From 2d3afd16cd006bb247665cfcba3869e4953a647d Mon Sep 17 00:00:00 2001 From: Dario Piotrowicz Date: Sat, 7 Dec 2024 17:43:38 +0000 Subject: [PATCH] fix Next.js calling a non-bound waitUntil method --- .changeset/bright-vans-relate.md | 5 +++++ .../processVercelFunctions/dedupeEdgeFunctions.ts | 8 ++++++++ 2 files changed, 13 insertions(+) create mode 100644 .changeset/bright-vans-relate.md diff --git a/.changeset/bright-vans-relate.md b/.changeset/bright-vans-relate.md new file mode 100644 index 000000000..eb5ed9fe8 --- /dev/null +++ b/.changeset/bright-vans-relate.md @@ -0,0 +1,5 @@ +--- +'@cloudflare/next-on-pages': patch +--- + +fix Next.js calling a non-bound waitUntil method diff --git a/packages/next-on-pages/src/buildApplication/processVercelFunctions/dedupeEdgeFunctions.ts b/packages/next-on-pages/src/buildApplication/processVercelFunctions/dedupeEdgeFunctions.ts index 9ac5fae48..9fef0f723 100644 --- a/packages/next-on-pages/src/buildApplication/processVercelFunctions/dedupeEdgeFunctions.ts +++ b/packages/next-on-pages/src/buildApplication/processVercelFunctions/dedupeEdgeFunctions.ts @@ -631,6 +631,14 @@ function fixFunctionContents(contents: string): string { 'const { originalRequest = $1 } = $1$3', ); + // Next.js calls `waitUntil` without binding is to the context object, triggering the following error: `TypeError: Illegal invocation: function called with incorrect `this` reference` + // We need to update it so that uses a `waitUntil` bound to our `ctx` object + // (source https://github.com/vercel/next.js/blob/b7c271d7/packages/next/src/server/web/spec-extension/fetch-event.ts#L21) + contents = contents.replace( + /this\[(.)\]=(\w)\?{kind:"external",function:\2}:{kind:"internal",promises:\[(.*?)\]}/gm, + `this[$1]=e?{kind:"external",function:globalThis[Symbol.for('__cloudflare-request-context__')].ctx.waitUntil.bind(globalThis[Symbol.for('__cloudflare-request-context__')].ctx)}:{kind:"internal",promises:[$3]}`, + ); + return contents; }