Unverified Commit 7282ce67 authored by Brooke's avatar Brooke Committed by GitHub

[prebuilt-skew-protection] feat: adding in automatic deploymentId (#88496)

Original [PR](https://github.com/vercel/next.js/pull/88012/) has a bug
that attempted to validate on environment variables. Edited function to
not run validations on environment variables, only on the user provided
deployment id.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 5a0b9787
---
title: '`deploymentId` contains invalid characters'
---
## Why This Error Occurred
The `deploymentId` in your `next.config.js` contains characters that are not allowed. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\_) are permitted.
## Possible Ways to Fix It
### Option 1: Remove Invalid Characters
Remove or replace any characters that are not alphanumeric, hyphens, or underscores:
```js
// ✅ Correct
module.exports = {
deploymentId: 'my-deployment-123', // Only alphanumeric, hyphens, underscores
}
// ❌ Incorrect
module.exports = {
deploymentId: 'my deployment 123', // Contains spaces
deploymentId: 'my.deployment.123', // Contains dots
deploymentId: 'my/deployment/123', // Contains slashes
deploymentId: 'my@deployment#123', // Contains special characters
}
```
### Option 2: Sanitize the Deployment ID
If you're generating the ID from user input or other sources, sanitize it to remove invalid characters:
```js
// next.config.js
module.exports = {
deploymentId: () => {
const rawId = process.env.DEPLOYMENT_ID || 'default-id'
// Remove all characters that are not alphanumeric, hyphens, or underscores
return rawId.replace(/[^a-zA-Z0-9_-]/g, '')
},
}
```
### Option 3: Use a Valid Format
Common valid formats include:
```js
// next.config.js
module.exports = {
// Using hyphens
deploymentId: 'my-deployment-id',
// Using underscores
deploymentId: 'my_deployment_id',
// Alphanumeric only
deploymentId: 'mydeployment123',
// Mixed format
deploymentId: 'my-deployment_123',
}
```
## Additional Information
- The deployment ID is used for skew protection and asset versioning
- Invalid characters can cause issues with URL encoding and routing
- Keep the ID URL-friendly by using only the allowed character set
- The validation ensures compatibility across different systems and environments
---
title: '`deploymentId` function must return a string'
---
## Why This Error Occurred
The `deploymentId` option in your `next.config.js` is defined as a function, but it did not return a string value.
## Possible Ways to Fix It
Always return a string from your `deploymentId` function:
```js
// ✅ Correct
module.exports = {
deploymentId: () => {
return process.env.GIT_HASH || Date.now().toString()
},
}
// ❌ Incorrect
module.exports = {
deploymentId: () => {
// Missing return statement or returning non-string
return null
},
}
```
The `deploymentId` can be:
- A string: `deploymentId: 'my-deployment-123'`
- A function that returns a string: `deploymentId: () => process.env.GIT_HASH || ''`
- `undefined` (will be empty string, or use `NEXT_DEPLOYMENT_ID` environment variable if set)
# Deployment ID Too Long
The `deploymentId` in your `next.config.js` exceeds the maximum length of 32 characters.
## Why This Error Occurred
The `deploymentId` configuration option has a maximum length of 32 characters to ensure compatibility with various systems and constraints.
## Possible Ways to Fix It
### Option 1: Shorten Your Deployment ID
Reduce the length of your `deploymentId` to 32 characters or less:
```js
// next.config.js
module.exports = {
deploymentId: 'my-short-id', // ✅ 12 characters
}
```
### Option 2: Use a Function to Generate a Shorter ID
If you're generating the ID dynamically, ensure it doesn't exceed 32 characters:
```js
// next.config.js
module.exports = {
deploymentId: () => {
// Generate a shorter ID (e.g., hash or truncate)
return process.env.GIT_COMMIT_SHA?.substring(0, 32) || 'default-id'
},
}
```
### Option 3: Truncate Environment Variables
If using environment variables, ensure the value is truncated to 32 characters:
```js
// next.config.js
module.exports = {
deploymentId: process.env.DEPLOYMENT_ID?.substring(0, 32),
}
```
## Additional Information
- The deployment ID is used for skew protection and asset versioning
- Keep it concise but meaningful for your use case
- Consider using hashes or shortened identifiers if you need unique values
......@@ -980,5 +980,9 @@
"979": "invariant: expected %s bytes of postponed state but only received %s bytes",
"980": "Failed to load client middleware manifest",
"981": "resolvedPathname must be set in request metadata",
"982": "`serializeResumeDataCache` should not be called in edge runtime."
"982": "`serializeResumeDataCache` should not be called in edge runtime.",
"983": "deploymentId function must return a string. https://nextjs.org/docs/messages/deploymentid-not-a-string",
"984": "The deploymentId \"%s\" cannot start with the \"dpl_\" prefix. Please choose a different deploymentId in your next.config.js. https://vercel.com/docs/skew-protection#custom-skew-protection-deployment-id",
"985": "The deploymentId \"%s\" exceeds the maximum length of 32 characters. Please choose a shorter deploymentId. https://nextjs.org/docs/messages/deploymentid-too-long",
"986": "The deploymentId \"%s\" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed. https://nextjs.org/docs/messages/deploymentid-invalid-characters"
}
......@@ -386,6 +386,11 @@ export interface NextAdapter {
* influenced by NextConfig.generateBuildId
*/
buildId: string
/**
* deploymentId is the current deployment ID, this can be
* influenced by NextConfig.deploymentId or NEXT_DEPLOYMENT_ID environment variable
*/
deploymentId: string
}) => Promise<void> | void
}
......@@ -415,6 +420,7 @@ export async function handleBuildComplete({
config,
appType,
buildId,
deploymentId,
configOutDir,
distDir,
pageKeys,
......@@ -438,6 +444,7 @@ export async function handleBuildComplete({
appType: 'app' | 'pages' | 'hybrid'
distDir: string
buildId: string
deploymentId: string
configOutDir: string
adapterPath: string
tracingRoot: string
......@@ -1856,6 +1863,7 @@ export async function handleBuildComplete({
config,
distDir,
buildId,
deploymentId,
nextVersion,
projectDir: dir,
repoRoot: tracingRoot,
......
......@@ -21,6 +21,7 @@ import loadCustomRoutes from '../../lib/load-custom-routes'
import { generateRoutesManifest } from '../generate-routes-manifest'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { resolveAndSetDeploymentId } from '../generate-deployment-id'
import http from 'node:http'
// @ts-expect-error types are in @types/serve-handler
......@@ -53,7 +54,10 @@ export default async function analyze({
reactProductionProfiling,
})
process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
config.deploymentId = resolveAndSetDeploymentId(
config.deploymentId,
config.deploymentId != null ? 'user-config' : 'env-var'
)
const distDir = path.join(dir, '.next')
const telemetry = new Telemetry({ distDir })
......
......@@ -49,6 +49,7 @@ export interface MappedPages {
// to pass it through function arguments.
// Not exhaustive, but should be extended to as needed whilst refactoring
export const NextBuildContext: Partial<{
deploymentId?: string | undefined
compilerIdx?: number
pluginState: Record<string, any>
// core fields
......@@ -96,6 +97,7 @@ export const NextBuildContext: Partial<{
isCompileMode?: boolean
debugPrerender: boolean
analyze: boolean
preservedDeploymentId?: string
debugBuildPaths?: {
app: string[]
pages: string[]
......
......@@ -46,6 +46,7 @@ const DEFINE_ENV_EXPRESSION = Symbol('DEFINE_ENV_EXPRESSION')
interface DefineEnv {
[key: string]:
| string
| (() => string)
| string[]
| boolean
| { [DEFINE_ENV_EXPRESSION]: string }
......@@ -170,7 +171,8 @@ export function getDefineEnv({
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
...(config.experimental?.useSkewCookie || !config.deploymentId
...(config.experimental?.useSkewCookie ||
(!config.deploymentId && !config.experimental?.runtimeServerDeploymentId)
? {
'process.env.NEXT_DEPLOYMENT_ID': false,
}
......
/**
* Generates a deployment ID from a user-provided function or string.
* Similar to generateBuildId, but for deploymentId.
*/
export function generateDeploymentId(
deploymentId: string | (() => string) | undefined
): string | undefined {
if (typeof deploymentId === 'function') {
const result = deploymentId()
if (typeof result !== 'string') {
throw new Error(
'deploymentId function must return a string. https://nextjs.org/docs/messages/deploymentid-not-a-string'
)
}
return result
}
if (typeof deploymentId === 'string') {
return deploymentId
}
return undefined
}
type DeploymentIdSource = 'user-config' | 'env-var'
/**
* Resolves and sets the deployment ID from config, handling precedence and ensuring function is only evaluated once.
* User-configured deploymentId always takes precedence over NEXT_DEPLOYMENT_ID.
*
* @param configDeploymentId - The deploymentId from config (can be string, function, or undefined)
* @param source - Source indicator: 'user-config' treats as user-configured (validates), 'env-var' uses NEXT_DEPLOYMENT_ID
* @param fallbackDeploymentId - Optional fallback deployment ID to use if process.env.NEXT_DEPLOYMENT_ID is empty
* @returns The resolved deploymentId string to use
*/
export function resolveAndSetDeploymentId(
configDeploymentId: string | (() => string) | undefined,
source: DeploymentIdSource,
fallbackDeploymentId?: string
): string {
if (source === 'env-var') {
// Prefer fallbackDeploymentId (from combinedEnv) over process.env since
// loadEnvConfig may have reset process.env
let envDeploymentId =
fallbackDeploymentId || process.env['NEXT_DEPLOYMENT_ID'] || ''
if (
envDeploymentId &&
envDeploymentId !== process.env['NEXT_DEPLOYMENT_ID']
) {
process.env['NEXT_DEPLOYMENT_ID'] = envDeploymentId
}
if (envDeploymentId.length > 0) {
if (envDeploymentId.length > 32) {
throw new Error(
`The deploymentId "${envDeploymentId}" exceeds the maximum length of 32 characters. Please choose a shorter deploymentId. https://nextjs.org/docs/messages/deploymentid-too-long`
)
}
const validCharacterPattern = /^[a-zA-Z0-9_-]+$/
if (!validCharacterPattern.test(envDeploymentId)) {
throw new Error(
`The deploymentId "${envDeploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed. https://nextjs.org/docs/messages/deploymentid-invalid-characters`
)
}
process.env['NEXT_DEPLOYMENT_ID'] = envDeploymentId
return envDeploymentId
}
return ''
}
let userConfiguredDeploymentId: string | undefined
if (typeof configDeploymentId === 'string') {
userConfiguredDeploymentId = configDeploymentId
} else if (typeof configDeploymentId === 'function') {
userConfiguredDeploymentId = generateDeploymentId(configDeploymentId)
}
if (userConfiguredDeploymentId !== undefined) {
if (userConfiguredDeploymentId.length === 0) {
return process.env['NEXT_DEPLOYMENT_ID'] || ''
}
if (userConfiguredDeploymentId.length > 32) {
throw new Error(
`The deploymentId "${userConfiguredDeploymentId}" exceeds the maximum length of 32 characters. Please choose a shorter deploymentId. https://nextjs.org/docs/messages/deploymentid-too-long`
)
}
const validCharacterPattern = /^[a-zA-Z0-9_-]+$/
if (!validCharacterPattern.test(userConfiguredDeploymentId)) {
throw new Error(
`The deploymentId "${userConfiguredDeploymentId}" contains invalid characters. Only alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (_) are allowed. https://nextjs.org/docs/messages/deploymentid-invalid-characters`
)
}
process.env['NEXT_DEPLOYMENT_ID'] = userConfiguredDeploymentId
return userConfiguredDeploymentId
}
return process.env['NEXT_DEPLOYMENT_ID'] || ''
}
......@@ -35,6 +35,7 @@ export interface GenerateRoutesManifestOptions {
restrictedRedirectPaths: string[]
isAppPPREnabled: boolean
appType: 'pages' | 'app' | 'hybrid'
deploymentId?: string
}
export interface GenerateRoutesManifestResult {
......@@ -60,6 +61,7 @@ export function generateRoutesManifest(
restrictedRedirectPaths,
isAppPPREnabled,
appType,
deploymentId,
} = options
const sortedRoutes = sortPages([...pageKeys.pages, ...(pageKeys.app ?? [])])
......@@ -134,6 +136,7 @@ export function generateRoutesManifest(
queryHeader: NEXT_REWRITTEN_QUERY_HEADER,
},
skipProxyUrlNormalize: config.skipProxyUrlNormalize,
deploymentId: deploymentId || undefined,
ppr: isAppPPREnabled
? {
chain: {
......
......@@ -10,7 +10,12 @@ import type { CacheControl, Revalidate } from '../server/lib/cache-control'
import '../lib/setup-exception-listeners'
import { loadEnvConfig, type LoadedEnvFiles } from '@next/env'
import {
loadEnvConfig,
type LoadedEnvFiles,
initialEnv,
updateInitialEnv,
} from '@next/env'
import { bold, yellow } from '../lib/picocolors'
import { makeRe } from 'next/dist/compiled/picomatch'
import { existsSync, promises as fs } from 'fs'
......@@ -128,6 +133,8 @@ import { sortByPageExts } from './sort-by-page-exts'
import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'
import { PAGE_TYPES } from '../lib/page-types'
import { generateBuildId } from './generate-build-id'
import { resolveAndSetDeploymentId } from './generate-deployment-id'
import { evaluateDeploymentId } from '../server/evaluate-deployment-id'
import { isWriteable } from './is-writeable'
import * as Log from './output/log'
import createSpinner from './spinner'
......@@ -488,6 +495,13 @@ export type RoutesManifest = {
}
skipProxyUrlNormalize?: boolean
caseSensitive?: boolean
/**
* User-configured deployment ID for skew protection.
* This allows users to specify a custom deployment identifier
* in their next.config.js that will be used for version skew protection
* with pre-built deployments.
*/
deploymentId?: string
/**
* Configuration related to Partial Prerendering.
*/
......@@ -924,6 +938,11 @@ export default async function build(
let loadedConfig: NextConfigComplete | undefined
let staticWorker: StaticWorker
try {
const preservedDeploymentIdAtStart = process.env.NEXT_DEPLOYMENT_ID
if (preservedDeploymentIdAtStart) {
NextBuildContext.preservedDeploymentId = preservedDeploymentIdAtStart
}
const nextBuildSpan = trace('next-build', undefined, {
buildMode: experimentalBuildMode,
version: process.env.__NEXT_VERSION as string,
......@@ -938,12 +957,35 @@ export default async function build(
NextBuildContext.debugBuildPaths = debugBuildPaths
await nextBuildSpan.traceAsyncFn(async () => {
// attempt to load global env values so they are available in next.config.js
const { loadedEnvFiles } = nextBuildSpan
// Check process.env first to get the latest value (e.g., from next.env in tests)
// Then fall back to NextBuildContext which might have a stale value from previous build
const preservedDeploymentId =
process.env.NEXT_DEPLOYMENT_ID || NextBuildContext.preservedDeploymentId
if (preservedDeploymentId) {
NextBuildContext.preservedDeploymentId = preservedDeploymentId
// Ensure it's in process.env so loadEnvConfig can see it
process.env.NEXT_DEPLOYMENT_ID = preservedDeploymentId
// Update initialEnv so loadEnvConfig includes it when resetting process.env
updateInitialEnv({ NEXT_DEPLOYMENT_ID: preservedDeploymentId })
}
const { loadedEnvFiles, combinedEnv } = nextBuildSpan
.traceChild('load-dotenv')
.traceFn(() => loadEnvConfig(dir, false, Log))
NextBuildContext.loadedEnvFiles = loadedEnvFiles
// Restore NEXT_DEPLOYMENT_ID after loadEnvConfig resets process.env
// Priority: preservedDeploymentId > process.env (after loadEnvConfig) > combinedEnv
if (preservedDeploymentId) {
process.env.NEXT_DEPLOYMENT_ID = preservedDeploymentId
NextBuildContext.preservedDeploymentId = preservedDeploymentId
} else if (process.env.NEXT_DEPLOYMENT_ID) {
NextBuildContext.preservedDeploymentId = process.env.NEXT_DEPLOYMENT_ID
} else if (combinedEnv.NEXT_DEPLOYMENT_ID) {
process.env.NEXT_DEPLOYMENT_ID = combinedEnv.NEXT_DEPLOYMENT_ID
NextBuildContext.preservedDeploymentId = combinedEnv.NEXT_DEPLOYMENT_ID
}
const turborepoAccessTraceResult = new TurborepoAccessTraceResult()
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
const config: NextConfigComplete = await nextBuildSpan
......@@ -967,13 +1009,32 @@ export default async function build(
)
loadedConfig = config
// Reading the config can modify environment variables that influence the bundler selection.
bundler = finalizeBundlerFromConfig(bundler)
nextBuildSpan.setAttribute('bundler', getBundlerForTelemetry(bundler))
// Install the native bindings early so we can have synchronous access later.
await installBindings(config.experimental?.useWasmBinary)
process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
// Collect all possible sources of deployment ID
let currentDeploymentId =
NextBuildContext.preservedDeploymentId ||
preservedDeploymentId ||
process.env.NEXT_DEPLOYMENT_ID ||
initialEnv?.NEXT_DEPLOYMENT_ID ||
combinedEnv.NEXT_DEPLOYMENT_ID ||
''
// Ensure process.env has the deployment ID before resolving
if (currentDeploymentId) {
process.env['NEXT_DEPLOYMENT_ID'] = currentDeploymentId
}
config.deploymentId = resolveAndSetDeploymentId(
config.deploymentId,
config.deploymentId != null ? 'user-config' : 'env-var',
currentDeploymentId || undefined
)
if (config.deploymentId) {
process.env['NEXT_DEPLOYMENT_ID'] = config.deploymentId
}
NextBuildContext.config = config
let configOutDir = 'out'
......@@ -993,6 +1054,7 @@ export default async function build(
config
)
NextBuildContext.buildId = buildId
NextBuildContext.deploymentId = config.deploymentId
if (experimentalBuildMode === 'generate-env') {
if (bundler === Bundler.Turbopack) {
......@@ -1018,7 +1080,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, config.deploymentId)
populateStaticEnv(config, config.deploymentId || '')
}
const customRoutes: CustomRoutes = await nextBuildSpan
......@@ -1637,6 +1699,7 @@ export default async function build(
rewrites,
restrictedRedirectPaths,
isAppPPREnabled,
deploymentId: evaluateDeploymentId(config.deploymentId),
})
)
......@@ -2714,7 +2777,10 @@ export default async function build(
2
)};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`
let clientMiddlewareManifestPath = config.deploymentId
const evaluatedDeploymentId = evaluateDeploymentId(
config.deploymentId
)
let clientMiddlewareManifestPath = evaluatedDeploymentId
? path.join(
CLIENT_STATIC_FILES_PATH,
TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST
......@@ -4074,7 +4140,7 @@ export default async function build(
distDir,
buildId,
locales: config.i18n?.locales,
deploymentId: config.deploymentId,
deploymentId: evaluateDeploymentId(config.deploymentId),
})
} else {
await writePrerenderManifest(distDir, {
......@@ -4206,6 +4272,7 @@ export default async function build(
config,
appType,
buildId,
deploymentId: (config.deploymentId as string) || '',
configOutDir: path.join(dir, configOutDir),
staticPages,
serverPropsPages,
......
......@@ -854,6 +854,10 @@ function bindingToApi(
): Promise<string> {
// Avoid mutating the existing `nextConfig` object. NOTE: This is only a shallow clone.
let nextConfigSerializable: Record<string, any> = { ...nextConfig }
// deploymentId is already evaluated to a string in config.ts, ensure it's typed correctly
if (nextConfigSerializable.deploymentId != null) {
nextConfigSerializable.deploymentId = nextConfig.deploymentId as string
}
// These values are never read by Turbopack and are potentially non-serializable.
nextConfigSerializable.exportPathMap = {}
......
......@@ -14,6 +14,8 @@ import { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loa
import { promises as fs } from 'fs'
import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants'
import loadConfig from '../../server/config'
import type { NextConfigComplete } from '../../server/config-shared'
import { evaluateDeploymentId } from '../../server/evaluate-deployment-id'
import { hasCustomExportOutput } from '../../export/utils'
import { Telemetry } from '../../telemetry/storage'
import { setGlobal } from '../../trace'
......@@ -57,7 +59,9 @@ export async function turbopackBuild(): Promise<{
rootPath: config.turbopack?.root || config.outputFileTracingRoot || dir,
projectPath: normalizePath(path.relative(rootPath, dir) || '.'),
distDir,
nextConfig: config,
nextConfig: config as NextConfigComplete & {
deploymentId?: string
},
watch: {
enable: false,
},
......@@ -138,7 +142,8 @@ export async function turbopackBuild(): Promise<{
distDir,
encryptionKey,
dev: false,
deploymentId: config.deploymentId,
deploymentId: evaluateDeploymentId(config.deploymentId),
runtimeServerDeploymentId: config.experimental.runtimeServerDeploymentId,
})
const currentEntrypoints = await rawEntrypointsToEntrypoints(
......
......@@ -32,6 +32,7 @@ import {
import type { CompilerNameValues } from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
import type { NextConfigComplete } from '../server/config-shared'
import { evaluateDeploymentId } from '../server/evaluate-deployment-id'
import { finalizeEntrypoint } from './entries'
import * as Log from './output/log'
import { buildConfiguration } from './webpack/config'
......@@ -563,7 +564,9 @@ export default async function getBaseWebpackConfig(
pagesDir,
appDir,
hasReactRefresh: dev && isClient,
nextConfig: config,
nextConfig: config as NextConfigComplete & {
deploymentId?: string
},
jsConfig,
transpilePackages: finalTranspilePackages,
supportedBrowsers,
......@@ -2110,13 +2113,18 @@ export default async function getBaseWebpackConfig(
__NEXT_PREVIEW_MODE_SIGNING_KEY: previewProps.previewModeSigningKey,
__NEXT_PREVIEW_MODE_ENCRYPTION_KEY:
previewProps.previewModeEncryptionKey,
...(config.experimental.runtimeServerDeploymentId
? {
NEXT_DEPLOYMENT_ID: process.env.NEXT_DEPLOYMENT_ID,
}
: {}),
},
}),
isClient &&
new BuildManifestPlugin({
buildId,
dev,
deploymentId: config.deploymentId,
deploymentId: evaluateDeploymentId(config.deploymentId),
rewrites,
isDevFallback,
appDirEnabled: hasAppDir,
......
......@@ -53,6 +53,7 @@ import { Telemetry } from '../telemetry/storage'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { loadEnvConfig } from '@next/env'
import { evaluateDeploymentId } from '../server/evaluate-deployment-id'
import { isAPIRoute } from '../lib/is-api-route'
import { getPagePath } from '../server/require'
import type { Span } from '../trace'
......@@ -712,7 +713,7 @@ async function exportAppImpl(
batches.map(async (batch) =>
worker.exportPages({
buildId,
deploymentId: nextConfig.deploymentId,
deploymentId: evaluateDeploymentId(nextConfig.deploymentId) || '',
exportPaths: batch,
parentSpanId: span.getId(),
pagesDataDir,
......
......@@ -6,6 +6,7 @@ import globOriginal from 'next/dist/compiled/glob'
import { Sema } from 'next/dist/compiled/async-sema'
import type { NextConfigComplete } from '../server/config-shared'
import { getNextConfigEnv, getStaticEnv } from './static-env'
import { evaluateDeploymentId } from '../server/evaluate-deployment-id'
const glob = promisify(globOriginal)
......@@ -17,7 +18,11 @@ export async function inlineStaticEnv({
config: NextConfigComplete
}) {
const nextConfigEnv = getNextConfigEnv(config)
const staticEnv = getStaticEnv(config, config.deploymentId)
// User-configured deploymentId takes precedence over NEXT_DEPLOYMENT_ID
const deploymentId = evaluateDeploymentId(
config.deploymentId || process.env.NEXT_DEPLOYMENT_ID
)
const staticEnv = getStaticEnv(config, deploymentId)
const serverDir = path.join(distDir, 'server')
const serverChunks = await glob('**/*.{js,json,js.map}', {
......
......@@ -182,6 +182,7 @@ export type RouteHandler<
* the rewrites normalized to the object shape that the router expects.
*/
export type NormalizedRouteManifest = {
readonly deploymentId?: string | undefined
readonly dynamicRoutes: ReadonlyArray<ManifestRoute>
readonly rewrites: {
readonly beforeFiles: ReadonlyArray<ManifestRewriteRoute>
......@@ -465,7 +466,7 @@ export default abstract class Server<
} else {
let id = this.nextConfig.experimental.useSkewCookie
? ''
: this.nextConfig.deploymentId || ''
: (this.nextConfig.deploymentId as string) || ''
this.deploymentId = id
process.env.NEXT_DEPLOYMENT_ID = id
......
......@@ -1149,8 +1149,9 @@ export interface NextConfig {
/**
* A unique identifier for a deployment that will be included in each request's query string or header.
* Can be a string or a function that returns a string.
*/
deploymentId?: string
deploymentId?: string | (() => string)
/**
* Deploy a Next.js application under a sub-path of a domain
......
......@@ -45,6 +45,7 @@ import { djb2Hash } from '../shared/lib/hash'
import type { NextAdapter } from '../build/adapter/build-complete'
import { HardDeprecatedConfigError } from '../shared/lib/errors/hard-deprecated-config-error'
import { NextInstanceErrorState } from './mcp/tools/next-instance-error-state'
import { evaluateDeploymentId } from './evaluate-deployment-id'
export { normalizeConfig } from './config-shared'
export type { DomainLocale, NextConfig } from './config-shared'
......@@ -955,28 +956,19 @@ function assignDefaultsAndValidate(
}
}
if (result.deploymentId != null) {
result.deploymentId = evaluateDeploymentId(result.deploymentId)
}
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
}
const tracingRoot = result?.outputFileTracingRoot
const turbopackRoot = result?.turbopack?.root
......
......@@ -77,6 +77,8 @@ import {
} from './messages'
import { generateEncryptionKeyBase64 } from '../app-render/encryption-utils-server'
import { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'
import type { NextConfigComplete } from '../config-shared'
import { evaluateDeploymentId } from '../evaluate-deployment-id'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import type { ModernSourceMapPayload } from '../lib/source-maps'
import { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'
......@@ -254,7 +256,9 @@ export async function createHotReloaderTurbopack(
rootPath,
projectPath: normalizePath(relative(rootPath, projectPath) || '.'),
distDir,
nextConfig: opts.nextConfig,
nextConfig: opts.nextConfig as NextConfigComplete & {
deploymentId?: string
},
watch: {
enable: dev,
pollIntervalMs: nextConfig.watchOptions?.pollIntervalMs,
......@@ -324,7 +328,9 @@ export async function createHotReloaderTurbopack(
distDir,
encryptionKey,
dev: true,
deploymentId: nextConfig.deploymentId,
deploymentId: evaluateDeploymentId(nextConfig.deploymentId),
runtimeServerDeploymentId:
nextConfig.experimental.runtimeServerDeploymentId,
})
// Dev specific
......
/**
* Evaluates a deployment ID from a user-provided function or string.
* Returns the string value, calling the function if needed.
* Returns empty string if undefined (for runtime use where a string is always needed).
* Handles all possible input types at runtime, including broader Function types.
*
* This file is safe to use in edge runtime - it does NOT modify process.env.
*/
export function evaluateDeploymentId(
deploymentId: string | (() => string) | Function | undefined | null | unknown
): string {
// Handle function type (including broader Function type, not just () => string)
if (typeof deploymentId === 'function') {
const result = deploymentId()
if (typeof result !== 'string') {
throw new Error(
'deploymentId function must return a string. https://nextjs.org/docs/messages/deploymentid-not-a-string'
)
}
return result
}
if (typeof deploymentId === 'string') {
return deploymentId
}
// Handle null, undefined, or any other type
return ''
}
......@@ -57,6 +57,7 @@ import type { BaseNextRequest } from '../base-http'
import type { I18NConfig, NextConfigRuntime } from '../config-shared'
import ResponseCache, { type ResponseGenerator } from '../response-cache'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { evaluateDeploymentId } from '../evaluate-deployment-id'
import {
RouterServerContextSymbol,
routerServerGlobal,
......@@ -544,7 +545,8 @@ export abstract class RouteModule<
}
deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else {
deploymentId = nextConfig.deploymentId || ''
// evaluateDeploymentId handles string, function, and undefined cases
deploymentId = evaluateDeploymentId(nextConfig.deploymentId)
}
return { nextConfig, deploymentId }
......@@ -946,7 +948,8 @@ export abstract class RouteModule<
}
deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else {
deploymentId = nextConfig.deploymentId || ''
// evaluateDeploymentId handles string, function, and undefined cases
deploymentId = evaluateDeploymentId(nextConfig.deploymentId)
}
return {
......
......@@ -204,6 +204,7 @@ export class TurbopackManifestLoader {
private readonly buildId: string
private readonly deploymentId: string
private readonly dev: boolean
private readonly runtimeServerDeploymentId: boolean
constructor({
distDir,
......@@ -211,18 +212,21 @@ export class TurbopackManifestLoader {
encryptionKey,
dev,
deploymentId,
runtimeServerDeploymentId = false,
}: {
buildId: string
distDir: string
encryptionKey: string
dev: boolean
deploymentId: string
runtimeServerDeploymentId?: boolean
}) {
this.distDir = distDir
this.buildId = buildId
this.encryptionKey = encryptionKey
this.dev = dev
this.deploymentId = deploymentId
this.runtimeServerDeploymentId = runtimeServerDeploymentId
}
delete(key: EntryKey) {
......@@ -763,9 +767,14 @@ export class TurbopackManifestLoader {
const updateFunctionDefinition = (
fun: EdgeFunctionDefinition
): EdgeFunctionDefinition => {
const env = { ...fun.env }
if (process.env.NEXT_DEPLOYMENT_ID) {
env.NEXT_DEPLOYMENT_ID = process.env.NEXT_DEPLOYMENT_ID
}
return {
...fun,
files: [...(instrumentation?.files ?? []), ...fun.files],
env,
}
}
for (const key of Object.keys(manifest.middleware)) {
......
import { createNext, isNextDev } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
describe('deploymentId function support', () => {
let next: NextInstance | undefined
// Generate unique deployment IDs for each test run to avoid Vercel conflicts
// Use a short unique ID to stay within 32 character limit
const uniqueId = Date.now().toString(36).slice(-6)
afterEach(async () => {
if (next) {
await next.destroy()
next = undefined
}
})
it('should work with deploymentId as a string', async () => {
next = await createNext({
files: {
'app/layout.jsx': `
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
`,
'app/page.jsx': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
deploymentId: 'my-static-deployment-id-${uniqueId}'
}
`,
},
dependencies: {},
})
const res = await next.fetch('/')
const html = await res.text()
expect(html).toContain('hello world')
})
it('should work with deploymentId as a function returning string', async () => {
next = await createNext({
files: {
'app/layout.jsx': `
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
`,
'app/page.jsx': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
deploymentId: () => {
return 'my-function-deployment-id-${uniqueId}'
}
}
`,
},
dependencies: {},
})
const res = await next.fetch('/')
const html = await res.text()
expect(html).toContain('hello world')
})
it('should work with deploymentId function using environment variable', async () => {
next = await createNext({
files: {
'app/layout.jsx': `
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
`,
'app/page.jsx': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
deploymentId: () => {
return process.env.CUSTOM_DEPLOYMENT_ID || 'fallback-id'
}
}
`,
},
env: {
CUSTOM_DEPLOYMENT_ID: `env-deployment-id-${uniqueId}`,
},
dependencies: {},
})
const res = await next.fetch('/')
const html = await res.text()
expect(html).toContain('hello world')
})
it('should work with useSkewCookie and deploymentId function', async () => {
next = await createNext({
files: {
'app/layout.jsx': `
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
`,
'app/page.jsx': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
experimental: {
useSkewCookie: true
},
deploymentId: () => {
return 'skew-cookie-deployment-id-${uniqueId}'
}
}
`,
},
dependencies: {},
})
const res = await next.fetch('/')
const setCookieHeader = res.headers.get('set-cookie')
// In deploy mode (NEXT_DEPLOYMENT_ID set by Vercel), expect the Vercel deployment ID (starts with dpl_)
// In prebuild mode (NEXT_DEPLOYMENT_ID not set), expect the user-configured ID
if (setCookieHeader?.includes('__vdpl=dpl_')) {
// Deploy mode: expect Vercel's deployment ID (format: dpl_...)
expect(setCookieHeader).toMatch(/__vdpl=dpl_[^;]+/)
} else {
// Prebuild mode: expect user-configured deployment ID
expect(setCookieHeader).toContain(
`__vdpl=skew-cookie-deployment-id-${uniqueId}`
)
}
})
// Note: In dev mode, config validation errors are thrown after the server says "Ready",
// so createNext() resolves before the error is caught. These tests only work in
// start/deploy modes where build-time validation catches the error.
it('should throw error when deploymentId function returns non-string', async () => {
if (isNextDev) {
// Skip in dev mode - validation errors occur after server starts
return
}
let errorThrown = false
let nextInstance: NextInstance | undefined
try {
nextInstance = await createNext({
files: {
'app/layout.jsx': `
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
`,
'app/page.jsx': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
deploymentId: () => {
return null
}
}
`,
},
dependencies: {},
})
} catch (err: any) {
errorThrown = true
// The error is thrown in the child process, so we just verify that createNext fails
// The actual error message "deploymentId function must return a string" is visible
// in the console output but wrapped differently in different modes:
// - Start mode: "next build failed with code/signal 1"
// - Deploy mode: "Failed to deploy project"
expect(err).toBeDefined()
expect(
err.message.includes('build failed') ||
err.message.includes('Failed to deploy')
).toBe(true)
} finally {
if (nextInstance) {
await nextInstance.destroy()
}
}
// Ensure an error was actually thrown
expect(errorThrown).toBe(true)
})
it('should throw error when deploymentId exceeds 32 characters', async () => {
if (isNextDev) {
// Skip in dev mode - validation errors occur after server starts
return
}
let errorThrown = false
let nextInstance: NextInstance | undefined
try {
nextInstance = await createNext({
files: {
'app/layout.jsx': `
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
`,
'app/page.jsx': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
deploymentId: 'this-is-a-very-long-deployment-id-that-exceeds-32-characters'
}
`,
},
dependencies: {},
})
} catch (err: any) {
errorThrown = true
// The error is thrown in the child process, so we just verify that createNext fails
// The actual error message about exceeding 32 characters is visible in the console output
// but wrapped differently in different modes
expect(err).toBeDefined()
expect(
err.message.includes('build failed') ||
err.message.includes('Failed to deploy')
).toBe(true)
} finally {
if (nextInstance) {
await nextInstance.destroy()
}
}
// Ensure an error was actually thrown
expect(errorThrown).toBe(true)
})
it('should throw error when deploymentId function returns string exceeding 32 characters', async () => {
if (isNextDev) {
// Skip in dev mode - validation errors occur after server starts
return
}
let errorThrown = false
let nextInstance: NextInstance | undefined
try {
nextInstance = await createNext({
files: {
'app/layout.jsx': `
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
`,
'app/page.jsx': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
deploymentId: () => {
return 'this-is-a-very-long-deployment-id-that-exceeds-32-characters'
}
}
`,
},
dependencies: {},
})
} catch (err: any) {
errorThrown = true
// The error is thrown in the child process, so we just verify that createNext fails
// The actual error message about exceeding 32 characters is visible in the console output
// but wrapped differently in different modes
expect(err).toBeDefined()
expect(
err.message.includes('build failed') ||
err.message.includes('Failed to deploy')
).toBe(true)
} finally {
if (nextInstance) {
await nextInstance.destroy()
}
}
// Ensure an error was actually thrown
expect(errorThrown).toBe(true)
})
})
......@@ -20,6 +20,12 @@
],
"strictNullChecks": true
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"include": [
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.ts",
"**/*.tsx",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
/** @type {import('next').NextConfig} */
module.exports = {
deploymentId: process.env.CUSTOM_DEPLOYMENT_ID,
// Read deploymentId from env vars - CUSTOM_DEPLOYMENT_ID takes precedence for explicit tests
// If CUSTOM_DEPLOYMENT_ID is not set, fall back to NEXT_DEPLOYMENT_ID
// This ensures NEXT_DEPLOYMENT_ID is available when next.config.js is loaded,
// which happens before loadEnvConfig might reset process.env
deploymentId:
process.env.CUSTOM_DEPLOYMENT_ID ||
process.env.NEXT_DEPLOYMENT_ID ||
undefined,
experimental: {
useSkewCookie: Boolean(process.env.COOKIE_SKEW),
runtimeServerDeploymentId: !!process.env.RUNTIME_SERVER_DEPLOYMENT_ID,
......
......@@ -27,6 +27,18 @@ async function readFiles(next: NextInstance) {
)
}
// TODO static/* browser chunks are content hashed and have the deployment id inlined
const IGNORE_NAME = new RegExp(
[
'static/chunks/',
'.*_buildManifest\\.js',
'.*_ssgManifest\\.js',
'.*_clientMiddlewareManifest\\.js',
]
.map((v) => '(?:\\/|^)' + v + '$')
.join('|')
)
const IGNORE_CONTENT = new RegExp(
[
// TODO this contains "env": { "__NEXT_BUILD_ID": "taBOOu8Znzobe4G7wEG_i",
......@@ -41,6 +53,10 @@ const IGNORE_CONTENT = new RegExp(
// These are not critical, as they aren't deployed to the serverless function itself
'client-build-manifest\\.json',
'fallback-build-manifest\\.json',
// TODO These contain manifest file paths that include build IDs
'build-manifest\\.json',
'middleware-build-manifest\\.js',
// Contains the deploymentId which is expected to change between deployments
'routes-manifest\\.json',
]
.map((v) => '(?:\\/|^)' + v + '$')
......@@ -86,6 +102,9 @@ const IGNORE_CONTENT = new RegExp(
await next.build()
let run2 = await readFiles(next)
run1 = run1.filter(([f, _]) => !IGNORE_NAME.test(f))
run2 = run2.filter(([f, _]) => !IGNORE_NAME.test(f))
// First, compare file names
let run1FileNames = run1.map(([f, _]) => f)
let run2FileNames = run2.map(([f, _]) => f)
......
This diff is collapsed.
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