@@ -89,13 +89,32 @@ export function getCloudflareContext<
89
89
* Note: this function should only be called inside the Next.js config file, and although async it doesn't need to be `await`ed
90
90
*/
91
91
export async function initOpenNextCloudflareForDev ( ) {
92
+ const shouldInitializationRun = shouldContextInitializationRun ( ) ;
93
+ if ( ! shouldInitializationRun ) return ;
94
+
92
95
const context = await getCloudflareContextFromWrangler ( ) ;
93
96
94
97
addCloudflareContextToNodejsGlobal ( context ) ;
95
98
96
99
await monkeyPatchVmModuleEdgeContext ( context ) ;
97
100
}
98
101
102
+ /**
103
+ * Next dev server imports the config file twice (in two different processes, making it hard to track),
104
+ * this causes the initialization to run twice as well, to keep things clean, not allocate extra
105
+ * resources (i.e. instantiate two miniflare instances) and avoid extra potential logs, it would be best
106
+ * to run the initialization only once, this function is used to try to make it so that it does, it returns
107
+ * a flag which indicates if the initialization should run in the current process or not.
108
+ *
109
+ * @returns boolean indicating if the initialization should run
110
+ */
111
+ function shouldContextInitializationRun ( ) : boolean {
112
+ // via debugging we've seen that AsyncLocalStorage is only set in one of the
113
+ // two processes so we're using it as the differentiator between the two
114
+ const AsyncLocalStorage = ( globalThis as unknown as { AsyncLocalStorage ?: unknown } ) [ "AsyncLocalStorage" ] ;
115
+ return ! ! AsyncLocalStorage ;
116
+ }
117
+
99
118
/**
100
119
* Adds the cloudflare context to the global scope in which the Next.js dev node.js process runs in, enabling
101
120
* future calls to `getCloudflareContext` to retrieve and return such context
0 commit comments