Unverified Commit 201c9604 authored by Brooke's avatar Brooke Committed by GitHub

Revert "[prebuilt-skew-protection] feat: adding in automatic deploymentId" (#88449)

Reverts vercel/next.js#88012
parent 0daf2b58
---
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
...@@ -977,8 +977,5 @@ ...@@ -977,8 +977,5 @@
"976": "Decompressed resume data cache exceeded %s byte limit", "976": "Decompressed resume data cache exceeded %s byte limit",
"977": "maxPostponedStateSize must be a valid number (bytes) or filesize format string (e.g., \"5mb\")", "977": "maxPostponedStateSize must be a valid number (bytes) or filesize format string (e.g., \"5mb\")",
"978": "Next.js has blocked a javascript: URL as a security precaution.", "978": "Next.js has blocked a javascript: URL as a security precaution.",
"979": "invariant: expected %s bytes of postponed state but only received %s bytes", "979": "invariant: expected %s bytes of postponed state but only received %s bytes"
"980": "deploymentId function must return a string. https://nextjs.org/docs/messages/deploymentid-not-a-string",
"981": "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",
"982": "The deploymentId \"%s\" exceeds the maximum length of 32 characters. Please choose a shorter deploymentId in your next.config.js. https://nextjs.org/docs/messages/deploymentid-too-long"
} }
...@@ -386,11 +386,6 @@ export interface NextAdapter { ...@@ -386,11 +386,6 @@ export interface NextAdapter {
* influenced by NextConfig.generateBuildId * influenced by NextConfig.generateBuildId
*/ */
buildId: string 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 }) => Promise<void> | void
} }
...@@ -420,7 +415,6 @@ export async function handleBuildComplete({ ...@@ -420,7 +415,6 @@ export async function handleBuildComplete({
config, config,
appType, appType,
buildId, buildId,
deploymentId,
configOutDir, configOutDir,
distDir, distDir,
pageKeys, pageKeys,
...@@ -444,7 +438,6 @@ export async function handleBuildComplete({ ...@@ -444,7 +438,6 @@ export async function handleBuildComplete({
appType: 'app' | 'pages' | 'hybrid' appType: 'app' | 'pages' | 'hybrid'
distDir: string distDir: string
buildId: string buildId: string
deploymentId: string
configOutDir: string configOutDir: string
adapterPath: string adapterPath: string
tracingRoot: string tracingRoot: string
...@@ -1863,7 +1856,6 @@ export async function handleBuildComplete({ ...@@ -1863,7 +1856,6 @@ export async function handleBuildComplete({
config, config,
distDir, distDir,
buildId, buildId,
deploymentId,
nextVersion, nextVersion,
projectDir: dir, projectDir: dir,
repoRoot: tracingRoot, repoRoot: tracingRoot,
......
...@@ -21,7 +21,6 @@ import loadCustomRoutes from '../../lib/load-custom-routes' ...@@ -21,7 +21,6 @@ import loadCustomRoutes from '../../lib/load-custom-routes'
import { generateRoutesManifest } from '../generate-routes-manifest' import { generateRoutesManifest } from '../generate-routes-manifest'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr' import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { resolveAndSetDeploymentId } from '../generate-deployment-id'
import http from 'node:http' import http from 'node:http'
// @ts-expect-error types are in @types/serve-handler // @ts-expect-error types are in @types/serve-handler
...@@ -54,9 +53,7 @@ export default async function analyze({ ...@@ -54,9 +53,7 @@ export default async function analyze({
reactProductionProfiling, reactProductionProfiling,
}) })
// Generate deploymentId - can be a string or function process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
// Call the function once and cache the result to ensure consistency throughout the analyze process
config.deploymentId = resolveAndSetDeploymentId(config.deploymentId)
const distDir = path.join(dir, '.next') const distDir = path.join(dir, '.next')
const telemetry = new Telemetry({ distDir }) const telemetry = new Telemetry({ distDir })
......
...@@ -44,7 +44,6 @@ export interface DefineEnvOptions { ...@@ -44,7 +44,6 @@ export interface DefineEnvOptions {
interface DefineEnv { interface DefineEnv {
[key: string]: [key: string]:
| string | string
| (() => string)
| string[] | string[]
| boolean | boolean
| ProxyMatcher[] | ProxyMatcher[]
......
/**
* 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
}
/**
* 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.
* If configDeploymentId is already a string, it was evaluated earlier - use it directly.
* If configDeploymentId is a function, evaluate it once here (regardless of NEXT_DEPLOYMENT_ID).
* Only sets NEXT_DEPLOYMENT_ID if it wasn't already set (to avoid overwriting if function was called before).
*
* @param configDeploymentId - The deploymentId from config (can be string, function, or undefined)
* @returns The resolved deploymentId string to use
*/
export function resolveAndSetDeploymentId(
configDeploymentId: string | (() => string) | undefined
): string {
// User-configured deploymentId always takes precedence over NEXT_DEPLOYMENT_ID
// Evaluate function once if needed (if it's a function, not already a string)
let userConfiguredDeploymentId: string | undefined
if (typeof configDeploymentId === 'string') {
// Already evaluated earlier (e.g., in config.ts), use the cached value
// This ensures the function is only called once
userConfiguredDeploymentId = configDeploymentId
} else if (configDeploymentId != null) {
// Function hasn't been evaluated yet - evaluate it once now
// We evaluate regardless of NEXT_DEPLOYMENT_ID to ensure user config can take precedence
userConfiguredDeploymentId = generateDeploymentId(configDeploymentId)
} else {
// No user configuration provided
userConfiguredDeploymentId = undefined
}
// Validate length early (before setting env var or returning)
if (userConfiguredDeploymentId !== undefined) {
if (userConfiguredDeploymentId.length > 32) {
throw new Error(
`The deploymentId "${userConfiguredDeploymentId}" exceeds the maximum length of 32 characters. Please choose a shorter deploymentId in your next.config.js. https://nextjs.org/docs/messages/deploymentid-too-long`
)
}
if (userConfiguredDeploymentId.startsWith('dpl_')) {
throw new Error(
`The deploymentId "${userConfiguredDeploymentId}" 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`
)
}
}
// User-configured deploymentId always takes precedence over NEXT_DEPLOYMENT_ID
if (userConfiguredDeploymentId !== undefined) {
// User-configured deploymentId always takes precedence
// Use bracket notation to prevent webpack from replacing this at build time
process.env['NEXT_DEPLOYMENT_ID'] = userConfiguredDeploymentId
return userConfiguredDeploymentId
} else if (process.env['NEXT_DEPLOYMENT_ID'] != null) {
// No user config, use NEXT_DEPLOYMENT_ID if set
return process.env['NEXT_DEPLOYMENT_ID']
} else {
// Neither is set, use empty string
return ''
}
}
...@@ -35,7 +35,6 @@ export interface GenerateRoutesManifestOptions { ...@@ -35,7 +35,6 @@ export interface GenerateRoutesManifestOptions {
restrictedRedirectPaths: string[] restrictedRedirectPaths: string[]
isAppPPREnabled: boolean isAppPPREnabled: boolean
appType: 'pages' | 'app' | 'hybrid' appType: 'pages' | 'app' | 'hybrid'
deploymentId?: string
} }
export interface GenerateRoutesManifestResult { export interface GenerateRoutesManifestResult {
...@@ -61,7 +60,6 @@ export function generateRoutesManifest( ...@@ -61,7 +60,6 @@ export function generateRoutesManifest(
restrictedRedirectPaths, restrictedRedirectPaths,
isAppPPREnabled, isAppPPREnabled,
appType, appType,
deploymentId,
} = options } = options
const sortedRoutes = sortPages([...pageKeys.pages, ...(pageKeys.app ?? [])]) const sortedRoutes = sortPages([...pageKeys.pages, ...(pageKeys.app ?? [])])
...@@ -136,7 +134,6 @@ export function generateRoutesManifest( ...@@ -136,7 +134,6 @@ export function generateRoutesManifest(
queryHeader: NEXT_REWRITTEN_QUERY_HEADER, queryHeader: NEXT_REWRITTEN_QUERY_HEADER,
}, },
skipProxyUrlNormalize: config.skipProxyUrlNormalize, skipProxyUrlNormalize: config.skipProxyUrlNormalize,
deploymentId: deploymentId || undefined,
ppr: isAppPPREnabled ppr: isAppPPREnabled
? { ? {
chain: { chain: {
......
...@@ -128,8 +128,6 @@ import { sortByPageExts } from './sort-by-page-exts' ...@@ -128,8 +128,6 @@ import { sortByPageExts } from './sort-by-page-exts'
import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts' import { getStaticInfoIncludingLayouts } from './get-static-info-including-layouts'
import { PAGE_TYPES } from '../lib/page-types' import { PAGE_TYPES } from '../lib/page-types'
import { generateBuildId } from './generate-build-id' 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 { isWriteable } from './is-writeable'
import * as Log from './output/log' import * as Log from './output/log'
import createSpinner from './spinner' import createSpinner from './spinner'
...@@ -489,13 +487,6 @@ export type RoutesManifest = { ...@@ -489,13 +487,6 @@ export type RoutesManifest = {
} }
skipProxyUrlNormalize?: boolean skipProxyUrlNormalize?: boolean
caseSensitive?: 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. * Configuration related to Partial Prerendering.
*/ */
...@@ -973,9 +964,7 @@ export default async function build( ...@@ -973,9 +964,7 @@ export default async function build(
// Install the native bindings early so we can have synchronous access later. // Install the native bindings early so we can have synchronous access later.
await installBindings(config.experimental?.useWasmBinary) await installBindings(config.experimental?.useWasmBinary)
// Generate deploymentId - can be a string or function process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
// Call the function once and cache the result to ensure consistency throughout the build process
config.deploymentId = resolveAndSetDeploymentId(config.deploymentId)
NextBuildContext.config = config NextBuildContext.config = config
let configOutDir = 'out' let configOutDir = 'out'
...@@ -1020,7 +1009,7 @@ export default async function build( ...@@ -1020,7 +1009,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, config.deploymentId || '') populateStaticEnv(config, config.deploymentId)
} }
const customRoutes: CustomRoutes = await nextBuildSpan const customRoutes: CustomRoutes = await nextBuildSpan
...@@ -1624,7 +1613,6 @@ export default async function build( ...@@ -1624,7 +1613,6 @@ export default async function build(
rewrites, rewrites,
restrictedRedirectPaths, restrictedRedirectPaths,
isAppPPREnabled, isAppPPREnabled,
deploymentId: evaluateDeploymentId(config.deploymentId),
}) })
) )
...@@ -4161,7 +4149,6 @@ export default async function build( ...@@ -4161,7 +4149,6 @@ export default async function build(
config, config,
appType, appType,
buildId, buildId,
deploymentId: (config.deploymentId as string) || '',
configOutDir: path.join(dir, configOutDir), configOutDir: path.join(dir, configOutDir),
staticPages, staticPages,
serverPropsPages, serverPropsPages,
......
...@@ -53,7 +53,6 @@ import { Telemetry } from '../telemetry/storage' ...@@ -53,7 +53,6 @@ import { Telemetry } from '../telemetry/storage'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { evaluateDeploymentId } from '../server/evaluate-deployment-id'
import { isAPIRoute } from '../lib/is-api-route' import { isAPIRoute } from '../lib/is-api-route'
import { getPagePath } from '../server/require' import { getPagePath } from '../server/require'
import type { Span } from '../trace' import type { Span } from '../trace'
...@@ -387,7 +386,7 @@ async function exportAppImpl( ...@@ -387,7 +386,7 @@ async function exportAppImpl(
join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`) join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)
), ),
images: nextConfig.images, images: nextConfig.images,
deploymentId: evaluateDeploymentId(nextConfig.deploymentId), deploymentId: nextConfig.deploymentId,
htmlLimitedBots: nextConfig.htmlLimitedBots.source, htmlLimitedBots: nextConfig.htmlLimitedBots.source,
experimental: { experimental: {
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata, clientTraceMetadata: nextConfig.experimental.clientTraceMetadata,
......
...@@ -6,7 +6,6 @@ import globOriginal from 'next/dist/compiled/glob' ...@@ -6,7 +6,6 @@ import globOriginal from 'next/dist/compiled/glob'
import { Sema } from 'next/dist/compiled/async-sema' import { Sema } from 'next/dist/compiled/async-sema'
import type { NextConfigComplete } from '../server/config-shared' import type { NextConfigComplete } from '../server/config-shared'
import { getNextConfigEnv, getStaticEnv } from './static-env' import { getNextConfigEnv, getStaticEnv } from './static-env'
import { evaluateDeploymentId } from '../server/evaluate-deployment-id'
const glob = promisify(globOriginal) const glob = promisify(globOriginal)
...@@ -18,11 +17,7 @@ export async function inlineStaticEnv({ ...@@ -18,11 +17,7 @@ export async function inlineStaticEnv({
config: NextConfigComplete config: NextConfigComplete
}) { }) {
const nextConfigEnv = getNextConfigEnv(config) const nextConfigEnv = getNextConfigEnv(config)
// User-configured deploymentId takes precedence over NEXT_DEPLOYMENT_ID const staticEnv = getStaticEnv(config, config.deploymentId)
const deploymentId = evaluateDeploymentId(
config.deploymentId || process.env.NEXT_DEPLOYMENT_ID
)
const staticEnv = getStaticEnv(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}', {
......
...@@ -464,16 +464,12 @@ export default abstract class Server< ...@@ -464,16 +464,12 @@ export default abstract class Server<
} }
deploymentId = process.env.NEXT_DEPLOYMENT_ID deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else { } else {
// deploymentId is resolved to a string in config.ts via resolveAndSetDeploymentId
let id = this.nextConfig.experimental.useSkewCookie let id = this.nextConfig.experimental.useSkewCookie
? '' ? ''
: (this.nextConfig.deploymentId as string) || '' : this.nextConfig.deploymentId || ''
deploymentId = id deploymentId = id
// Use bracket notation to prevent webpack from replacing this at build time process.env.NEXT_DEPLOYMENT_ID = id
if (process.env['NEXT_DEPLOYMENT_ID'] == null) {
process.env['NEXT_DEPLOYMENT_ID'] = id
}
} }
this.hostname = hostname this.hostname = hostname
......
...@@ -1145,9 +1145,8 @@ export interface NextConfig { ...@@ -1145,9 +1145,8 @@ export interface NextConfig {
/** /**
* A unique identifier for a deployment that will be included in each request's query string or header. * 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 | (() => string) deploymentId?: string
/** /**
* Deploy a Next.js application under a sub-path of a domain * Deploy a Next.js application under a sub-path of a domain
......
...@@ -45,7 +45,6 @@ import { djb2Hash } from '../shared/lib/hash' ...@@ -45,7 +45,6 @@ import { djb2Hash } from '../shared/lib/hash'
import type { NextAdapter } from '../build/adapter/build-complete' import type { NextAdapter } from '../build/adapter/build-complete'
import { HardDeprecatedConfigError } from '../shared/lib/errors/hard-deprecated-config-error' import { HardDeprecatedConfigError } from '../shared/lib/errors/hard-deprecated-config-error'
import { NextInstanceErrorState } from './mcp/tools/next-instance-error-state' import { NextInstanceErrorState } from './mcp/tools/next-instance-error-state'
import { evaluateDeploymentId } from './evaluate-deployment-id'
export { normalizeConfig } from './config-shared' export { normalizeConfig } from './config-shared'
export type { DomainLocale, NextConfig } from './config-shared' export type { DomainLocale, NextConfig } from './config-shared'
...@@ -925,29 +924,28 @@ function assignDefaultsAndValidate( ...@@ -925,29 +924,28 @@ function assignDefaultsAndValidate(
} }
} }
// Evaluate deploymentId early if it's a function, so it's available as a string
// User-configured deploymentId always takes precedence over NEXT_DEPLOYMENT_ID env var
// This ensures the function is only called once and the result is cached
if (result.deploymentId != null) {
result.deploymentId = evaluateDeploymentId(result.deploymentId)
// Set process.env so it's available to other parts of the system
if (process.env['NEXT_DEPLOYMENT_ID'] == null) {
process.env['NEXT_DEPLOYMENT_ID'] = result.deploymentId
}
} else if (process.env.NEXT_DEPLOYMENT_ID) {
// No user config, fall back to NEXT_DEPLOYMENT_ID env var
result.deploymentId = process.env.NEXT_DEPLOYMENT_ID
}
if ( if (
result.experimental.runtimeServerDeploymentId == null && result.experimental.runtimeServerDeploymentId == null &&
phase === PHASE_PRODUCTION_BUILD && phase === PHASE_PRODUCTION_BUILD &&
ciEnvironment.hasNextSupport && ciEnvironment.hasNextSupport &&
process.env.NEXT_DEPLOYMENT_ID 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 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 tracingRoot = result?.outputFileTracingRoot
const turbopackRoot = result?.turbopack?.root const turbopackRoot = result?.turbopack?.root
......
/**
* 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,7 +57,6 @@ import type { BaseNextRequest } from '../base-http' ...@@ -57,7 +57,6 @@ import type { BaseNextRequest } from '../base-http'
import type { I18NConfig, NextConfigRuntime } from '../config-shared' import type { I18NConfig, NextConfigRuntime } from '../config-shared'
import ResponseCache, { type ResponseGenerator } from '../response-cache' import ResponseCache, { type ResponseGenerator } from '../response-cache'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { evaluateDeploymentId } from '../evaluate-deployment-id'
import { import {
RouterServerContextSymbol, RouterServerContextSymbol,
routerServerGlobal, routerServerGlobal,
...@@ -545,8 +544,7 @@ export abstract class RouteModule< ...@@ -545,8 +544,7 @@ export abstract class RouteModule<
} }
deploymentId = process.env.NEXT_DEPLOYMENT_ID deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else { } else {
// evaluateDeploymentId handles string, function, and undefined cases deploymentId = nextConfig.deploymentId || ''
deploymentId = evaluateDeploymentId(nextConfig.deploymentId)
} }
return { nextConfig, deploymentId } return { nextConfig, deploymentId }
...@@ -947,8 +945,7 @@ export abstract class RouteModule< ...@@ -947,8 +945,7 @@ export abstract class RouteModule<
} }
deploymentId = process.env.NEXT_DEPLOYMENT_ID deploymentId = process.env.NEXT_DEPLOYMENT_ID
} else { } else {
// evaluateDeploymentId handles string, function, and undefined cases deploymentId = nextConfig.deploymentId || ''
deploymentId = evaluateDeploymentId(nextConfig.deploymentId)
} }
return { return {
......
import { createNext, isNextDev } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
describe('deploymentId function support', () => {
let next: NextInstance | undefined
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'
}
`,
},
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'
}
}
`,
},
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',
},
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'
}
}
`,
},
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')
}
})
// 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)
})
})
...@@ -42,8 +42,6 @@ const IGNORE_CONTENT = new RegExp( ...@@ -42,8 +42,6 @@ const IGNORE_CONTENT = new RegExp(
'client-build-manifest\\.json', 'client-build-manifest\\.json',
'fallback-build-manifest\\.json', 'fallback-build-manifest\\.json',
'middleware-build-manifest\\.js', 'middleware-build-manifest\\.js',
// Contains the deploymentId which is expected to change between deployments
'routes-manifest\\.json',
] ]
.map((v) => '(?:\\/|^)' + v + '$') .map((v) => '(?:\\/|^)' + v + '$')
.join('|') .join('|')
......
import { generateDeploymentId } from 'next/dist/build/generate-deployment-id'
describe('generateDeploymentId', () => {
it('should return undefined when deploymentId is undefined', () => {
expect(generateDeploymentId(undefined)).toBeUndefined()
})
it('should return string when deploymentId is a string', () => {
expect(generateDeploymentId('my-deployment-123')).toBe('my-deployment-123')
expect(generateDeploymentId(' my-deployment-123 ')).toBe(
' my-deployment-123 '
)
})
it('should call function and return string when deploymentId is a function', () => {
const fn = () => 'my-deployment-123'
expect(generateDeploymentId(fn)).toBe('my-deployment-123')
const fnWithWhitespace = () => ' my-deployment-123 '
expect(generateDeploymentId(fnWithWhitespace)).toBe(' my-deployment-123 ')
})
it('should throw error when function returns non-string', () => {
const fn = () => 123 as any
expect(() => generateDeploymentId(fn)).toThrow(
'deploymentId function must return a string'
)
})
it('should handle function that returns empty string', () => {
const fn = () => ''
expect(generateDeploymentId(fn)).toBe('')
})
it('should handle empty string deploymentId', () => {
expect(generateDeploymentId('')).toBe('')
expect(generateDeploymentId(' ')).toBe(' ')
})
})
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