summaryrefslogtreecommitdiff
path: root/packages/integrations/netlify/src/netlify-edge-functions.ts
blob: 5e95035a6a1f4e1b09bec46a89fdcf10677f4f59 (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
import type { Context } from '@netlify/edge-functions';
import type { SSRManifest } from 'astro';
import { App } from 'astro/app';

const clientAddressSymbol = Symbol.for('astro.clientAddress');

export function createExports(manifest: SSRManifest) {
	const app = new App(manifest);

	const handler = async (request: Request, context: Context): Promise<Response | void> => {
		const url = new URL(request.url);

		// If this matches a static asset, just return and Netlify will forward it
		// to its static asset handler.
		if (manifest.assets.has(url.pathname)) {
			return;
		}
		const routeData = app.match(request);
		const ip =
			request.headers.get('x-nf-client-connection-ip') ||
			context?.ip ||
			(context as any)?.remoteAddr?.hostname;
		Reflect.set(request, clientAddressSymbol, ip);
		const response = await app.render(request, routeData);
		if (app.setCookieHeaders) {
			for (const setCookieHeader of app.setCookieHeaders(response)) {
				response.headers.append('Set-Cookie', setCookieHeader);
			}
		}
		return response;
	};

	return { default: handler };
}