Commit a3707f5a authored by Steven's avatar Steven

feat: add `deploymentId` config (#63198)

This PR stabilizes an experimental feature that was added in a previous
PR https://github.com/vercel/next.js/pull/50470

It allows the user to set `deploymentId` in `next.config.js`, which is a
unique identifier for a deployment that will be included in each
request's query string or header.

This PR is easier to review with whitespace hidden:
https://github.com/vercel/next.js/pull/63198/files?w=1

Closes NEXT-2789
parent f904dcd4
...@@ -210,11 +210,13 @@ module.exports = { ...@@ -210,11 +210,13 @@ module.exports = {
### Version Skew ### Version Skew
Next.js will automatically mitigate most instances of [version skew](https://www.industrialempathy.com/posts/version-skew/) and automatically reload the application to retrieve new assets when detected. For example, if there is a mismatch in the build ID, transitions between pages will perform a hard navigation versus using a prefetched value. Next.js will automatically mitigate most instances of [version skew](https://www.industrialempathy.com/posts/version-skew/) and automatically reload the application to retrieve new assets when detected. For example, if there is a mismatch in the `deploymentId`, transitions between pages will perform a hard navigation versus using a prefetched value.
When the application is reloaded, there may be a loss of application state if it's not designed to persist between page navigations. For example, using URL state or local storage would persist state after a page refresh. However, component state like `useState` would be lost in such navigations. When the application is reloaded, there may be a loss of application state if it's not designed to persist between page navigations. For example, using URL state or local storage would persist state after a page refresh. However, component state like `useState` would be lost in such navigations.
Vercel provides additional [skew protection](https://vercel.com/docs/deployments/skew-protection?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) for Next.js applications to ensure assets and functions from the previous build are still available while the new build is being deployed. Vercel provides additional [skew protection](https://vercel.com/docs/deployments/skew-protection?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) for Next.js applications to ensure assets and functions from the previous version are still available to older clients, even after the new version is deployed.
You can manually configure the `deploymentId` property in your `next.config.js` file to ensure each request uses either `?dpl` query string or `x-deployment-id` header.
<PagesOnly> <PagesOnly>
......
...@@ -730,7 +730,7 @@ export default async function build( ...@@ -730,7 +730,7 @@ export default async function build(
}) })
) )
process.env.NEXT_DEPLOYMENT_ID = config.experimental.deploymentId || '' process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
NextBuildContext.config = config NextBuildContext.config = config
let configOutDir = 'out' let configOutDir = 'out'
......
...@@ -96,11 +96,8 @@ export function getDefineEnv({ ...@@ -96,11 +96,8 @@ export function getDefineEnv({
), ),
'process.env.NEXT_MINIMAL': JSON.stringify(''), 'process.env.NEXT_MINIMAL': JSON.stringify(''),
'process.env.__NEXT_PPR': JSON.stringify(config.experimental.ppr === true), 'process.env.__NEXT_PPR': JSON.stringify(config.experimental.ppr === true),
'process.env.__NEXT_ACTIONS_DEPLOYMENT_ID': JSON.stringify(
config.experimental.useDeploymentIdServerActions
),
'process.env.NEXT_DEPLOYMENT_ID': JSON.stringify( 'process.env.NEXT_DEPLOYMENT_ID': JSON.stringify(
config.experimental.deploymentId || false config.deploymentId || false
), ),
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX': 'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX':
JSON.stringify(fetchCacheKeyPrefix), JSON.stringify(fetchCacheKeyPrefix),
......
...@@ -70,8 +70,7 @@ async function fetchServerAction( ...@@ -70,8 +70,7 @@ async function fetchServerAction(
Accept: RSC_CONTENT_TYPE_HEADER, Accept: RSC_CONTENT_TYPE_HEADER,
[ACTION]: actionId, [ACTION]: actionId,
[NEXT_ROUTER_STATE_TREE]: encodeURIComponent(JSON.stringify(state.tree)), [NEXT_ROUTER_STATE_TREE]: encodeURIComponent(JSON.stringify(state.tree)),
...(process.env.__NEXT_ACTIONS_DEPLOYMENT_ID && ...(process.env.NEXT_DEPLOYMENT_ID
process.env.NEXT_DEPLOYMENT_ID
? { ? {
'x-deployment-id': process.env.NEXT_DEPLOYMENT_ID, 'x-deployment-id': process.env.NEXT_DEPLOYMENT_ID,
} }
......
...@@ -505,7 +505,7 @@ export async function exportAppImpl( ...@@ -505,7 +505,7 @@ export async function exportAppImpl(
} }
: {}), : {}),
strictNextHead: !!nextConfig.experimental.strictNextHead, strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId, deploymentId: nextConfig.deploymentId,
experimental: { experimental: {
ppr: nextConfig.experimental.ppr === true, ppr: nextConfig.experimental.ppr === true,
missingSuspenseWithCSRBailout: missingSuspenseWithCSRBailout:
......
...@@ -501,13 +501,12 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -501,13 +501,12 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.nextFontManifest = this.getNextFontManifest() this.nextFontManifest = this.getNextFontManifest()
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
process.env.NEXT_DEPLOYMENT_ID = process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''
this.nextConfig.experimental.deploymentId || ''
} }
this.renderOpts = { this.renderOpts = {
trailingSlash: this.nextConfig.trailingSlash, trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.experimental.deploymentId, deploymentId: this.nextConfig.deploymentId,
strictNextHead: !!this.nextConfig.experimental.strictNextHead, strictNextHead: !!this.nextConfig.experimental.strictNextHead,
poweredByHeader: this.nextConfig.poweredByHeader, poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '', canonicalBase: this.nextConfig.amp.canonicalBase || '',
......
...@@ -204,6 +204,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -204,6 +204,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
z.literal('use-credentials'), z.literal('use-credentials'),
]) ])
.optional(), .optional(),
deploymentId: z.string().optional(),
devIndicators: z devIndicators: z
.object({ .object({
buildActivity: z.boolean().optional(), buildActivity: z.boolean().optional(),
...@@ -247,9 +248,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -247,9 +248,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
memoryBasedWorkersCount: z.boolean().optional(), memoryBasedWorkersCount: z.boolean().optional(),
craCompat: z.boolean().optional(), craCompat: z.boolean().optional(),
caseSensitiveRoutes: z.boolean().optional(), caseSensitiveRoutes: z.boolean().optional(),
useDeploymentId: z.boolean().optional(),
useDeploymentIdServerActions: z.boolean().optional(),
deploymentId: z.string().optional(),
disableOptimizedLoading: z.boolean().optional(), disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(), disablePostcssPresetEnv: z.boolean().optional(),
esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(), esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),
......
...@@ -160,9 +160,6 @@ export interface NextJsWebpackConfig { ...@@ -160,9 +160,6 @@ export interface NextJsWebpackConfig {
export interface ExperimentalConfig { export interface ExperimentalConfig {
caseSensitiveRoutes?: boolean caseSensitiveRoutes?: boolean
useDeploymentId?: boolean
useDeploymentIdServerActions?: boolean
deploymentId?: string
appDocumentPreloading?: boolean appDocumentPreloading?: boolean
strictNextHead?: boolean strictNextHead?: boolean
clientRouterFilter?: boolean clientRouterFilter?: boolean
...@@ -591,6 +588,11 @@ export interface NextConfig extends Record<string, any> { ...@@ -591,6 +588,11 @@ export interface NextConfig extends Record<string, any> {
canonicalBase?: string canonicalBase?: string
} }
/**
* A unique identifier for a deployment that will be included in each request's query string or header.
*/
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
* *
...@@ -812,9 +814,6 @@ export const defaultConfig: NextConfig = { ...@@ -812,9 +814,6 @@ export const defaultConfig: NextConfig = {
serverMinification: true, serverMinification: true,
serverSourceMaps: false, serverSourceMaps: false,
caseSensitiveRoutes: false, caseSensitiveRoutes: false,
useDeploymentId: false,
deploymentId: undefined,
useDeploymentIdServerActions: false,
appDocumentPreloading: undefined, appDocumentPreloading: undefined,
clientRouterFilter: true, clientRouterFilter: true,
clientRouterFilterRedirects: false, clientRouterFilterRedirects: false,
......
...@@ -601,16 +601,8 @@ function assignDefaults( ...@@ -601,16 +601,8 @@ function assignDefaults(
} }
// only leverage deploymentId // only leverage deploymentId
if (result.experimental?.useDeploymentId && process.env.NEXT_DEPLOYMENT_ID) { if (process.env.NEXT_DEPLOYMENT_ID) {
if (!result.experimental) { result.deploymentId = process.env.NEXT_DEPLOYMENT_ID
result.experimental = {}
}
result.experimental.deploymentId = process.env.NEXT_DEPLOYMENT_ID
}
// can't use this one without the other
if (result.experimental?.useDeploymentIdServerActions) {
result.experimental.useDeploymentId = true
} }
// use the closest lockfile as tracing root // use the closest lockfile as tracing root
......
...@@ -194,8 +194,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -194,8 +194,7 @@ 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 = process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''
this.nextConfig.experimental.deploymentId || ''
if (!this.minimalMode) { if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode) this.imageResponseCache = new ResponseCache(this.minimalMode)
......
/** @type {import('next').NextConfig} */
module.exports = { module.exports = {
experimental: { deploymentId: process.env.CUSTOM_DEPLOYMENT_ID,
useDeploymentId: !!process.env.USE_DEPLOYMENT_ID,
},
} }
import { createNextDescribe } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { check } from 'next-test-utils'
import { join } from 'node:path' import { join } from 'node:path'
const deploymentId = Date.now() + '' describe.each(['NEXT_DEPLOYMENT_ID', 'CUSTOM_DEPLOYMENT_ID'])(
'deployment-id-handling enabled with %s',
createNextDescribe( (envKey) => {
'deployment-id-handling enabled', const deploymentId = Date.now() + ''
{ const { next } = nextTestSetup({
files: join(__dirname, 'app'), files: join(__dirname, 'app'),
env: { env: {
NEXT_DEPLOYMENT_ID: deploymentId, [envKey]: deploymentId,
USE_DEPLOYMENT_ID: '1',
},
}, },
({ next }) => { })
it.each([ it.each([
{ urlPath: '/' }, { urlPath: '/' },
{ urlPath: '/pages-edge' }, { urlPath: '/pages-edge' },
...@@ -84,16 +83,11 @@ createNextDescribe( ...@@ -84,16 +83,11 @@ createNextDescribe(
) )
} }
) )
describe('deployment-id-handling disabled', () => {
createNextDescribe( const deploymentId = Date.now() + ''
'deployment-id-handling disabled', const { next } = nextTestSetup({
{
files: join(__dirname, 'app'), files: join(__dirname, 'app'),
env: { })
NEXT_DEPLOYMENT_ID: deploymentId,
},
},
({ next }) => {
it.each([ it.each([
{ urlPath: '/' }, { urlPath: '/' },
{ urlPath: '/pages-edge' }, { urlPath: '/pages-edge' },
...@@ -151,16 +145,4 @@ createNextDescribe( ...@@ -151,16 +145,4 @@ createNextDescribe(
} }
} }
) )
})
it.each([{ pathname: '/api/hello' }, { pathname: '/api/hello-app' }])(
'should not have deployment id env available',
async ({ pathname }) => {
const res = await next.fetch(pathname)
expect(await res.json()).not.toEqual({
deploymentId,
})
}
)
}
)
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