@@ -35,14 +35,14 @@ export type CloudflareContext<
3535const cloudflareContextSymbol = Symbol . for ( "__cloudflare-context__" ) ;
3636
3737/**
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
4039 */
4140type InternalGlobalThis <
4241 CfProperties extends Record < string , unknown > = IncomingRequestCfProperties ,
4342 Context = ExecutionContext ,
4443> = typeof globalThis & {
4544 [ cloudflareContextSymbol ] : CloudflareContext < CfProperties , Context > | undefined ;
45+ __NEXT_DATA__ : Record < string , unknown > ;
4646} ;
4747
4848/**
@@ -59,6 +59,20 @@ export function getCloudflareContext<
5959 const cloudflareContext = global [ cloudflareContextSymbol ] ;
6060
6161 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+
6276 // the cloudflare context is initialized by the worker and is always present in production/preview
6377 // during local development (`next dev`) it might be missing only if the developers hasn't called
6478 // the `initOpenNextCloudflareForDev` function in their Next.js config file
0 commit comments