@@ -89,13 +89,32 @@ export function getCloudflareContext<
8989 * Note: this function should only be called inside the Next.js config file, and although async it doesn't need to be `await`ed
9090 */
9191export async function initOpenNextCloudflareForDev ( ) {
92+ const shouldInitializationRun = shouldContextInitializationRun ( ) ;
93+ if ( ! shouldInitializationRun ) return ;
94+
9295 const context = await getCloudflareContextFromWrangler ( ) ;
9396
9497 addCloudflareContextToNodejsGlobal ( context ) ;
9598
9699 await monkeyPatchVmModuleEdgeContext ( context ) ;
97100}
98101
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+
99118/**
100119 * Adds the cloudflare context to the global scope in which the Next.js dev node.js process runs in, enabling
101120 * future calls to `getCloudflareContext` to retrieve and return such context
0 commit comments