summaryrefslogtreecommitdiff
path: root/packages/integrations/netlify/src/netlify-edge-functions.ts
blob: 8011e2b1be43a2eee76f027d2dec5c1bd8a5fdce (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
import type { SSRManifest } from 'astro';
import type { Context } from '@netlify/edge-functions';
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;
		}
		if (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);
			if (app.setCookieHeaders) {
				for (const setCookieHeader of app.setCookieHeaders(response)) {
					response.headers.append('Set-Cookie', setCookieHeader);
				}
			}
			return response;
		}

		return new Response(null, {
			status: 404,
			statusText: 'Not found',
		});
	};

	return { default: handler };
}