Skip to content

Instantly share code, notes, and snippets.

@gabidobo
Created March 3, 2023 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabidobo/c7ead7f55caaabf2ae20e8b851a18260 to your computer and use it in GitHub Desktop.
Save gabidobo/c7ead7f55caaabf2ae20e8b851a18260 to your computer and use it in GitHub Desktop.
Example serverless handler to deploy Eleventy Serverless to Lambda@Edge
const { EleventyServerless } = require("@11ty/eleventy");
const querystring = require("querystring");
async function handler(event) {
const { request } = event.Records[0].cf;
const path = `${request.uri}${request.uri.endsWith("/") ? "" : "/"}`;
const query = querystring.parse(request.querystring);
let elev = new EleventyServerless("edge", {
path,
query,
functionsDir: "./",
});
try {
let [page] = await elev.getOutput();
return {
status: "200",
headers: {
"cache-control": [
{
key: "Cache-Control",
value: "max-age=0",
},
],
"content-type": [
{
key: "Content-Type",
value: "text/html; charset=UTF-8",
},
],
},
body: page.content,
};
} catch (error) {
if (elev.isServerlessUrl(event.path)) {
console.log("Serverless Error:", error);
}
return {
status: `${error.httpStatusCode || 500}`,
headers: {
"cache-control": [
{
key: "Cache-Control",
value: "max-age=0",
},
],
"content-type": [
{
key: "Content-Type",
value: "text/html; charset=UTF-8",
},
],
},
body: JSON.stringify(
{
error: error.message,
},
null,
2
),
};
}
}
exports.handler = handler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment