Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/brob/demo-eleventy-serverless


https://github.com/brob/demo-eleventy-serverless

Last synced: 7 days ago
JSON representation

Awesome Lists containing this project

README

        

# Eleventy Serverless Demo

Running Eleventy inside of a Netlify serverless function.

## Run it

### Locally

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

### Production

1. [View the demo on Netlify](https://demo-eleventy-serverless.netlify.app)
1. [Deploy your own to Netlify](https://app.netlify.com/start/deploy?repository=https://github.com/11ty/demo-eleventy-serverless)

## How it works

_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.

2. 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`).

```js
const { EleventyServerlessBundlerPlugin } = require("@11ty/eleventy");

module.exports = function(eleventyConfig) {
eleventyConfig.addPlugin(EleventyServerlessBundlerPlugin, {
name: "serverless",
functionsDir: "./netlify/functions/",
});
};
```

3. `./netlify/functions/serverless/index.js` is the boilerplate serverless function code. You’ll need to create this yourself.

```js
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);
```

4. Add entries to your `.gitignore` file so the bundles aren’t checked into your repository.

```
netlify/functions/serverless/*
!netlify/functions/serverless/index.js
```