@@ -37,17 +37,49 @@ export async function getCloudflareContext<
37
37
CfProperties extends Record < string , unknown > = IncomingRequestCfProperties ,
38
38
Context = ExecutionContext ,
39
39
> ( ) : Promise < CloudflareContext < CfProperties , Context > > {
40
- const cloudflareContext = (
41
- globalThis as unknown as {
42
- [ cloudflareContextSymbol ] : CloudflareContext < CfProperties , Context > | undefined ;
43
- }
44
- ) [ cloudflareContextSymbol ] ;
40
+ const global = globalThis as unknown as {
41
+ [ cloudflareContextSymbol ] : CloudflareContext < CfProperties , Context > | undefined ;
42
+ } ;
43
+
44
+ const cloudflareContext = global [ cloudflareContextSymbol ] ;
45
45
46
46
if ( ! cloudflareContext ) {
47
- // TODO: cloudflareContext should always be present in production/preview, if not it means that this
48
- // is running under `next dev`, in this case use `getPlatformProxy` to return local proxies
49
- throw new Error ( "Cloudflare context is not defined!" ) ;
47
+ // the cloudflare context is initialized by the worker and is always present in production/preview,
48
+ // so, it not being present means that the application is running under `next dev`
49
+ return getCloudflareContextInNextDev ( ) ;
50
50
}
51
51
52
52
return cloudflareContext ;
53
53
}
54
+
55
+ const cloudflareContextInNextDevSymbol = Symbol . for ( "__next-dev/cloudflare-context__" ) ;
56
+
57
+ /**
58
+ * Gets a local proxy version of the cloudflare context (created using `getPlatformProxy`) when
59
+ * running in the standard next dev server (via `next dev`)
60
+ *
61
+ * @returns the local proxy version of the cloudflare context
62
+ */
63
+ async function getCloudflareContextInNextDev <
64
+ CfProperties extends Record < string , unknown > = IncomingRequestCfProperties ,
65
+ Context = ExecutionContext ,
66
+ > ( ) : Promise < CloudflareContext < CfProperties , Context > > {
67
+ const global = globalThis as unknown as {
68
+ [ cloudflareContextInNextDevSymbol ] : CloudflareContext < CfProperties , Context > | undefined ;
69
+ } ;
70
+
71
+ if ( ! global [ cloudflareContextInNextDevSymbol ] ) {
72
+ // Note: we need to add the webpackIgnore comment to the dynamic import because
73
+ // the next dev server transpiled modules on the fly but we don't want it to try
74
+ // to also transpile the wrangler code
75
+ const { getPlatformProxy } = await import ( /* webpackIgnore: true */ "wrangler" ) ;
76
+ const { env, cf, ctx } = await getPlatformProxy ( ) ;
77
+ global [ cloudflareContextInNextDevSymbol ] = {
78
+ env,
79
+ cf : cf as unknown as CfProperties ,
80
+ ctx : ctx as Context ,
81
+ } ;
82
+ }
83
+
84
+ return global [ cloudflareContextInNextDevSymbol ] ! ;
85
+ }
0 commit comments