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 @@ ...@@ -967,5 +967,7 @@
"966": "Expected process.nextTick to reject invalid arguments", "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", "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", "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 { ...@@ -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. * 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 { function serializeDefineEnv(defineEnv: DefineEnv): SerializedDefineEnv {
const defineEnvStringified: SerializedDefineEnv = {} const defineEnvStringified: SerializedDefineEnv = Object.fromEntries(
for (const key in defineEnv) { Object.entries(defineEnv).map(([key, value]) => [
const value = defineEnv[key] key,
defineEnvStringified[key] = JSON.stringify(value) JSON.stringify(value),
} ])
)
return defineEnvStringified return defineEnvStringified
} }
...@@ -167,9 +167,24 @@ export function getDefineEnv({ ...@@ -167,9 +167,24 @@ export function getDefineEnv({
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled, 'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled, 'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
'process.env.NEXT_DEPLOYMENT_ID': config.experimental?.useSkewCookie ...(isClient
? false ? {
: config.deploymentId || false, // 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 // Propagates the `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` environment
// variable to the client. // variable to the client.
'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING': 'process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING':
...@@ -372,8 +387,10 @@ export function getDefineEnv({ ...@@ -372,8 +387,10 @@ export function getDefineEnv({
for (const key in nextConfigEnv) { for (const key in nextConfigEnv) {
serializedDefineEnv[key] = safeKey(key) serializedDefineEnv[key] = safeKey(key)
} }
for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) { if (!config.experimental.runtimeServerDeploymentId) {
serializedDefineEnv[key] = safeKey(key) for (const key of ['process.env.NEXT_DEPLOYMENT_ID']) {
serializedDefineEnv[key] = safeKey(key)
}
} }
} }
......
...@@ -989,7 +989,7 @@ export default async function build( ...@@ -989,7 +989,7 @@ export default async function build(
// when using compile mode static env isn't inlined so we // when using compile mode static env isn't inlined so we
// need to populate in normal runtime env // need to populate in normal runtime env
if (isCompileMode || isGenerateMode) { if (isCompileMode || isGenerateMode) {
populateStaticEnv(config) populateStaticEnv(config, config.deploymentId)
} }
const customRoutes: CustomRoutes = await nextBuildSpan const customRoutes: CustomRoutes = await nextBuildSpan
......
...@@ -170,6 +170,7 @@ export async function handler( ...@@ -170,6 +170,7 @@ export async function handler(
nextConfig, nextConfig,
parsedUrl, parsedUrl,
interceptionRoutePatterns, interceptionRoutePatterns,
deploymentId,
} = prepareResult } = prepareResult
const normalizedSrcPage = normalizeAppPath(srcPage) const normalizedSrcPage = normalizeAppPath(srcPage)
...@@ -559,7 +560,7 @@ export async function handler( ...@@ -559,7 +560,7 @@ export async function handler(
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
images: nextConfig.images, images: nextConfig.images,
previewProps: prerenderManifest.preview, previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId, deploymentId: deploymentId,
enableTainting: nextConfig.experimental.taint, enableTainting: nextConfig.experimental.taint,
htmlLimitedBots: nextConfig.htmlLimitedBots, htmlLimitedBots: nextConfig.htmlLimitedBots,
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength, reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
......
...@@ -81,6 +81,7 @@ async function requestHandler( ...@@ -81,6 +81,7 @@ async function requestHandler(
resolvedPathname, resolvedPathname,
interceptionRoutePatterns, interceptionRoutePatterns,
routerServerContext, routerServerContext,
deploymentId,
} = prepareResult } = prepareResult
// Initialize the cache handlers interface. // Initialize the cache handlers interface.
...@@ -137,7 +138,7 @@ async function requestHandler( ...@@ -137,7 +138,7 @@ async function requestHandler(
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
images: nextConfig.images, images: nextConfig.images,
previewProps: prerenderManifest.preview, previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId, deploymentId,
enableTainting: nextConfig.experimental.taint, enableTainting: nextConfig.experimental.taint,
htmlLimitedBots: nextConfig.htmlLimitedBots, htmlLimitedBots: nextConfig.htmlLimitedBots,
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength, reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
......
...@@ -17,7 +17,7 @@ export async function inlineStaticEnv({ ...@@ -17,7 +17,7 @@ export async function inlineStaticEnv({
config: NextConfigComplete config: NextConfigComplete
}) { }) {
const nextConfigEnv = getNextConfigEnv(config) const nextConfigEnv = getNextConfigEnv(config)
const staticEnv = getStaticEnv(config) const staticEnv = getStaticEnv(config, config.deploymentId)
const serverDir = path.join(distDir, 'server') const serverDir = path.join(distDir, 'server')
const serverChunks = await glob('**/*.{js,json,js.map}', { const serverChunks = await glob('**/*.{js,json,js.map}', {
......
...@@ -53,22 +53,26 @@ export function getNextConfigEnv( ...@@ -53,22 +53,26 @@ export function getNextConfigEnv(
return defineEnv return defineEnv
} }
export function getStaticEnv(config: NextConfigComplete | NextConfigRuntime) { export function getStaticEnv(
config: NextConfigComplete | NextConfigRuntime,
deploymentId: string
) {
const staticEnv: Record<string, string | undefined> = { const staticEnv: Record<string, string | undefined> = {
...getNextPublicEnvironmentVariables(), ...getNextPublicEnvironmentVariables(),
...getNextConfigEnv(config), ...getNextConfigEnv(config),
'process.env.NEXT_DEPLOYMENT_ID': config.deploymentId || '', 'process.env.NEXT_DEPLOYMENT_ID': deploymentId,
} }
return staticEnv return staticEnv
} }
export function populateStaticEnv( export function populateStaticEnv(
config: NextConfigComplete | NextConfigRuntime config: NextConfigComplete | NextConfigRuntime,
deploymentId: string
) { ) {
// since inlining comes after static generation we need // since inlining comes after static generation we need
// to ensure this value is assigned to process env so it // to ensure this value is assigned to process env so it
// can still be accessed // can still be accessed
const staticEnv = getStaticEnv(config) const staticEnv = getStaticEnv(config, deploymentId)
for (const key in staticEnv) { for (const key in staticEnv) {
const innerKey = key.split('.').pop() || '' const innerKey = key.split('.').pop() || ''
if (!process.env[innerKey]) { if (!process.env[innerKey]) {
......
...@@ -447,6 +447,24 @@ export default abstract class Server< ...@@ -447,6 +447,24 @@ export default abstract class Server<
// TODO: should conf be normalized to prevent missing // TODO: should conf be normalized to prevent missing
// values from causing issues as this can be user provided // values from causing issues as this can be user provided
this.nextConfig = conf as NextConfigRuntime 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 this.hostname = hostname
if (this.hostname) { if (this.hostname) {
// we format the hostname so that it can be fetched // we format the hostname so that it can be fetched
...@@ -501,13 +519,12 @@ export default abstract class Server< ...@@ -501,13 +519,12 @@ export default abstract class Server<
} }
this.nextFontManifest = this.getNextFontManifest() this.nextFontManifest = this.getNextFontManifest()
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''
this.renderOpts = { this.renderOpts = {
dir: this.dir, dir: this.dir,
supportsDynamicResponse: true, supportsDynamicResponse: true,
trailingSlash: this.nextConfig.trailingSlash, trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.deploymentId, deploymentId: deploymentId,
poweredByHeader: this.nextConfig.poweredByHeader, poweredByHeader: this.nextConfig.poweredByHeader,
generateEtags, generateEtags,
previewProps: this.getPrerenderManifest().preview, previewProps: this.getPrerenderManifest().preview,
......
...@@ -347,6 +347,7 @@ export const experimentalSchema = { ...@@ -347,6 +347,7 @@ export const experimentalSchema = {
.optional(), .optional(),
lockDistDir: z.boolean().optional(), lockDistDir: z.boolean().optional(),
hideLogsAfterAbort: z.boolean().optional(), hideLogsAfterAbort: z.boolean().optional(),
runtimeServerDeploymentId: z.boolean().optional(),
} }
export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
......
...@@ -836,6 +836,14 @@ export interface ExperimentalConfig { ...@@ -836,6 +836,14 @@ export interface ExperimentalConfig {
* @default false * @default false
*/ */
hideLogsAfterAbort?: boolean 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 = { export type ExportPathMap = {
...@@ -1586,8 +1594,8 @@ export async function normalizeConfig(phase: string, config: any) { ...@@ -1586,8 +1594,8 @@ export async function normalizeConfig(phase: string, config: any) {
// }; // };
// }; // };
export interface NextConfigRuntime { export interface NextConfigRuntime {
// TODO remove in some cases // Can be undefined, particularly when experimental.runtimeServerDeploymentId is true
deploymentId: NextConfigComplete['deploymentId'] deploymentId?: NextConfigComplete['deploymentId']
configFileName?: string configFileName?: string
// Should only be included when using isExperimentalCompile // Should only be included when using isExperimentalCompile
...@@ -1652,6 +1660,7 @@ export interface NextConfigRuntime { ...@@ -1652,6 +1660,7 @@ export interface NextConfigRuntime {
| 'proxyClientMaxBodySize' | 'proxyClientMaxBodySize'
| 'proxyTimeout' | 'proxyTimeout'
| 'testProxy' | 'testProxy'
| 'runtimeServerDeploymentId'
> & { > & {
// Pick on @internal fields generates invalid .d.ts files // Pick on @internal fields generates invalid .d.ts files
/** @internal */ /** @internal */
...@@ -1706,6 +1715,7 @@ export function getNextConfigRuntime( ...@@ -1706,6 +1715,7 @@ export function getNextConfigRuntime(
proxyClientMaxBodySize: ex.proxyClientMaxBodySize, proxyClientMaxBodySize: ex.proxyClientMaxBodySize,
proxyTimeout: ex.proxyTimeout, proxyTimeout: ex.proxyTimeout,
testProxy: ex.testProxy, testProxy: ex.testProxy,
runtimeServerDeploymentId: ex.runtimeServerDeploymentId,
trustHostHeader: ex.trustHostHeader, trustHostHeader: ex.trustHostHeader,
isExperimentalCompile: ex.isExperimentalCompile, isExperimentalCompile: ex.isExperimentalCompile,
...@@ -1713,7 +1723,9 @@ export function getNextConfigRuntime( ...@@ -1713,7 +1723,9 @@ export function getNextConfigRuntime(
: {} : {}
let runtimeConfig: Requiredish<NextConfigRuntime> = { let runtimeConfig: Requiredish<NextConfigRuntime> = {
deploymentId: config.deploymentId, deploymentId: config.experimental.runtimeServerDeploymentId
? ''
: config.deploymentId,
configFileName: undefined, configFileName: undefined,
env: undefined, env: undefined,
......
...@@ -370,7 +370,7 @@ function assignDefaultsAndValidate( ...@@ -370,7 +370,7 @@ function assignDefaultsAndValidate(
} }
// ensure correct default is set for api-resolver revalidate handling // 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 result.experimental.trustHostHeader = true
} }
...@@ -916,6 +916,23 @@ function assignDefaultsAndValidate( ...@@ -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 // only leverage deploymentId
if (process.env.NEXT_DEPLOYMENT_ID) { if (process.env.NEXT_DEPLOYMENT_ID) {
result.deploymentId = process.env.NEXT_DEPLOYMENT_ID result.deploymentId = process.env.NEXT_DEPLOYMENT_ID
......
...@@ -295,9 +295,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -295,9 +295,6 @@ export default class NextNodeServer extends BaseServer<
if (this.renderOpts.nextScriptWorkers) { if (this.renderOpts.nextScriptWorkers) {
process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true) process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)
} }
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.experimental.useSkewCookie
? ''
: this.nextConfig.deploymentId || ''
if (!this.minimalMode) { if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode) this.imageResponseCache = new ResponseCache(this.minimalMode)
...@@ -356,7 +353,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -356,7 +353,7 @@ export default class NextNodeServer extends BaseServer<
// when using compile mode static env isn't inlined so we // when using compile mode static env isn't inlined so we
// need to populate in normal runtime env // need to populate in normal runtime env
if (this.renderOpts.isExperimentalCompile) { if (this.renderOpts.isExperimentalCompile) {
populateStaticEnv(this.nextConfig) populateStaticEnv(this.nextConfig, this.renderOpts.deploymentId || '')
} }
const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean( const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean(
...@@ -729,7 +726,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -729,7 +726,7 @@ export default class NextNodeServer extends BaseServer<
renderOpts as LoadedRenderOpts<PagesModule>, renderOpts as LoadedRenderOpts<PagesModule>,
{ {
buildId: this.buildId, buildId: this.buildId,
deploymentId: this.nextConfig.deploymentId, deploymentId: this.renderOpts.deploymentId,
customServer: this.serverOptions.customServer || undefined, customServer: this.serverOptions.customServer || undefined,
}, },
{ {
......
...@@ -182,7 +182,7 @@ export abstract class RouteModule< ...@@ -182,7 +182,7 @@ export abstract class RouteModule<
routesManifest: DeepReadonly<DevRoutesManifest> routesManifest: DeepReadonly<DevRoutesManifest>
nextFontManifest: DeepReadonly<NextFontManifest> nextFontManifest: DeepReadonly<NextFontManifest>
prerenderManifest: DeepReadonly<PrerenderManifest> prerenderManifest: DeepReadonly<PrerenderManifest>
serverFilesManifest: RequiredServerFilesManifest | undefined serverFilesManifest: DeepReadonly<RequiredServerFilesManifest> | undefined
reactLoadableManifest: DeepReadonly<ReactLoadableManifest> reactLoadableManifest: DeepReadonly<ReactLoadableManifest>
subresourceIntegrityManifest: any subresourceIntegrityManifest: any
clientReferenceManifest: any clientReferenceManifest: any
...@@ -190,6 +190,7 @@ export abstract class RouteModule< ...@@ -190,6 +190,7 @@ export abstract class RouteModule<
dynamicCssManifest: any dynamicCssManifest: any
interceptionRoutePatterns: RegExp[] interceptionRoutePatterns: RegExp[]
} { } {
let result
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
const { getEdgePreviewProps } = const { getEdgePreviewProps } =
require('../web/get-edge-preview-props') as typeof import('../web/get-edge-preview-props') require('../web/get-edge-preview-props') as typeof import('../web/get-edge-preview-props')
...@@ -197,7 +198,7 @@ export abstract class RouteModule< ...@@ -197,7 +198,7 @@ export abstract class RouteModule<
const maybeJSONParse = (str?: string) => const maybeJSONParse = (str?: string) =>
str ? JSON.parse(str) : undefined str ? JSON.parse(str) : undefined
return { result = {
buildId: process.env.__NEXT_BUILD_ID || '', buildId: process.env.__NEXT_BUILD_ID || '',
buildManifest: self.__BUILD_MANIFEST as any, buildManifest: self.__BUILD_MANIFEST as any,
fallbackBuildManifest: {} as any, fallbackBuildManifest: {} as any,
...@@ -209,7 +210,7 @@ export abstract class RouteModule< ...@@ -209,7 +210,7 @@ export abstract class RouteModule<
notFoundRoutes: [], notFoundRoutes: [],
version: 4, version: 4,
preview: getEdgePreviewProps(), preview: getEdgePreviewProps(),
}, } as const,
routesManifest: { routesManifest: {
version: 4, version: 4,
caseSensitive: Boolean(process.env.__NEXT_CASE_SENSITIVE_ROUTES), caseSensitive: Boolean(process.env.__NEXT_CASE_SENSITIVE_ROUTES),
...@@ -336,11 +337,11 @@ export abstract class RouteModule< ...@@ -336,11 +337,11 @@ export abstract class RouteModule<
}), }),
this.isDev this.isDev
? undefined ? undefined
: (loadManifestFromRelativePath<RequiredServerFilesManifest>({ : loadManifestFromRelativePath<RequiredServerFilesManifest>({
projectDir, projectDir,
distDir: this.distDir, distDir: this.distDir,
manifest: `${SERVER_FILES_MANIFEST}.json`, manifest: `${SERVER_FILES_MANIFEST}.json`,
}) as RequiredServerFilesManifest), }),
this.isDev this.isDev
? 'development' ? 'development'
: loadManifestFromRelativePath<any>({ : loadManifestFromRelativePath<any>({
...@@ -357,7 +358,7 @@ export abstract class RouteModule< ...@@ -357,7 +358,7 @@ export abstract class RouteModule<
}), }),
] ]
return { result = {
buildId, buildId,
buildManifest, buildManifest,
fallbackBuildManifest, fallbackBuildManifest,
...@@ -376,6 +377,8 @@ export abstract class RouteModule< ...@@ -376,6 +377,8 @@ export abstract class RouteModule<
.map((rewrite) => new RegExp(rewrite.regex)), .map((rewrite) => new RegExp(rewrite.regex)),
} }
} }
return result
} }
public async loadCustomCacheHandlers( public async loadCustomCacheHandlers(
...@@ -503,7 +506,10 @@ export abstract class RouteModule< ...@@ -503,7 +506,10 @@ export abstract class RouteModule<
} }
/** A more lightweight version of `prepare()` for only retrieving the config on edge */ /** 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') { if (process.env.NEXT_RUNTIME !== 'edge') {
throw new Error( throw new Error(
'Invariant: getNextConfigEdge must only be called in edge runtime' 'Invariant: getNextConfigEdge must only be called in edge runtime'
...@@ -524,7 +530,19 @@ export abstract class RouteModule< ...@@ -524,7 +530,19 @@ export abstract class RouteModule<
throw new Error("Invariant: nextConfig couldn't be loaded") 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( public async prepare(
...@@ -540,6 +558,7 @@ export abstract class RouteModule< ...@@ -540,6 +558,7 @@ export abstract class RouteModule<
): Promise< ): Promise<
| { | {
buildId: string buildId: string
deploymentId: string
locale?: string locale?: string
locales?: readonly string[] locales?: readonly string[]
defaultLocale?: string defaultLocale?: string
...@@ -905,6 +924,18 @@ export abstract class RouteModule< ...@@ -905,6 +924,18 @@ export abstract class RouteModule<
resolvedPathname = removeTrailingSlash(resolvedPathname) 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 { return {
query, query,
originalQuery, originalQuery,
...@@ -923,9 +954,12 @@ export abstract class RouteModule< ...@@ -923,9 +954,12 @@ export abstract class RouteModule<
isOnDemandRevalidate, isOnDemandRevalidate,
revalidateOnlyGenerated, revalidateOnlyGenerated,
...manifests, ...manifests,
clientReferenceManifest: manifests.clientReferenceManifest, // loadManifest returns a readonly object, but we don't want to propagate that throughout the
nextConfig, // whole codebase (for now)
nextConfig:
nextConfig satisfies DeepReadonly<NextConfigRuntime> as NextConfigRuntime,
routerServerContext, routerServerContext,
deploymentId,
} }
} }
......
...@@ -81,7 +81,7 @@ export class EdgeRouteModuleWrapper { ...@@ -81,7 +81,7 @@ export class EdgeRouteModuleWrapper {
caseSensitive: false, caseSensitive: false,
}) })
const nextConfig = this.routeModule.getNextConfigEdge( const { nextConfig } = this.routeModule.getNextConfigEdge(
new WebNextRequest(request) 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