Skip to content

Commit

Permalink
fixup! enable getCloudflareContext to work in middlewares via a new…
Browse files Browse the repository at this point in the history
… `enableEdgeDevGetCloudflareContext` utility

create new `monkeyPatchVmModuleEdgeContext` commented function
  • Loading branch information
dario-piotrowicz committed Jan 20, 2025
1 parent 2754445 commit 836e157
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/cloudflare/src/api/cloudflare-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@ type RuntimeContext = Record<string, unknown> & {
* Note: this function should only be called inside the Next.js config file
*/
export async function enableEdgeDevGetCloudflareContext() {
await monkeyPatchVmModuleEdgeContext();
}

/**
* Next.js uses the Node.js vm module's `runInContext()` function to evaluate the edge functions
* in a runtime context that tries to simulate as accurately as possible the actual production runtime
* behavior, see: https://github.com/vercel/next.js/blob/9a1cd3/packages/next/src/server/web/sandbox/context.ts#L525-L527
*
* This function monkey-patches the Node.js `vm` module to override the `runInContext()` function so that the
* cloudflare context (which is created using the platform proxy obtained via wrangler's `getPlatformProxy` utility)
* can be added to the runtime context's `process.env` before the actual edge functions are evaluated.
*/
async function monkeyPatchVmModuleEdgeContext() {
const require = (
await import(/* webpackIgnore: true */ `${"__module".replaceAll("_", "")}`)
).default.createRequire(import.meta.url);
Expand Down

0 comments on commit 836e157

Please sign in to comment.