/
index.ts
76 lines (64 loc) · 2.26 KB
/
index.ts
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { SUSPENSE_CACHE_URL } from '../cache';
import { handleRequest } from './handleRequest';
import {
adjustRequestForVercel,
handleImageResizingRequest,
patchFetch,
} from './utils';
import type { AsyncLocalStorage } from 'node:async_hooks';
declare const __NODE_ENV__: string;
declare const __CONFIG__: ProcessedVercelConfig;
declare const __BUILD_OUTPUT__: VercelBuildOutput;
declare const __BUILD_METADATA__: NextOnPagesBuildMetadata;
declare const __ALSes_PROMISE__: Promise<null | {
envAsyncLocalStorage: AsyncLocalStorage<unknown>;
requestContextAsyncLocalStorage: AsyncLocalStorage<unknown>;
}>;
export default {
async fetch(request, env, ctx) {
patchFetch();
const asyncLocalStorages = await __ALSes_PROMISE__;
if (!asyncLocalStorages) {
const reqUrl = new URL(request.url);
const noNodeJsCompatStaticPageRequest = await env.ASSETS.fetch(
`${reqUrl.protocol}//${reqUrl.host}/cdn-cgi/errors/no-nodejs_compat.html`,
);
const responseBody = noNodeJsCompatStaticPageRequest.ok
? noNodeJsCompatStaticPageRequest.body
: "Error: Could not access built-in Node.js modules. Please make sure that your Cloudflare Pages project has the 'nodejs_compat' compatibility flag set.";
return new Response(responseBody, { status: 503 });
}
const { envAsyncLocalStorage, requestContextAsyncLocalStorage } =
asyncLocalStorages;
return envAsyncLocalStorage.run(
// NOTE: The `SUSPENSE_CACHE_URL` is used to tell the Next.js Fetch Cache where to send requests.
{ ...env, NODE_ENV: __NODE_ENV__, SUSPENSE_CACHE_URL },
async () => {
return requestContextAsyncLocalStorage.run(
{ env, ctx, cf: request.cf },
async () => {
const url = new URL(request.url);
if (url.pathname.startsWith('/_next/image')) {
return handleImageResizingRequest(request, {
buildOutput: __BUILD_OUTPUT__,
assetsFetcher: env.ASSETS,
imagesConfig: __CONFIG__.images,
});
}
const adjustedRequest = adjustRequestForVercel(request);
return handleRequest(
{
request: adjustedRequest,
ctx,
assetsFetcher: env.ASSETS,
},
__CONFIG__,
__BUILD_OUTPUT__,
__BUILD_METADATA__,
);
},
);
},
);
},
} as ExportedHandler<{ ASSETS: Fetcher }>;