Skip to content

Commit db0a4fb

Browse files
fixup! enable getCloudflareContext to work in middlewares via a new enableEdgeDevGetCloudflareContext utility
amend `monkeyPatchVmModuleEdgeContext`
1 parent 836e157 commit db0a4fb

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

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

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,19 +112,22 @@ type RuntimeContext = Record<string, unknown> & {
112112
* Note: this function should only be called inside the Next.js config file
113113
*/
114114
export async function enableEdgeDevGetCloudflareContext() {
115-
await monkeyPatchVmModuleEdgeContext();
115+
const context = await getCloudflareContextFromWrangler();
116+
117+
await monkeyPatchVmModuleEdgeContext(context);
116118
}
117119

118120
/**
119-
* Next.js uses the Node.js vm module's `runInContext()` function to evaluate the edge functions
121+
* Next.js uses the Node.js vm module's `runInContext()` function to evaluate edge functions
120122
* in a runtime context that tries to simulate as accurately as possible the actual production runtime
121123
* behavior, see: https://github.com/vercel/next.js/blob/9a1cd3/packages/next/src/server/web/sandbox/context.ts#L525-L527
122124
*
123125
* This function monkey-patches the Node.js `vm` module to override the `runInContext()` function so that the
124-
* cloudflare context (which is created using the platform proxy obtained via wrangler's `getPlatformProxy` utility)
125-
* can be added to the runtime context's `process.env` before the actual edge functions are evaluated.
126+
* cloudflare context is added to the runtime context's global scope before edge functions are evaluated
127+
*
128+
* @param cloudflareContext the cloudflare context to patch onto the runtime context global scope
126129
*/
127-
async function monkeyPatchVmModuleEdgeContext() {
130+
async function monkeyPatchVmModuleEdgeContext(cloudflareContext: CloudflareContext<CfProperties, Context>) {
128131
const require = (
129132
await import(/* webpackIgnore: true */ `${"__module".replaceAll("_", "")}`)
130133
).default.createRequire(import.meta.url);
@@ -134,15 +137,13 @@ async function monkeyPatchVmModuleEdgeContext() {
134137

135138
const originalRunInContext = vmModule.runInContext.bind(vmModule);
136139

137-
const context = await getCloudflareContextFromWrangler();
138-
139140
vmModule.runInContext = (
140141
code: string,
141142
contextifiedObject: Context,
142143
options?: RunningCodeOptions | string
143144
) => {
144145
const runtimeContext = contextifiedObject as RuntimeContext;
145-
runtimeContext[cloudflareContextInNextDevSymbol] ??= context;
146+
runtimeContext[cloudflareContextInNextDevSymbol] ??= cloudflareContext;
146147
return originalRunInContext(code, contextifiedObject, options);
147148
};
148149
}

0 commit comments

Comments
 (0)