Skip to content

Instantly share code, notes, and snippets.

@spacedawwwg
Last active July 26, 2022 18:15
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 spacedawwwg/ef19ab11d0a526b933bd7a0c8651d4cb to your computer and use it in GitHub Desktop.
Save spacedawwwg/ef19ab11d0a526b933bd7a0c8651d4cb to your computer and use it in GitHub Desktop.
Function for generating pages on Netlify using Vite Plugin SSR
// /package/functions/generatePage.ts
// `importBuild.cjs` enables us to bundle our serverless functions, see https://vite-plugin-ssr.com/importBuild.cjs
// File is generated within /package/dist/server/importBuild.cjs
import '../dist/server/importBuild.cjs';
import type { Handler, HandlerEvent } from '@netlify/functions';
import { builder } from '@netlify/functions';
import { fixPathSlashes } from '@unilever/utils-helpers';
import consola from 'consola';
import { renderPage } from 'vite-plugin-ssr';
export async function generatePage(event: HandlerEvent) {
const { path } = event;
const fixedPath = fixPathSlashes(path);
consola.info('Request to path:', path);
if (path !== fixedPath) {
return {
statusCode: 301,
headers: {
Location: fixedPath,
},
};
}
try {
const pageContextInit = { url: fixedPath };
const pageContext = await renderPage(pageContextInit);
const { httpResponse } = pageContext;
if (!httpResponse) {
throw Error;
}
const { body, statusCode, contentType } = httpResponse;
return {
statusCode,
headers: {
'Content-Type': contentType,
},
body,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
return {
statusCode: error.httpStatusCode || 500,
body: JSON.stringify(
{
error: error.message,
},
null,
2
),
};
}
}
const handler = builder(generatePage as Handler);
export { handler };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment