summaryrefslogtreecommitdiff
path: root/packages/integrations/vercel/src/serverless/entrypoint.ts
blob: 661e75f1cf987449db0f12fa3297bb867b1da698 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import type { SSRManifest } from 'astro';
import { applyPolyfills, NodeApp } from 'astro/app/node';
import type { IncomingMessage, ServerResponse } from 'node:http';
import {
	ASTRO_PATH_HEADER,
	ASTRO_PATH_PARAM,
	ASTRO_LOCALS_HEADER,
	ASTRO_MIDDLEWARE_SECRET_HEADER,
} from './adapter.js';

applyPolyfills();

export const createExports = (
	manifest: SSRManifest,
	{ middlewareSecret }: { middlewareSecret: string }
) => {
	const app = new NodeApp(manifest);
	const handler = async (req: IncomingMessage, res: ServerResponse) => {
		const url = new URL(`https://example.com${req.url}`);
		const clientAddress = req.headers['x-forwarded-for'] as string | undefined;
		const localsHeader = req.headers[ASTRO_LOCALS_HEADER];
		const middlewareSecretHeader = req.headers[ASTRO_MIDDLEWARE_SECRET_HEADER];
		const realPath = req.headers[ASTRO_PATH_HEADER] ?? url.searchParams.get(ASTRO_PATH_PARAM);
		if (typeof realPath === 'string') {
			req.url = realPath;
		}

		let locals = {};
		if (localsHeader) {
			if (middlewareSecretHeader !== middlewareSecret) {
				res.statusCode = 403;
				res.end('Forbidden');
				return;
			}
			locals =
				typeof localsHeader === 'string' ? JSON.parse(localsHeader) : JSON.parse(localsHeader[0]);
		}
		// hide the secret from the rest of user code
		delete req.headers[ASTRO_MIDDLEWARE_SECRET_HEADER];

		const webResponse = await app.render(req, { addCookieHeader: true, clientAddress, locals });
		await NodeApp.writeResponse(webResponse, res);
	};

	return { default: handler };
};

// HACK: prevent warning
// @astrojs-ssr-virtual-entry (22:23) "start" is not exported by "dist/serverless/entrypoint.js", imported by "@astrojs-ssr-virtual-entry".
export function start() {}