Skip to content

Commit 1a2b815

Browse files
authoredJan 28, 2025··
fix: make sure that the initOpenNextCloudflareForDev() logic runs only once (#293)
1 parent 94e5969 commit 1a2b815

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
 

‎.changeset/friendly-ears-ring.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
"@opennextjs/cloudflare": patch
3+
---
4+
5+
fix: make sure that the `initOpenNextCloudflareForDev()` logic runs only once
6+
7+
Currently calling `initOpenNextCloudflareForDev()` in the Next.js config file causes
8+
this initialization logic to run twice, consuming more resources and causing extra
9+
noise in the terminal logs, this change makes sure that the initialization logic
10+
is run only once instead

‎packages/cloudflare/src/api/cloudflare-context.ts

+19
Original file line numberDiff line numberDiff line change
@@ -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
*/
9191
export 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

Comments
 (0)
Please sign in to comment.