From 91dbdd365e808852c3db3f25f3e1b81f83f69e8f Mon Sep 17 00:00:00 2001 From: Ramazan Elsunkaev Date: Fri, 5 Dec 2025 16:55:25 -0700 Subject: [PATCH] fix: detect Turbopack builds and set TURBOPACK env accordingly When building with Turbopack (default in Next.js 16), the standalone output only includes *-turbo.runtime.prod.js files, not the webpack variants. The previous behavior of unconditionally setting TURBOPACK=false caused runtime errors because module.compiled.js would try to load non-existent runtime files. This change: - Detects Turbopack builds by checking if only turbo runtime files exist in the traced files - Sets TURBOPACK=true for Turbopack builds so the correct runtime is loaded - Keeps TURBOPACK=false for Webpack builds (existing behavior) Fixes runtime error: Cannot find module 'next/dist/compiled/next-server/pages.runtime.prod.js' --- .../src/build/patch/patches/patchEnvVar.ts | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/open-next/src/build/patch/patches/patchEnvVar.ts b/packages/open-next/src/build/patch/patches/patchEnvVar.ts index c34e9b4d1..dd6378721 100644 --- a/packages/open-next/src/build/patch/patches/patchEnvVar.ts +++ b/packages/open-next/src/build/patch/patches/patchEnvVar.ts @@ -1,5 +1,5 @@ -import { createPatchCode } from "../astCodePatcher.js"; -import type { CodePatcher } from "../codePatcher"; +import { createPatchCode, patchCode } from "../astCodePatcher.js"; +import type { CodePatcher, PatchCodeFn } from "../codePatcher.js"; /** * Creates a rule to replace `process.env.${envVar}` by `value` in the condition of if statements @@ -21,6 +21,22 @@ fix: '${value}' `; +function isTurbopackBuild(tracedFiles: string[]): boolean { + const hasTurboRuntime = tracedFiles.some((file) => + /-turbo[.-].*\.runtime\.(prod|dev)\.js$/.test(file), + ); + const hasNonTurboRuntime = tracedFiles.some( + (file) => + /\.runtime\.(prod|dev)\.js$/.test(file) && !/-turbo[.-]/.test(file), + ); + return hasTurboRuntime && !hasNonTurboRuntime; +} + +const createTurbopackPatch: PatchCodeFn = async ({ code, tracedFiles }) => { + const value = isTurbopackBuild(tracedFiles) ? "true" : "false"; + return patchCode(code, envVarRuleCreator("TURBOPACK", value)); +}; + export const patchEnvVars: CodePatcher = { name: "patch-env-vars", patches: [ @@ -39,12 +55,12 @@ export const patchEnvVars: CodePatcher = { contentFilter: /process\.env\.NODE_ENV/, patchCode: createPatchCode(envVarRuleCreator("NODE_ENV", '"production"')), }, - // This patch will set `TURBOPACK` env to false to avoid loading turbopack related deps at runtime + // Turbopack builds only include *-turbo.runtime.prod.js files, so we detect and set accordingly { versions: ">=15.0.0", pathFilter: /module\.compiled\.js$/, contentFilter: /process\.env\.TURBOPACK/, - patchCode: createPatchCode(envVarRuleCreator("TURBOPACK", "false")), + patchCode: createTurbopackPatch, }, ], };