@@ -35,14 +35,14 @@ export type CloudflareContext<
35
35
const cloudflareContextSymbol = Symbol . for ( "__cloudflare-context__" ) ;
36
36
37
37
/**
38
- * `globalThis` override for internal usage (simply the standard `globalThis`) enhanced with
39
- * a property indexed by the `cloudflareContextSymbol`
38
+ * `globalThis` override for internal usage
40
39
*/
41
40
type InternalGlobalThis <
42
41
CfProperties extends Record < string , unknown > = IncomingRequestCfProperties ,
43
42
Context = ExecutionContext ,
44
43
> = typeof globalThis & {
45
44
[ cloudflareContextSymbol ] : CloudflareContext < CfProperties , Context > | undefined ;
45
+ __NEXT_DATA__ : Record < string , unknown > ;
46
46
} ;
47
47
48
48
/**
@@ -59,6 +59,20 @@ export function getCloudflareContext<
59
59
const cloudflareContext = global [ cloudflareContextSymbol ] ;
60
60
61
61
if ( ! cloudflareContext ) {
62
+ // For SSG Next.js creates (jest) workers that run in parallel, those don't get the current global
63
+ // state so they can't get access to the cloudflare context, unfortunately there isn't anything we
64
+ // can do about this, so the only solution is to error asking the developer to opt-out of SSG
65
+ // Next.js sets globalThis.__NEXT_DATA__.nextExport to true for the worker, so we can use that to detect
66
+ // that the route is being SSG'd (source: https://github.com/vercel/next.js/blob/4e394608423/packages/next/src/export/worker.ts#L55-L57)
67
+ if ( global . __NEXT_DATA__ ?. nextExport === true ) {
68
+ throw new Error (
69
+ `\n\nERROR: \`getCloudflareContext\` has been called in a static route` +
70
+ ` that is not allowed, please either avoid calling \`getCloudflareContext\`` +
71
+ ` in the route or make the route non static (for example by exporting the` +
72
+ ` \`dynamic\` route segment config set to \`'force-dynamic'\`.\n`
73
+ ) ;
74
+ }
75
+
62
76
// the cloudflare context is initialized by the worker and is always present in production/preview
63
77
// during local development (`next dev`) it might be missing only if the developers hasn't called
64
78
// the `initOpenNextCloudflareForDev` function in their Next.js config file
0 commit comments