Running Eleventy inside of a Netlify serverless function.
Read the documentation on 11ty.dev
- Run
npm install
- Run
npm start
- Navigate to the demo URL at
http://localhost:8080/
Read the documentation on 11ty.dev
This requires Eleventy 1.0 Canary 30 or newer. Be careful here, Canary is considered unstable! Don’t use it in production.
- Use Eleventy as normal.
- In this demo
src
is the input directory. - For this demo we include one Nunjucks template (
./src/sample-nunjucks.njk
), a Global Data file, an include template, and an Eleventy layout. - To make any template file into a serverless template, modify your
permalink
object to include aserverless
key.
- In this demo
---
permalink:
build: "/"
serverless: "/:slug/"
---
This makes eleventy.path.slug
(the slug
name matches :slug
) available in global data for use in your serverless templates.
- Add the bundler plugin to your Eleventy configuration file (probably
.eleventy.js
). The name you pass into the plugin (we useserverless
in this example) should match the key inside of your template’spermalink
object (permalink.serverless
).
const { EleventyServerlessBundlerPlugin } = require("@11ty/eleventy");
module.exports = function(eleventyConfig) {
eleventyConfig.addPlugin(EleventyServerlessBundlerPlugin, {
name: "serverless",
functionsDir: "./netlify/functions/",
});
};
./netlify/functions/serverless/index.js
is the boilerplate serverless function code. You’ll need to create this yourself.
const { EleventyServerless } = require("@11ty/eleventy");
const { builder } = require("@netlify/functions");
// For the bundler (auto-generated by the plugin)
require("./eleventy-bundler-modules.js");
async function handler (event) {
let elev = new EleventyServerless("serverless", event.path, {
inputDir: "src",
functionsDir: "netlify/functions/",
query: event.queryStringParameters,
});
try {
return {
statusCode: 200,
headers: {
"Content-Type": "text/html; charset=UTF-8"
},
body: await elev.render()
};
} catch (error) {
return {
statusCode: error.httpStatusCode || 500,
body: JSON.stringify({
error: error.message
})
};
}
}
// Netlify On-demand Builder (runs on first request only)
exports.handler = builder(handler);
- Add entries to your
.gitignore
file so the bundles aren’t checked into your repository.
netlify/functions/serverless/**
!netlify/functions/serverless/index.js