diff --git a/packages/open-next/src/build/edge/createEdgeBundle.ts b/packages/open-next/src/build/edge/createEdgeBundle.ts index b53177689..5ba1fe502 100644 --- a/packages/open-next/src/build/edge/createEdgeBundle.ts +++ b/packages/open-next/src/build/edge/createEdgeBundle.ts @@ -130,6 +130,27 @@ globalThis.Buffer = Buffer; import {AsyncLocalStorage} from "node:async_hooks"; globalThis.AsyncLocalStorage = AsyncLocalStorage; + +${ + "" + /** + * Next.js sets this `__import_unsupported` on `globalThis` (with `configurable: false`): + * https://github.com/vercel/next.js/blob/5b7833e3/packages/next/src/server/web/globals.ts#L94-L98 + * + * It does so in both the middleware and the main server, so if the middleware runs in the same place + * as the main handler this code gets run twice triggering a runtime error. + * + * For this reason we need to patch `Object.defineProperty` to avoid this issue. + */ +} +const defaultDefineProperty = Object.defineProperty; +Object.defineProperty = function(o, p, a) { + if(p=== '__import_unsupported' && Boolean(globalThis.__import_unsupported)) { + return; + } + return defaultDefineProperty(o, p, a); +}; + ${ isInCloudfare ? "" @@ -137,14 +158,6 @@ globalThis.AsyncLocalStorage = AsyncLocalStorage; const require = (await import("node:module")).createRequire(import.meta.url); const __filename = (await import("node:url")).fileURLToPath(import.meta.url); const __dirname = (await import("node:path")).dirname(__filename); - - const defaultDefineProperty = Object.defineProperty; - Object.defineProperty = function(o, p, a) { - if(p=== '__import_unsupported' && Boolean(globalThis.__import_unsupported)) { - return; - } - return defaultDefineProperty(o, p, a); - }; ` } ${additionalInject ?? ""}