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