@@ -37,17 +37,46 @@ 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
+ const { getPlatformProxy } = await import ( "wrangler" ) ;
73
+ const { env, cf, ctx } = await getPlatformProxy ( ) ;
74
+ global [ cloudflareContextInNextDevSymbol ] = {
75
+ env,
76
+ cf : cf as unknown as CfProperties ,
77
+ ctx : ctx as Context ,
78
+ } ;
79
+ }
80
+
81
+ return global [ cloudflareContextInNextDevSymbol ] ! ;
82
+ }
0 commit comments