UNPKG

@astrojs/netlify

Version:
54 lines (53 loc) 2.1 kB
import "./polyfill.js"; import { App } from "astro/app"; import { setGetEnv } from "astro/env/setup"; setGetEnv((key) => process.env[key]); const clientAddressSymbol = Symbol.for("astro.clientAddress"); const createExports = (manifest, { middlewareSecret }) => { const app = new App(manifest); function createHandler(integrationConfig) { return async function handler(request, context) { const routeData = app.match(request); if (!routeData && typeof integrationConfig.notFoundContent !== "undefined") { return new Response(integrationConfig.notFoundContent, { status: 404, headers: { "Content-Type": "text/html; charset=utf-8" } }); } Reflect.set(request, clientAddressSymbol, context.ip); let locals = {}; const astroLocalsHeader = request.headers.get("x-astro-locals"); const middlewareSecretHeader = request.headers.get("x-astro-middleware-secret"); if (astroLocalsHeader) { if (middlewareSecretHeader !== middlewareSecret) { return new Response("Forbidden", { status: 403 }); } request.headers.delete("x-astro-middleware-secret"); locals = JSON.parse(astroLocalsHeader); } 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) { const isCacheableMethod = ["GET", "HEAD"].includes(request.method); const hasCacheControl = [ "Cache-Control", "CDN-Cache-Control", "Netlify-CDN-Cache-Control" ].some((header) => response.headers.has(header)); if (isCacheableMethod && !hasCacheControl) { response.headers.append("CDN-Cache-Control", "public, max-age=31536000, must-revalidate"); } } return response; }; } return { default: createHandler }; }; export { createExports };