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

Replace flight navigation build id field with header (#88855)

Closes PACK-6536

- with deployment id available: a header contains the process.env.NEXT_DEPLOYMENT_ID , the client knows its dpl id already, so we can use that already
- with deployment id unavailable: a response field contains the BUILD_ID, keep the existing logic of storing the build id in the browser

It's unfortunate that we have to keep the BUILD_ID response field approach as a fallback, but oh well.
This has the benefit that we won't need the build id anymore when the deployment id is available.

If you use `output:export` and set `config.deploymentId` (i.e. enable skew protection) you are still expected to set these headers.

---

- [x] Fallback behavior for when there is no deployment id
- [ ] Run deployment tests
parent 7437fed8
......@@ -901,7 +901,7 @@ async function getBuildId(
config: NextConfigComplete
) {
if (isGenerateMode) {
return await fs.readFile(path.join(distDir, 'BUILD_ID'), 'utf8')
return await fs.readFile(path.join(distDir, BUILD_ID_FILE), 'utf8')
}
return await nextBuildSpan
.traceChild('generate-buildid')
......
......@@ -55,6 +55,7 @@ import {
CACHE_ONE_YEAR,
HTML_CONTENT_TYPE_HEADER,
NEXT_CACHE_TAGS_HEADER,
NEXT_NAV_DEPLOYMENT_ID_HEADER,
NEXT_RESUME_HEADER,
NEXT_RESUME_STATE_LENGTH_HEADER,
} from '../../lib/constants'
......@@ -1145,6 +1146,15 @@ export async function handler(
const didPostpone = typeof cacheEntry.value.postponed === 'string'
// Set the build ID header for RSC navigation requests when deploymentId is configured. This
// corresponds with maybeAppendBuildIdToRSCPayload in app-render.tsx which omits the build ID
// from the RSC payload when deploymentId is set (relying on this header instead). Server
// actions are excluded because the client doesn't check the build ID for action responses.
// For static prerenders served from CDN, routes-manifest.json adds a header.
if (isRSCRequest && !isPossibleServerAction && deploymentId) {
res.setHeader(NEXT_NAV_DEPLOYMENT_ID_HEADER, deploymentId)
}
if (
isSSG &&
// We don't want to send a cache header for requests that contain dynamic
......
......@@ -23,9 +23,10 @@ import AppRouter from './components/app-router'
import type { InitialRSCPayload } from '../shared/lib/app-router-types'
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state'
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime'
import { setAppBuildId } from './app-build-id'
import type { StaticIndicatorState } from './dev/hot-reloader/app/hot-reloader-app'
import { createInitialRSCPayloadFromFallbackPrerender } from './flight-data-helpers'
import { getDeploymentId } from '../shared/lib/deployment-id'
import { setNavigationBuildId } from './navigation-build-id'
/// <reference types="react-dom/experimental" />
......@@ -307,9 +308,14 @@ export async function hydrate(
webSocket = createWebSocket(assetPrefix, staticIndicatorState)
}
const initialRSCPayload = await initialServerResponse
// setAppBuildId should be called only once, during JS initialization
// setNavigationBuildId should be called only once, during JS initialization
// and before any components have hydrated.
setAppBuildId(initialRSCPayload.b)
if (initialRSCPayload.b) {
setNavigationBuildId(initialRSCPayload.b!)
} else {
setNavigationBuildId(getDeploymentId()!)
}
const initialTimestamp = Date.now()
const actionQueue: AppRouterActionQueue = createMutableActionQueue(
......
......@@ -33,11 +33,12 @@ import {
prepareFlightRouterStateForRequest,
type NormalizedFlightData,
} from '../../flight-data-helpers'
import { getAppBuildId } from '../../app-build-id'
import { setCacheBustingSearchParam } from './set-cache-busting-search-param'
import { urlToUrlWithoutFlightMarker } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key'
import { getDeploymentId } from '../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
......@@ -241,7 +242,11 @@ export async function fetchServerResponse(
const flightResponse = await flightResponsePromise
if (getAppBuildId() !== flightResponse.b) {
if (
(res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==
getNavigationBuildId()
) {
// The server build does not match the client build.
return doMpaNavigation(res.url)
}
......
......@@ -53,7 +53,6 @@ import {
getPartialLayoutVaryPath,
getRenderedSearchFromVaryPath,
} from './vary-path'
import { getAppBuildId } from '../../app-build-id'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import type {
NormalizedPathname,
......@@ -104,6 +103,8 @@ import { FetchStrategy } from './types'
import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'
import { readFromBFCacheDuringRegularNavigation } from './bfcache'
import { discoverKnownRoute, matchKnownRoute } from './optimistic-routes'
import { getNavigationBuildId } from '../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
/**
* Ensures a minimum stale time of 30s to avoid issues where the server sends a too
......@@ -1685,12 +1686,13 @@ export async function fetchRouteOnCacheMiss(
prefetchStream,
headers
)
if (serverData.buildId !== getAppBuildId()) {
if (
(response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
serverData.buildId) !== getNavigationBuildId()
) {
// The server build does not match the client. Treat as a 404. During
// an actual navigation, the router will trigger an MPA navigation.
// TODO: Consider moving the build ID to a response header so we can check
// it before decoding the response, and so there's one way of checking
// across all response types.
// TODO: We should cache the fact that this is an MPA navigation.
rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)
return null
......@@ -1749,12 +1751,13 @@ export async function fetchRouteOnCacheMiss(
prefetchStream,
headers
)
if (serverData.b !== getAppBuildId()) {
if (
(response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
serverData.b) !== getNavigationBuildId()
) {
// The server build does not match the client. Treat as a 404. During
// an actual navigation, the router will trigger an MPA navigation.
// TODO: Consider moving the build ID to a response header so we can check
// it before decoding the response, and so there's one way of checking
// across all response types.
// TODO: We should cache the fact that this is an MPA navigation.
rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)
return null
......@@ -1898,16 +1901,16 @@ export async function fetchSegmentOnCacheMiss(
setSizeInCacheMap(segmentCacheEntry, size)
}
)
const serverData = await (createFromNextReadableStream(
const serverData = await createFromNextReadableStream<SegmentPrefetch>(
prefetchStream,
headers
) as Promise<SegmentPrefetch>)
if (serverData.buildId !== getAppBuildId()) {
)
if (
(response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
serverData.buildId) !== getNavigationBuildId()
) {
// The server build does not match the client. Treat as a 404. During
// an actual navigation, the router will trigger an MPA navigation.
// TODO: Consider moving the build ID to a response header so we can check
// it before decoding the response, and so there's one way of checking
// across all response types.
rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)
return null
}
......@@ -2049,10 +2052,11 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
}
}
)
const serverData = await (createFromNextReadableStream(
prefetchStream,
headers
) as Promise<NavigationFlightResponse>)
const serverData =
await createFromNextReadableStream<NavigationFlightResponse>(
prefetchStream,
headers
)
const isResponsePartial =
fetchStrategy === FetchStrategy.PPRRuntime
......@@ -2216,12 +2220,12 @@ function writeDynamicRenderResponseIntoCache(
route: FulfilledRouteCacheEntry,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null
): Array<FulfilledSegmentCacheEntry> | null {
if (serverData.b !== getAppBuildId()) {
if (
(response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b) !==
getNavigationBuildId()
) {
// The server build does not match the client. Treat as a 404. During
// an actual navigation, the router will trigger an MPA navigation.
// TODO: Consider moving the build ID to a response header so we can check
// it before decoding the response, and so there's one way of checking
// across all response types.
if (spawnedEntries !== null) {
rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)
}
......
......@@ -99,8 +99,7 @@ export function createInitialRSCPayloadFromFallbackPrerender(
const canonicalUrl = createHrefFromUrl(new URL(location.href))
const originalFlightDataPath = fallbackInitialRSCPayload.f[0]
const originalFlightRouterState = originalFlightDataPath[0]
return {
b: fallbackInitialRSCPayload.b,
const payload: InitialRSCPayload = {
c: canonicalUrl.split('/'),
q: renderedSearch,
i: fallbackInitialRSCPayload.i,
......@@ -121,6 +120,10 @@ export function createInitialRSCPayloadFromFallbackPrerender(
S: fallbackInitialRSCPayload.S,
h: fallbackInitialRSCPayload.h,
}
if (fallbackInitialRSCPayload.b) {
payload.b = fallbackInitialRSCPayload.b
}
return payload
}
function fillInFallbackFlightRouterState(
......
......@@ -5,18 +5,21 @@
// When performing RSC requests, if the incoming data has a different build ID,
// we perform an MPA navigation/refresh to load the updated build and ensure
// that the client and server in sync.
// Starts as an empty string. In practice, because setAppBuildId is called
// during initialization before hydration starts, this will always get
// reassigned to the actual build ID before it's ever needed by a navigation.
// If for some reasons it didn't, due to a bug or race condition, then on
//
// Starts as an empty string. In practice, because setNavigationBuildId is called during initialization
// before hydration starts, this will always get reassigned to the actual ID before it's ever needed
// by a navigation. If for some reasons it didn't, due to a bug or race condition, then on
// navigation the build comparision would fail and trigger an MPA navigation.
//
// Note that this can also be initialized with the deployment id instead (if available). So it's not
// the same as "the build id", but we are running out of alternative names for "build id or
// deployment id".
let globalBuildId: string = ''
export function setAppBuildId(buildId: string) {
export function setNavigationBuildId(buildId: string) {
globalBuildId = buildId
}
export function getAppBuildId(): string {
export function getNavigationBuildId(): string {
return globalBuildId
}
......@@ -19,6 +19,8 @@ export const NEXT_DATA_SUFFIX = '.json'
export const NEXT_META_SUFFIX = '.meta'
export const NEXT_BODY_SUFFIX = '.body'
export const NEXT_NAV_DEPLOYMENT_ID_HEADER = 'x-nextjs-deployment-id'
export const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags'
export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'
export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER =
......
......@@ -6,6 +6,7 @@ import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import { tryToParsePath } from './try-to-parse-path'
import { allowedStatusCodes } from './redirect-status'
import { isFullStringUrl } from './url'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from './constants'
export type RouteHas =
| {
......@@ -746,13 +747,32 @@ export default async function loadCustomRoutes(
)
}
if (config.experimental?.useSkewCookie && config.deploymentId) {
if (config.deploymentId) {
if (config.experimental?.useSkewCookie) {
headers.unshift({
source: '/:path*',
headers: [
{
key: 'Set-Cookie',
value: `__vdpl=${config.deploymentId}; Path=/; HttpOnly`,
},
],
})
}
headers.unshift({
source: '/:path*',
has: [
{
type: 'header',
key: 'rsc',
value: '1',
},
],
headers: [
{
key: 'Set-Cookie',
value: `__vdpl=${config.deploymentId}; Path=/; HttpOnly`,
key: NEXT_NAV_DEPLOYMENT_ID_HEADER,
value: config.deploymentId,
},
],
})
......
......@@ -271,6 +271,23 @@ export type AppRenderContext = {
implicitTags: ImplicitTags
}
function maybeAppendBuildIdToRSCPayload<T extends RSCPayload>(
ctx: AppRenderContext,
payload: T
): T {
if (!ctx.sharedContext.deploymentId) {
// When using the build id, we need to initialize the id on initial page load, so a build id
// header wouldn't be enough.
return {
...payload,
b: ctx.sharedContext.buildId,
}
} else {
// We rely on a response header
return payload
}
}
interface ParseRequestHeadersOptions {
readonly isRoutePPREnabled: boolean
readonly previewModeId: string | undefined
......@@ -553,24 +570,22 @@ async function generateDynamicRSCPayload(
// We can rely on this because `ActionResult` will always be a promise, even if
// the result is falsey.
if (options?.actionResult) {
return {
return maybeAppendBuildIdToRSCPayload(ctx, {
a: options.actionResult,
f: flightData,
b: ctx.sharedContext.buildId,
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
}
})
}
// Otherwise, it's a regular RSC response.
const baseResponse = {
b: ctx.sharedContext.buildId,
const baseResponse = maybeAppendBuildIdToRSCPayload(ctx, {
f: flightData,
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
}
})
// For runtime prefetches, we encode the stale time and isPartial flag in the response body
// rather than relying on response headers. Both of these values will be transformed
......@@ -1544,12 +1559,11 @@ async function getRSCPayload(
workStore.isStaticGeneration &&
ctx.renderOpts.experimental.isRoutePPREnabled === true
return {
return maybeAppendBuildIdToRSCPayload(ctx, {
// See the comment above the `Preloads` component (below) for why this is part of the payload
P: createElement(Preloads, {
preloadCallbacks: preloadCallbacks,
}),
b: ctx.sharedContext.buildId,
c: prepareInitialCanonicalUrl(url),
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
......@@ -1565,7 +1579,7 @@ async function getRSCPayload(
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
}
})
}
/**
......@@ -1674,8 +1688,7 @@ async function getErrorRSCPayload(
workStore.isStaticGeneration &&
ctx.renderOpts.experimental.isRoutePPREnabled === true
return {
b: ctx.sharedContext.buildId,
return maybeAppendBuildIdToRSCPayload(ctx, {
c: prepareInitialCanonicalUrl(url),
q: getRenderedSearch(query),
m: undefined,
......@@ -1691,7 +1704,7 @@ async function getErrorRSCPayload(
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
} satisfies InitialRSCPayload
} satisfies InitialRSCPayload)
}
// This component must run in an SSR context. It will render the RSC root component
......
......@@ -36,7 +36,7 @@ import { workAsyncStorage } from './work-async-storage.external'
// Contains metadata about the route tree. The client must fetch this before
// it can fetch any actual segment data.
export type RootTreePrefetch = {
buildId: string
buildId?: string
tree: TreePrefetch
staleTime: number
}
......@@ -78,7 +78,7 @@ export type TreePrefetch = {
}
export type SegmentPrefetch = {
buildId: string
buildId?: string
rsc: React.ReactNode | null
isPartial: boolean
staleTime: number
......@@ -293,17 +293,19 @@ async function PrefetchTreeData({
// Render the route tree to a special `/_tree` segment.
const treePrefetch: RootTreePrefetch = {
buildId,
tree,
staleTime,
}
if (buildId) {
treePrefetch.buildId = buildId
}
return treePrefetch
}
function collectSegmentDataImpl(
isClientParamParsingEnabled: boolean,
route: FlightRouterState,
buildId: string,
buildId: string | undefined,
staleTime: number,
seedData: CacheNodeSeedData | null,
clientModules: ManifestNode,
......@@ -407,7 +409,7 @@ function collectSegmentDataImpl(
}
async function renderSegmentPrefetch(
buildId: string,
buildId: string | undefined,
staleTime: number,
rsc: React.ReactNode,
requestKey: SegmentRequestKey,
......@@ -416,12 +418,14 @@ async function renderSegmentPrefetch(
): Promise<[SegmentRequestKey, Buffer]> {
// Render the segment data to a stream.
const segmentPrefetch: SegmentPrefetch = {
buildId,
rsc,
isPartial: await isPartialRSCData(rsc, clientModules),
staleTime,
varyParams,
}
if (buildId) {
segmentPrefetch.buildId = buildId
}
// Since all we're doing is decoding and re-encoding a cached prerender, if
// it takes longer than a microtask, it must because of hanging promises
// caused by dynamic data. Abort the stream at the end of the current task.
......
......@@ -238,8 +238,8 @@ export type FlightData = Array<FlightDataPath> | string
export type ActionResult = Promise<any>
export type InitialRSCPayload = {
/** buildId */
b: string
/** buildId, can be empty if the x-nextjs-build-id header is set */
b?: string
/** initialCanonicalUrlParts */
c: string[]
/** initialRenderedSearch */
......@@ -262,8 +262,8 @@ export type InitialRSCPayload = {
// Response from `createFromFetch` for normal rendering
export type NavigationFlightResponse = {
/** buildId */
b: string
/** buildId, can be empty if the x-nextjs-build-id header is set */
b?: string
/** flightData */
f: FlightData
/** prerendered */
......@@ -282,8 +282,8 @@ export type NavigationFlightResponse = {
export type ActionFlightResponse = {
/** actionResult */
a: ActionResult
/** buildId */
b: string
/** buildId, can be empty if the x-nextjs-build-id header is set */
b?: string
/** flightData */
f: FlightData
/** renderedSearch */
......
......@@ -2,12 +2,12 @@ import type * as Playwright from 'playwright'
import webdriver from 'next-webdriver'
import { createRouterAct } from 'router-act'
import { findPort } from 'next-test-utils'
import { isNextDeploy, isNextDev } from 'e2e-utils'
import { isNextDeploy, isNextDev, isNextStart, nextTestSetup } from 'e2e-utils'
import { build, start } from './servers.mjs'
describe('segment cache (deployment skew)', () => {
if (isNextDev || isNextDeploy) {
test('should not run during dev or deploy test runs', () => {})
if (isNextDev) {
test('should not run during dev', () => {})
return
}
......@@ -21,39 +21,65 @@ describe('segment cache (deployment skew)', () => {
// start a proxy server that rewrites incoming requests to one or the other
// based on the request information.
let cleanup: () => Promise<void>
let port: number
if (isNextStart) {
let cleanup: () => Promise<void>
let port: number
describe('with BUILD_ID', () => {
beforeAll(async () => {
build('BUILD_ID')
const proxyPort = (port = await findPort())
const nextPort1 = await findPort()
const nextPort2 = await findPort()
cleanup = await start(proxyPort, nextPort1, nextPort2, 'BUILD_ID')
})
describe('with BUILD_ID', () => {
beforeAll(async () => {
build('BUILD_ID')
const proxyPort = (port = await findPort())
const nextPort1 = await findPort()
const nextPort2 = await findPort()
cleanup = await start(proxyPort, nextPort1, nextPort2, 'BUILD_ID')
})
afterAll(async () => {
await cleanup()
})
afterAll(async () => {
await cleanup()
runTests(() => port)
})
runTests(() => port)
})
describe('with NEXT_DEPLOYMENT_ID', () => {
beforeAll(async () => {
build('DEPLOYMENT_ID')
const proxyPort = (port = await findPort())
const nextPort1 = await findPort()
const nextPort2 = await findPort()
cleanup = await start(proxyPort, nextPort1, nextPort2, 'DEPLOYMENT_ID')
})
describe('with NEXT_DEPLOYMENT_ID', () => {
beforeAll(async () => {
build('DEPLOYMENT_ID')
const proxyPort = (port = await findPort())
const nextPort1 = await findPort()
const nextPort2 = await findPort()
cleanup = await start(proxyPort, nextPort1, nextPort2, 'DEPLOYMENT_ID')
afterAll(async () => {
await cleanup()
})
runTests(() => port)
})
}
afterAll(async () => {
await cleanup()
describe('header with deployment id', () => {
const { next } = nextTestSetup({
files: __dirname,
env: {
// rely on skew protection when deployed
NEXT_DEPLOYMENT_ID: isNextDeploy ? undefined : 'test-deployment-id',
},
})
runTests(() => port)
// Deployment skew is hard to properly e2e deploy test, so this just checks for the header
it('header is set on RSC responses', async () => {
for (const route of ['/dynamic-page', '/static-page']) {
await next.fetch(route)
let res = await next.fetch(`${route}?_rsc=`, {
headers: { rsc: '1' },
})
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('text/x-component')
expect(res.headers.get('x-nextjs-deployment-id')).toBeTruthy()
}
})
})
})
......
const BUILD_ID = process.env.BUILD_ID
if (!BUILD_ID && !process.env.NEXT_DEPLOYMENT_ID) {
throw new Error('Neither BUILD_ID nor NEXT_DEPLOYMENT_ID is set')
const buildId = process.env.NEXT_PUBLIC_BUILD_ID
if (!buildId && !process.env.NEXT_DEPLOYMENT_ID) {
throw new Error('Neither NEXT_PUBLIC_BUILD_ID nor NEXT_DEPLOYMENT_ID is set')
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
distDir: '.next.' + (BUILD_ID ?? process.env.NEXT_DEPLOYMENT_ID),
distDir: '.next' + (process.env.DIST_DIR || ''),
generateBuildId:
BUILD_ID &&
buildId &&
(async () => {
return BUILD_ID
return buildId
}),
}
......
......@@ -11,12 +11,13 @@ function getEnv(id, mode) {
if (mode === 'BUILD_ID') {
return {
...process.env,
BUILD_ID: id,
DIST_DIR: id,
NEXT_PUBLIC_BUILD_ID: id,
}
} else if (mode === 'DEPLOYMENT_ID') {
return {
...process.env,
DIST_DIR: id,
NEXT_DEPLOYMENT_ID: id,
}
} else {
......
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