Unverified Commit 0e973f71 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Add experimental.runtimeServerDeploymentId (#86865)

If this is set, `process.env.NEXT_DEPLOYMENT_ID` is available at runtime, and we don't need to inline the build-time value into the build output.

This is currently true for Node.js routes, and will also be the case for edge routes once https://github.com/vercel/next.js/pull/86769 is merged.

`experimental.runtimeServerDeploymentId` defaults to true when deploying on Vercel and `NEXT_DEPLOYMENT_ID` is set.

- [x] Perform `config.deploymentId = process.env.NEXT_DEPLOYMENT_ID` in the right places in the server

This brings us to this state regarding the deployoment ids in the output (notice the exclusion field):

<img width="628" height="323" alt="Bildschirmfoto 2025-12-05 um 21 17 53" src="https://github.com/user-attachments/assets/6e35997f-3f81-4da4-880e-d1d1984f7272" />
parent 3c2fc61b
......@@ -967,5 +967,7 @@
"966": "Expected process.nextTick to reject invalid arguments",
"967": "The key \"%s\" under \"env\" in %sconfig is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed",
"968": "Invariant: getNextConfigEdge must only be called in edge runtime",
"969": "Invariant: nextConfig couldn't be loaded"
"969": "Invariant: nextConfig couldn't be loaded",
"970": "process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled",
"971": "The NEXT_DEPLOYMENT_ID environment variable value \"%s\" does not match the provided deploymentId \"%s\" in the config."
}
......@@ -61,12 +61,12 @@ interface SerializedDefineEnv {
* Serializes the DefineEnv config so that it can be inserted into the code by Webpack/Turbopack, JSON stringifies each value.
*/
function serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {
const defineEnvStringified: SerializedDefineEnv = {}
for (const key in defineEnv) {
const value = defineEnv[key]
defineEnvStringified[key] = JSON.stringify(value)
}
const defineEnvStringified: SerializedDefineEnv = Object.fromEntries(
Object.entries(defineEnv).map(([key, value]) => [
key,
JSON.stringify(value),
])
)
return defineEnvStringified
}
......@@ -167,9 +167,24 @@ export function getDefineEnv({
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie
? false
: config.deploymentId || false,
...(isClient
? {
// TODO use `globalThis.NEXT_DEPLOYMENT_ID` on client to still support accessing
// process.env.NEXT_DEPLOYMENT_ID in userland
'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie
? false
: config.deploymentId || false,
}
: config.experimental?.runtimeServerDeploymentId
? {
// Don't inline at all, keep process.env.NEXT_DEPLOYMENT_ID as is
}
: {
'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie
? false
: config.deploymentId || false,
}),
// Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment
// variable to the client.
'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':
......@@ -372,8 +387,10 @@ export function getDefineEnv({
for (const key in nextConfigEnv) {
serializedDefineEnv[key] = safeKey(key)
}
for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {
serializedDefineEnv[key] = safeKey(key)
if (!config.experimental.runtimeServerDeploymentId) {
for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {
serializedDefineEnv[key] = safeKey(key)
}
}
}
......
......@@ -989,7 +989,7 @@ export default async function build(
// when using compile mode static env isn't inlined so we
// need to populate in normal runtime env
if (isCompileMode || isGenerateMode) {
populateStaticEnv(config)
populateStaticEnv(config, config.deploymentId)
}
const customRoutes: CustomRoutes = await nextBuildSpan
......
......@@ -170,6 +170,7 @@ export async function handler(
nextConfig,
parsedUrl,
interceptionRoutePatterns,
deploymentId,
} = prepareResult
const normalizedSrcPage = normalizeAppPath(srcPage)
......@@ -559,7 +560,7 @@ export async function handler(
trailingSlash: nextConfig.trailingSlash,
images: nextConfig.images,
previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId,
deploymentId: deploymentId,
enableTainting: nextConfig.experimental.taint,
htmlLimitedBots: nextConfig.htmlLimitedBots,
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
......
......@@ -81,6 +81,7 @@ async function requestHandler(
resolvedPathname,
interceptionRoutePatterns,
routerServerContext,
deploymentId,
} = prepareResult
// Initialize the cache handlers interface.
......@@ -137,7 +138,7 @@ async function requestHandler(
trailingSlash: nextConfig.trailingSlash,
images: nextConfig.images,
previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId,
deploymentId,
enableTainting: nextConfig.experimental.taint,
htmlLimitedBots: nextConfig.htmlLimitedBots,
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
......
......@@ -17,7 +17,7 @@ export async function inlineStaticEnv({
config: NextConfigComplete
}) {
const nextConfigEnv = getNextConfigEnv(config)
const staticEnv = getStaticEnv(config)
const staticEnv = getStaticEnv(config, config.deploymentId)
const serverDir = path.join(distDir, 'server')
const serverChunks = await glob('**/*.{js,json,js.map}', {
......
......@@ -53,22 +53,26 @@ export function getNextConfigEnv(
return defineEnv
}
export function getStaticEnv(config: NextConfigComplete | NextConfigRuntime) {
export function getStaticEnv(
config: NextConfigComplete | NextConfigRuntime,
deploymentId: string
) {
const staticEnv: Record<string, string | undefined> = {
...getNextPublicEnvironmentVariables(),
...getNextConfigEnv(config),
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || '',
'process.env.NEXT_DEPLOYMENT_ID': deploymentId,
}
return staticEnv
}
export function populateStaticEnv(
config: NextConfigComplete | NextConfigRuntime
config: NextConfigComplete | NextConfigRuntime,
deploymentId: string
) {
// since inlining comes after static generation we need
// to ensure this value is assigned to process env so it
// can still be accessed
const staticEnv = getStaticEnv(config)
const staticEnv = getStaticEnv(config, deploymentId)
for (const key in staticEnv) {
const innerKey = key.split('.').pop() || ''
if (!process.env[innerKey]) {
......
......@@ -447,6 +447,24 @@ export default abstract class Server<
// TODO: should conf be normalized to prevent missing
// values from causing issues as this can be user provided
this.nextConfig = conf as NextConfigRuntime
let deploymentId
if (this.nextConfig.experimental.runtimeServerDeploymentId) {
if (!process.env.NEXT_DEPLOYMENT_ID) {
throw new Error(
'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'
)
}
deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else {
let id = this.nextConfig.experimental.useSkewCookie
? ''
: this.nextConfig.deploymentId || ''
deploymentId = id
process.env.NEXT_DEPLOYMENT_ID = id
}
this.hostname = hostname
if (this.hostname) {
// we format the hostname so that it can be fetched
......@@ -501,13 +519,12 @@ export default abstract class Server<
}
this.nextFontManifest = this.getNextFontManifest()
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''
this.renderOpts = {
dir: this.dir,
supportsDynamicResponse: true,
trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.deploymentId,
deploymentId: deploymentId,
poweredByHeader: this.nextConfig.poweredByHeader,
generateEtags,
previewProps: this.getPrerenderManifest().preview,
......
......@@ -347,6 +347,7 @@ export const experimentalSchema = {
.optional(),
lockDistDir: z.boolean().optional(),
hideLogsAfterAbort: z.boolean().optional(),
runtimeServerDeploymentId: z.boolean().optional(),
}
export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
......
......@@ -836,6 +836,14 @@ export interface ExperimentalConfig {
* @default false
*/
hideLogsAfterAbort?: boolean
/**
* Whether `process.env.NEXT_DEPLOYMENT_ID` is available at runtime in the server (and `next
* build` doesn't need to embed the deployment ID value into the build output).
*
* @default false
*/
runtimeServerDeploymentId?: boolean
}
export type ExportPathMap = {
......@@ -1586,8 +1594,8 @@ export async function normalizeConfig(phase: string, config: any) {
// };
// };
export interface NextConfigRuntime {
// TODO remove in some cases
deploymentId: NextConfigComplete['deploymentId']
// Can be undefined, particularly when experimental.runtimeServerDeploymentId is true
deploymentId?: NextConfigComplete['deploymentId']
configFileName?: string
// Should only be included when using isExperimentalCompile
......@@ -1652,6 +1660,7 @@ export interface NextConfigRuntime {
| 'proxyClientMaxBodySize'
| 'proxyTimeout'
| 'testProxy'
| 'runtimeServerDeploymentId'
> & {
// Pick on @internal fields generates invalid .d.ts files
/** @internal */
......@@ -1706,6 +1715,7 @@ export function getNextConfigRuntime(
proxyClientMaxBodySize: ex.proxyClientMaxBodySize,
proxyTimeout: ex.proxyTimeout,
testProxy: ex.testProxy,
runtimeServerDeploymentId: ex.runtimeServerDeploymentId,
trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile,
......@@ -1713,7 +1723,9 @@ export function getNextConfigRuntime(
: {}
let runtimeConfig: Requiredish<NextConfigRuntime> = {
deploymentId: config.deploymentId,
deploymentId: config.experimental.runtimeServerDeploymentId
? ''
: config.deploymentId,
configFileName: undefined,
env: undefined,
......
......@@ -370,7 +370,7 @@ function assignDefaultsAndValidate(
}
// ensure correct default is set for api-resolver revalidate handling
if (!result.experimental?.trustHostHeader && ciEnvironment.hasNextSupport) {
if (!result.experimental.trustHostHeader && ciEnvironment.hasNextSupport) {
result.experimental.trustHostHeader = true
}
......@@ -916,6 +916,23 @@ function assignDefaultsAndValidate(
}
}
if (
result.experimental.runtimeServerDeploymentId == null &&
phase === PHASE_PRODUCTION_BUILD &&
ciEnvironment.hasNextSupport &&
process.env.NEXT_DEPLOYMENT_ID
) {
if (
result.deploymentId != null &&
result.deploymentId !== process.env.NEXT_DEPLOYMENT_ID
) {
throw new Error(
`The NEXT_DEPLOYMENT_ID environment variable value "${process.env.NEXT_DEPLOYMENT_ID}" does not match the provided deploymentId "${result.deploymentId}" in the config.`
)
}
result.experimental.runtimeServerDeploymentId = true
}
// only leverage deploymentId
if (process.env.NEXT_DEPLOYMENT_ID) {
result.deploymentId = process.env.NEXT_DEPLOYMENT_ID
......
......@@ -295,9 +295,6 @@ export default class NextNodeServer extends BaseServer<
if (this.renderOpts.nextScriptWorkers) {
process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)
}
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.experimental.useSkewCookie
? ''
: this.nextConfig.deploymentId || ''
if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode)
......@@ -356,7 +353,7 @@ export default class NextNodeServer extends BaseServer<
// when using compile mode static env isn't inlined so we
// need to populate in normal runtime env
if (this.renderOpts.isExperimentalCompile) {
populateStaticEnv(this.nextConfig)
populateStaticEnv(this.nextConfig, this.renderOpts.deploymentId || '')
}
const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean(
......@@ -729,7 +726,7 @@ export default class NextNodeServer extends BaseServer<
renderOpts as LoadedRenderOpts<PagesModule>,
{
buildId: this.buildId,
deploymentId: this.nextConfig.deploymentId,
deploymentId: this.renderOpts.deploymentId,
customServer: this.serverOptions.customServer || undefined,
},
{
......
......@@ -182,7 +182,7 @@ export abstract class RouteModule<
routesManifest: DeepReadonly<DevRoutesManifest>
nextFontManifest: DeepReadonly<NextFontManifest>
prerenderManifest: DeepReadonly<PrerenderManifest>
serverFilesManifest: RequiredServerFilesManifest | undefined
serverFilesManifest: DeepReadonly<RequiredServerFilesManifest> | undefined
reactLoadableManifest: DeepReadonly<ReactLoadableManifest>
subresourceIntegrityManifest: any
clientReferenceManifest: any
......@@ -190,6 +190,7 @@ export abstract class RouteModule<
dynamicCssManifest: any
interceptionRoutePatterns: RegExp[]
} {
let result
if (process.env.NEXT_RUNTIME === 'edge') {
const { getEdgePreviewProps } =
require('../web/get-edge-preview-props') as typeof import('../web/get-edge-preview-props')
......@@ -197,7 +198,7 @@ export abstract class RouteModule<
const maybeJSONParse = (str?: string) =>
str ? JSON.parse(str) : undefined
return {
result = {
buildId: process.env.__NEXT_BUILD_ID || '',
buildManifest: self.__BUILD_MANIFEST as any,
fallbackBuildManifest: {} as any,
......@@ -209,7 +210,7 @@ export abstract class RouteModule<
notFoundRoutes: [],
version: 4,
preview: getEdgePreviewProps(),
},
} as const,
routesManifest: {
version: 4,
caseSensitive: Boolean(process.env.__NEXT_CASE_SENSITIVE_ROUTES),
......@@ -336,11 +337,11 @@ export abstract class RouteModule<
}),
this.isDev
? undefined
: (loadManifestFromRelativePath<RequiredServerFilesManifest>({
: loadManifestFromRelativePath<RequiredServerFilesManifest>({
projectDir,
distDir: this.distDir,
manifest: `${SERVER_FILES_MANIFEST}.json`,
}) as RequiredServerFilesManifest),
}),
this.isDev
? 'development'
: loadManifestFromRelativePath<any>({
......@@ -357,7 +358,7 @@ export abstract class RouteModule<
}),
]
return {
result = {
buildId,
buildManifest,
fallbackBuildManifest,
......@@ -376,6 +377,8 @@ export abstract class RouteModule<
.map((rewrite) => new RegExp(rewrite.regex)),
}
}
return result
}
public async loadCustomCacheHandlers(
......@@ -503,7 +506,10 @@ export abstract class RouteModule<
}
/** A more lightweight version of `prepare()` for only retrieving the config on edge */
public getNextConfigEdge(req: NextIncomingMessage): NextConfigRuntime {
public getNextConfigEdge(req: NextIncomingMessage): {
nextConfig: NextConfigRuntime
deploymentId: string
} {
if (process.env.NEXT_RUNTIME !== 'edge') {
throw new Error(
'Invariant: getNextConfigEdge must only be called in edge runtime'
......@@ -524,7 +530,19 @@ export abstract class RouteModule<
throw new Error("Invariant: nextConfig couldn't be loaded")
}
return nextConfig
let deploymentId
if (nextConfig.experimental?.runtimeServerDeploymentId) {
if (!process.env.NEXT_DEPLOYMENT_ID) {
throw new Error(
'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'
)
}
deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else {
deploymentId = nextConfig.deploymentId || ''
}
return { nextConfig, deploymentId }
}
public async prepare(
......@@ -540,6 +558,7 @@ export abstract class RouteModule<
): Promise<
| {
buildId: string
deploymentId: string
locale?: string
locales?: readonly string[]
defaultLocale?: string
......@@ -905,6 +924,18 @@ export abstract class RouteModule<
resolvedPathname = removeTrailingSlash(resolvedPathname)
let deploymentId
if (nextConfig.experimental?.runtimeServerDeploymentId) {
if (!process.env.NEXT_DEPLOYMENT_ID) {
throw new Error(
'process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled'
)
}
deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else {
deploymentId = nextConfig.deploymentId || ''
}
return {
query,
originalQuery,
......@@ -923,9 +954,12 @@ export abstract class RouteModule<
isOnDemandRevalidate,
revalidateOnlyGenerated,
...manifests,
clientReferenceManifest: manifests.clientReferenceManifest,
nextConfig,
// loadManifest returns a readonly object, but we don't want to propagate that throughout the
// whole codebase (for now)
nextConfig:
nextConfig satisfies DeepReadonly<NextConfigRuntime> as NextConfigRuntime,
routerServerContext,
deploymentId,
}
}
......
......@@ -81,7 +81,7 @@ export class EdgeRouteModuleWrapper {
caseSensitive: false,
})
const nextConfig = this.routeModule.getNextConfigEdge(
const { nextConfig } = this.routeModule.getNextConfigEdge(
new WebNextRequest(request)
)
......
export default function AppPage() {
return <div>Hello from app-page-edge</div>
}
export const runtime = 'edge'
export default function AppPage() {
return <div>Hello from app-page</div>
}
export function GET() {
return new Response('Hello from app-route-edge')
}
export const runtime = 'edge'
export function GET() {
return new Response('Hello from app-route')
}
export default function Layout({ children }) {
return (
<html>
<head />
<body>{children}</body>
</html>
)
}
import { NextInstance, createNext } from 'e2e-utils'
import fs from 'fs-extra'
import {
findPort,
initNextServerScript,
killApp,
renderViaHTTP,
} from 'next-test-utils'
import { join } from 'path'
let MY_DEPLOYMENT_ID = 'test-deployment-id'
describe('standalone mode: runtimeServerDeploymentId', () => {
let next: NextInstance
let server
let appPort
let output = ''
beforeAll(async () => {
next = await createNext({
files: __dirname,
env: {
NEXT_DEPLOYMENT_ID: MY_DEPLOYMENT_ID,
},
skipStart: true,
})
let { exitCode } = await next.build()
// eslint-disable-next-line jest/no-standalone-expect
expect(exitCode).toBe(0)
await fs.move(
join(next.testDir, '.next/standalone'),
join(next.testDir, 'standalone')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const testServer = join(next.testDir, 'standalone/server.js')
appPort = await findPort()
server = await initNextServerScript(
testServer,
/- Local:/,
{
...process.env,
HOSTNAME: '::',
PORT: appPort,
NEXT_DEPLOYMENT_ID: MY_DEPLOYMENT_ID,
},
undefined,
{
cwd: next.testDir,
onStdout(msg) {
output += msg
},
onStderr(msg) {
output += msg
},
}
)
})
afterAll(async () => {
await next.destroy()
if (server) await killApp(server)
})
it.each([
'app-page',
'app-page-edge',
'app-route',
'app-route-edge',
'pages-page',
'pages-page-edge',
'api/pages-route',
'api/pages-route-edge',
])('it should load %s', async (name) => {
expect(output).toContain(`- Local:`)
let html = await renderViaHTTP(appPort, `/${name}`)
expect(html).toContain(`Hello from ${name}`)
})
})
module.exports = {
output: 'standalone',
experimental: {
runtimeServerDeploymentId: true,
},
}
export default function handler(req) {
return new Response('Hello from api/pages-route-edge')
}
export const runtime = 'edge'
export default function handler(req, res) {
res.json('Hello from api/pages-route')
}
export default function AppPage() {
return <div>Hello from pages-page-edge</div>
}
export const runtime = 'experimental-edge'
export default function AppPage() {
return <div>Hello from pages-page</div>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment