diff options
author | 2023-12-17 16:44:09 +0100 | |
---|---|---|
committer | 2023-12-17 16:44:09 +0100 | |
commit | 94dcbfed0607d037c591001b5484de74661c90a2 (patch) | |
tree | 7ecfac03e71d61da8cf9fcf935291fc57e005432 /packages/integrations/netlify/src/ssr-function.ts | |
parent | acb92412634176ae32dfbe186bf430055408e8fd (diff) | |
download | astro-94dcbfed0607d037c591001b5484de74661c90a2.tar.gz astro-94dcbfed0607d037c591001b5484de74661c90a2.tar.zst astro-94dcbfed0607d037c591001b5484de74661c90a2.zip |
feat(netlify): Netlify Adapter v4 (#84)
Co-authored-by: Matt Kane <m@mk.gg>
Co-authored-by: Jacklyn <70537879+jacklyn-net@users.noreply.github.com>
Co-authored-by: Arsh <69170106+lilnasy@users.noreply.github.com>
Co-authored-by: Emanuele Stoppa <602478+ematipico@users.noreply.github.com>
Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
Diffstat (limited to 'packages/integrations/netlify/src/ssr-function.ts')
-rw-r--r-- | packages/integrations/netlify/src/ssr-function.ts | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/packages/integrations/netlify/src/ssr-function.ts b/packages/integrations/netlify/src/ssr-function.ts new file mode 100644 index 000000000..c2b6ed14c --- /dev/null +++ b/packages/integrations/netlify/src/ssr-function.ts @@ -0,0 +1,56 @@ +import type { Context } from '@netlify/functions'; +import type { SSRManifest } from 'astro'; +import { App } from 'astro/app'; +import { applyPolyfills } from 'astro/app/node'; + +applyPolyfills(); + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface Args {} + +const clientAddressSymbol = Symbol.for('astro.clientAddress'); + +export const createExports = (manifest: SSRManifest, _args: Args) => { + const app = new App(manifest); + + function createHandler(integrationConfig: { cacheOnDemandPages: boolean }) { + return async function handler(request: Request, context: Context) { + const routeData = app.match(request); + Reflect.set(request, clientAddressSymbol, context.ip); + + let locals: Record<string, unknown> = {}; + + if (request.headers.has('x-astro-locals')) { + locals = JSON.parse(request.headers.get('x-astro-locals')!); + } + + locals.netlify = { context }; + + const response = await app.render(request, routeData, locals); + + if (app.setCookieHeaders) { + for (const setCookieHeader of app.setCookieHeaders(response)) { + response.headers.append('Set-Cookie', setCookieHeader); + } + } + + if (integrationConfig.cacheOnDemandPages) { + // any user-provided Cache-Control headers take precedence + const hasCacheControl = [ + 'Cache-Control', + 'CDN-Cache-Control', + 'Netlify-CDN-Cache-Control', + ].some((header) => response.headers.has(header)); + + if (!hasCacheControl) { + // caches this page for up to a year + response.headers.append('CDN-Cache-Control', 'public, max-age=31536000, must-revalidate'); + } + } + + return response; + }; + } + + return { default: createHandler }; +}; |