Eleventy Serverless Demo

Running Eleventy inside of a Netlify serverless function.

Read the documentation on 11ty.dev

Run it

Locally

  1. Run npm install
  2. Run npm start
  3. Navigate to the demo URL at http://localhost:8080/

Production

  1. View the demo on Netlify
  2. Deploy your own to Netlify

How it works

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.

  1. 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 a serverless key.
---
permalink:
  build: "/"
  serverless: "/:slug/"
---

This makes eleventy.path.slug (the slug name matches :slug) available in global data for use in your serverless templates.

  1. Add the bundler plugin to your Eleventy configuration file (probably .eleventy.js). The name you pass into the plugin (we use serverless in this example) should match the key inside of your template’s permalink object (permalink.serverless).
const { EleventyServerlessBundlerPlugin } = require("@11ty/eleventy");

module.exports = function(eleventyConfig) {
	eleventyConfig.addPlugin(EleventyServerlessBundlerPlugin, {
		name: "serverless",
		functionsDir: "./netlify/functions/",
	});
};
  1. ./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);
  1. Add entries to your .gitignore file so the bundles aren’t checked into your repository.
netlify/functions/serverless/**
!netlify/functions/serverless/index.js