Unverified Commit 60a847b0 authored by Josh Story's avatar Josh Story Committed by GitHub

Rewrite instant validation to use depth-based URL boundary discovery (#90905)

Instead of pre-planning validation tasks by walking the tree and
accumulating `navigationParents`, the new implementation drives
validation by URL depth. Starting from the deepest URL segment and
working backwards, it builds a combined payload at each depth where the
boundary between shared (already-mounted) and new (being-navigated-to)
content is determined by counting URL-consuming segments. If the new
subtree at that depth contains any `unstable_instant` configs, the
payload is validated. If not, it moves to the next shallower depth.

This approach has several advantages over the task-based model:

- Route group layouts no longer create spurious navigation boundaries —
they don\`t consume URL depth, so they naturally share the boundary of
their parent URL segment
- The `requiresInstantUI` requirement propagates correctly through the
tree: a local `false` config opts the subtree out, a non-false config
opts it in, and no config defers to the OR-union of children slots
- Both the static-stage and runtime-retry payloads are built in a single
tree walk, avoiding the separate retry pass
- The `<head>` stage correctly uses Runtime when any segment in the new
tree uses runtime prefetch
parent d1fcd201
......@@ -246,9 +246,10 @@ import {
} from './debug-channel-server'
import { createNodeStreamWithLateRelease } from './instant-validation/stream-utils'
// NOTE: Only use this for types, access implementations via ComponentMod
import type * as InstantValidation from './instant-validation/instant-validation'
import { createValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import {
createValidationBoundaryTracking,
type ValidationBoundaryTracking,
} from './instant-validation/boundary-tracking'
export type GetDynamicParamFromSegment = (
// The LoaderTree to extract the dynamic param from
......@@ -4096,6 +4097,7 @@ async function spawnStaticShellValidationInDevImpl(
ctx,
hmrRefreshHash
)
if (instantConfigsResult.length > 0) {
return logMessagesAndSendErrorsToBrowser(instantConfigsResult, ctx)
}
......@@ -4434,6 +4436,14 @@ async function validateStagedShell(
}
}
/**
* Validates instant configs by iterating URL depths from deepest to
* shallowest. At each depth, builds a combined payload where segments
* above the boundary use Dynamic stage (already mounted) and segments
* below use Static/Runtime stage (being prefetched). If the new subtree
* contains any `unstable_instant` configs, the payload is rendered to
* detect dynamic holes without Suspense.
*/
async function validateInstantConfigs(
accumulatedChunks: AccumulatedStreamChunks,
debugChunks: null | Array<Uint8Array>,
......@@ -4445,37 +4455,18 @@ async function validateInstantConfigs(
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
const { findNavigationsToValidate, collectStagedSegmentData } =
ctx.componentMod.InstantValidation!
const {
createCombinedPayloadAtDepth,
createCombinedPayloadStream,
collectStagedSegmentData,
} = ctx.componentMod.InstantValidation!
debug?.('\nStarting instant validation...')
debug?.('\nStarting depth-based instant validation...')
let init: Awaited<ReturnType<typeof findNavigationsToValidate>>
// We throw for invalid configurations, so errors should be surfaced.
try {
init = await findNavigationsToValidate(
ctx.componentMod.routeModule.userland.loaderTree,
ctx.getDynamicParamFromSegment,
ctx.query
)
} catch (err) {
debug?.('Error while planning validations.')
return [err]
}
const {
tree: validationRouteTree,
treeNodes,
validationTasks,
segmentsWithInstantConfigs,
} = init
const hasRuntimePrefetch = segmentsWithInstantConfigs.some((segmentPath) => {
const treeNode = treeNodes.get(segmentPath)!
const instantConfig = treeNode.module!.instantConfig!
return instantConfig && typeof instantConfig === 'object'
? instantConfig.prefetch === 'runtime'
: false
})
const loaderTree = ctx.componentMod.routeModule.userland.loaderTree
// Only affects a debug environment name label, not functional behavior.
const hasRuntimePrefetch = true
const clientReferenceManifest = getClientReferenceManifest()
......@@ -4495,268 +4486,244 @@ async function validateInstantConfigs(
clientReferenceManifest
)
const getFilepathForSegment = (segmentPath: InstantValidation.SegmentPath) =>
treeNodes.get(segmentPath)?.module?.conventionPath
const getCreateInstantStackForSegment = (
segmentPath: InstantValidation.SegmentPath
) => treeNodes.get(segmentPath)?.module?.createInstantStack ?? null
for (const { parents, target } of validationTasks) {
const createInstantStack = getCreateInstantStackForSegment(target)
for (const navigationParent of parents) {
debug?.(
`-------------------------------\n` +
`Validating navigation\n` +
` from '${navigationParent}/*' (${getFilepathForSegment(navigationParent) ?? '<no file>'})\n` +
` to '${workAsyncStorage.getStore()!.route}'`
)
const initialResults = await validateInstantConfigNavigation(
initialRscPayload,
cache,
startTime,
stageEndTimes,
rootParams,
ctx,
hmrRefreshHash,
validationRouteTree,
navigationParent,
false, // use static stage for static segments
createInstantStack
)
if (initialResults.errors.length === 0) {
debug?.(` ✅ Validation successful`)
}
if (initialResults.errors.length > 0) {
if (initialResults.dynamicHoleKind !== DynamicHoleKind.Dynamic) {
debug?.(' Retrying to gather more info...')
const runtimeResults = await validateInstantConfigNavigation(
initialRscPayload,
cache,
startTime,
stageEndTimes,
rootParams,
ctx,
hmrRefreshHash,
validationRouteTree,
navigationParent,
true, // use runtime stage for static segments instead
createInstantStack
)
if (runtimeResults.errors.length > 0) {
// The errors remained in the runtime stage, so they were caused by a dynamic access.
debug?.(
` ❌ Failed after runtime retry (${runtimeResults.errors.length} errors)`
)
return runtimeResults.errors
}
// Otherwise, the errors disappeared in the runtime stage, so they were caused
// by a runtime access. report the original errors.
}
debug?.(` ❌ Failed (${initialResults.errors.length} errors)`)
return initialResults.errors
}
}
}
debug?.(`✅ Passed`)
return []
}
async function validateInstantConfigNavigation(
initialRscPayload: InitialRSCPayload,
cache: InstantValidation.SegmentCache,
startTime: number,
stageEndTimes: InstantValidation.StageEndTimes,
rootParams: Params,
ctx: AppRenderContext,
hmrRefreshHash: string | undefined,
routeTree: InstantValidation.RouteTree,
navigationParent: InstantValidation.SegmentPath,
useRuntimeStageForPartialSegments: boolean,
createInstantStack: (() => Error) | null
): Promise<{ dynamicHoleKind: DynamicHoleKind; errors: Array<unknown> }> {
const { implicitTags, nonce, workStore } = ctx
const isDebugChannelEnabled = !!ctx.renderOpts.setReactDebugChannel
const { createCombinedPayload, createCombinedPayloadStream } =
ctx.componentMod.InstantValidation!
const clientDynamicTracking = createDynamicTrackingState(
false //isDebugDynamicAccesses
)
const clientReactController = new AbortController()
const clientRenderController = new AbortController()
/**
* Build and validate a combined payload at the given URL depth.
*
* Returns null if no instant config exists at this depth.
* Returns an empty array if validation passed.
* Returns a non-empty array of errors if validation failed.
*
* When the initial validation uses static segments and finds errors,
* automatically retries with runtime stages to discriminate between
* runtime and dynamic errors, returning the more specific result.
*/
async function validateAtDepth(
depth: number
): Promise<Array<unknown> | null> {
return validateAtDepthImpl(depth, null)
}
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
async function validateAtDepthImpl(
depth: number,
previousBoundaryState: null | ValidationBoundaryTracking
): Promise<null | Array<unknown>> {
const extraChunksController = new AbortController()
const boundaryState = createValidationBoundaryTracking()
let useRuntimeStageForPartialSegments = false
if (previousBoundaryState) {
// We're doing a followup render to better discriminate error types
useRuntimeStageForPartialSegments = true
for (const id of previousBoundaryState.expectedIds) {
boundaryState.expectedIds.add(id)
}
}
const dynamicValidation = createInstantValidationState(createInstantStack)
const boundaryState = createValidationBoundaryTracking()
const payloadResult = await createCombinedPayloadAtDepth(
initialRscPayload,
cache,
loaderTree,
ctx.getDynamicParamFromSegment,
ctx.query,
depth,
extraChunksController.signal,
boundaryState,
clientReferenceManifest,
stageEndTimes,
useRuntimeStageForPartialSegments
)
const finalClientPrerenderStore: PrerenderStore = {
type: 'validation-client',
phase: 'render',
rootParams,
implicitTags,
renderSignal: clientRenderController.signal,
controller: clientReactController,
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null,
dynamicTracking: clientDynamicTracking,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
// TODO should this be removed from client stores?
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash,
// We don't need to track vary params during validation.
varyParamsAccumulator: null,
boundaryState,
}
if (payloadResult === null) {
return null
}
const clientReferenceManifest = getClientReferenceManifest()
const reactController = new AbortController()
const renderController = new AbortController()
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const { stream: serverStream, debugStream } =
await createCombinedPayloadStream(
payloadResult.payload,
extraChunksController,
reactController.signal,
clientReferenceManifest,
startTime,
isDebugChannelEnabled
)
const usedSegmentKinds = new Set<InstantValidation.SegmentStage>()
const { stream: serverStream, debugStream } =
await createCombinedPayloadStream(
(extraChunksReleaseSignal) =>
createCombinedPayload(
initialRscPayload,
cache,
routeTree,
navigationParent,
extraChunksReleaseSignal,
boundaryState,
clientReferenceManifest,
stageEndTimes,
useRuntimeStageForPartialSegments,
usedSegmentKinds
),
clientReactController.signal, // release chunks before the abort
clientReferenceManifest,
startTime,
isDebugChannelEnabled
const dynamicValidation = createInstantValidationState(
payloadResult.createInstantStack
)
const clientDynamicTracking = createDynamicTrackingState(false)
// If we have static segments, we don't know if the error comes from a runtime or dynamic access.
// In that case, we report messages as if the failure is a runtime access.
// if we get errors, we'll retry this validation, forcing all the static segements into runtime stage.
// If the error disappears in the runtime stage, then we'll use the original runtime message.
// If it doesn't disappears, it has to come from a dynamic access, so we'll use the message from the retry.
const dynamicHoleKind = usedSegmentKinds.has(RenderStage.Static)
? DynamicHoleKind.Runtime
: DynamicHoleKind.Dynamic
const prerenderStore: PrerenderStore = {
type: 'validation-client',
phase: 'render',
rootParams,
implicitTags,
renderSignal: renderController.signal,
controller: reactController,
cacheSignal: null,
dynamicTracking: clientDynamicTracking,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash,
varyParamsAccumulator: null,
boundaryState,
}
try {
let { prelude: unprocessedPrelude } = await runInSequentialTasks(
() => {
const pendingFinalClientResult = workUnitAsyncStorage.run(
finalClientPrerenderStore,
getClientPrerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- React Client
<App
reactServerStream={serverStream}
reactDebugStream={debugStream ?? undefined}
// Debug info is already filtered when constructing the combined payload.
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
signal: clientReactController.signal,
onError: (err: unknown, errorInfo: ErrorInfo) => {
if (
isPrerenderInterruptedError(err) ||
clientReactController.signal.aborted
) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackDynamicHoleInNavigation(
workStore,
componentStack,
dynamicValidation,
clientDynamicTracking,
dynamicHoleKind,
boundaryState
)
let errors: Array<unknown>
try {
const { prelude: unprocessedPrelude } = await runInSequentialTasks(
() => {
const pendingResult = workUnitAsyncStorage.run(
prerenderStore,
getClientPrerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- React Client
<App
reactServerStream={serverStream}
reactDebugStream={debugStream ?? undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
signal: reactController.signal,
onError: (err: unknown, errorInfo: ErrorInfo) => {
if (
isPrerenderInterruptedError(err) ||
reactController.signal.aborted
) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackDynamicHoleInNavigation(
workStore,
componentStack,
dynamicValidation,
clientDynamicTracking,
payloadResult.hasAmbiguousErrors
? DynamicHoleKind.Runtime
: DynamicHoleKind.Dynamic,
boundaryState
)
}
return
} else if (!reactController.signal.aborted) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackThrownErrorInNavigation(
dynamicValidation,
err,
componentStack
)
}
}
return
} else if (!clientReactController.signal.aborted) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackThrownErrorInNavigation(
dynamicValidation,
err,
componentStack
)
if (isReactLargeShellError(err)) {
console.error(err)
return undefined
}
}
if (isReactLargeShellError(err)) {
// TODO: Aggregate
console.error(err)
return undefined
}
return getDigestForWellKnownError(err)
},
}
)
return getDigestForWellKnownError(err)
reactController.signal.addEventListener(
'abort',
() => {
renderController.abort()
},
// We don't need bootstrap scripts in this prerender
// bootstrapScripts: [bootstrapScript],
}
)
{ once: true }
)
// The listener to abort our own render controller must be added after
// React has added its listener, to ensure that pending I/O is not
// aborted/rejected too early.
clientReactController.signal.addEventListener(
'abort',
() => {
clientRenderController.abort()
},
{ once: true }
return pendingResult
},
() => {
reactController.abort()
}
)
const { preludeIsEmpty } = await processPreludeOp(unprocessedPrelude)
errors = getNavigationDisallowedDynamicReasons(
workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
dynamicValidation,
boundaryState
)
} catch (thrownValue) {
errors = getNavigationDisallowedDynamicReasons(
workStore,
PreludeState.Errored,
dynamicValidation,
boundaryState
)
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) {
// TODO(instant-validation) we should switch to pushing an Error with a cause of the
// thrownValue. Since we want to report the issue to code that largely expects
// Error objects we should aim to provide this whereever possible
errors.unshift(
'During dynamic validation the root of the page errored.',
thrownValue
)
}
}
return pendingFinalClientResult
},
() => {
clientReactController.abort()
if (errors === null || errors.length === 0) {
// This prerender did not produce any errors
return null
}
if (previousBoundaryState === null && payloadResult.hasAmbiguousErrors) {
// This is the first validation attempt. we prepared a payload where dynamic holes might be runtime data dependencies
// or dynamic data dependencies. We do a followup validation using a payload with only Runtime segments to discriminate
const dynamicOnlyErrors = await validateAtDepthImpl(depth, boundaryState)
if (dynamicOnlyErrors !== null && dynamicOnlyErrors.length > 0) {
// The dynamic errors only validation found errors to report so we favor those
return dynamicOnlyErrors
}
)
}
const { preludeIsEmpty } = await processPreludeOp(unprocessedPrelude)
// If we didn't return some other errors at this point the only thing to return is this validation's errors
return errors
}
const reasons = getNavigationDisallowedDynamicReasons(
workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
dynamicValidation,
boundaryState
)
const urlSegments = ctx.url.pathname.split('/').filter(Boolean)
const maxDepth = urlSegments.length + 1 // +1 for root
return { dynamicHoleKind, errors: reasons }
} catch (thrownValue) {
// Even if the root errors we still want to report any cache components errors
// that were discovered before the root errored.
let errors: Array<unknown> = getNavigationDisallowedDynamicReasons(
workStore,
PreludeState.Errored,
dynamicValidation,
boundaryState
)
for (let depth = maxDepth - 1; depth >= 0; depth--) {
debug?.(`Trying depth ${depth}...`)
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) {
errors.unshift(
'During dynamic validation the root of the page errored. The next logged error is the thrown value. It may be a duplicate of errors reported during the normal development mode render.',
thrownValue
)
const errors = await validateAtDepth(depth)
if (errors === null) {
debug?.(` No config at depth ${depth}, skipping.`)
continue
}
if (errors.length > 0) {
debug?.(` Depth ${depth}: ❌ Failed (${errors.length} errors)`)
return errors
}
return { dynamicHoleKind, errors }
debug?.(` Depth ${depth}: ✅ Passed`)
}
debug?.(`✅ All depths passed`)
return []
}
type PrerenderToStreamResult = {
......
......@@ -37,12 +37,17 @@ import {
createNodeStreamFromChunks,
} from './stream-utils'
import { createDebugChannel } from '../debug-channel-server'
// eslint-disable-next-line import/no-extraneous-dependencies
import { createFromNodeStream } from 'react-server-dom-webpack/client'
// eslint-disable-next-line import/no-extraneous-dependencies
import { renderToReadableStream } from 'react-server-dom-webpack/server'
import { addSearchParamsIfPageSegment } from '../../../shared/lib/segment'
import {
addSearchParamsIfPageSegment,
isGroupSegment,
PAGE_SEGMENT_KEY,
DEFAULT_SEGMENT_KEY,
NOT_FOUND_SEGMENT_KEY,
} from '../../../shared/lib/segment'
import type { NextParsedUrlQuery } from '../../request-meta'
const filterStackFrame =
......@@ -92,167 +97,6 @@ export type RouteTree = {
slots: { [parallelRouteKey: string]: RouteTree } | null
}
/**
* The entrypoint. Traverses the loader tree, finds `unstable_instant` configs,
* and determines what navigations we should validate.
* */
export async function findNavigationsToValidate(
rootLoaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
query: NextParsedUrlQuery | null
) {
type ValidationTask = { target: SegmentPath; parents: SegmentPath[] }
const validationTasks: ValidationTask[] = []
let navigationParents: SegmentPath[] = []
const segmentsWithInstantConfigs: SegmentPath[] = []
const treeNodes = new Map<SegmentPath, RouteTree>()
function getSegmentFromLoaderTree(loaderTree: LoaderTree): Segment {
const dynamicParam = getDynamicParamFromSegment(loaderTree)
if (dynamicParam) {
return dynamicParam.treeSegment
}
const segment = loaderTree[0]
// In dev, the segment paths for all the page segments will include search params (`__PAGE__?{"q":"123"`}
// because the payload we're reassembling had them encoded in the router state,
// so we need to match that here.
// TODO(instant-validation): this will likely need some restructuring for build
return query ? addSearchParamsIfPageSegment(segment, query) : segment
}
async function visit(
loaderTree: LoaderTree,
parentPath: SegmentPath | null,
key: string | null,
parentLayoutPath: SegmentPath | null,
isInsideParallelSlot: boolean
): Promise<RouteTree> {
const { conventionPath, parallelRoutes } = parseLoaderTree(loaderTree)
const { mod: layoutOrPageMod, modType } =
await getLayoutOrPageModule(loaderTree)
const segment = getSegmentFromLoaderTree(loaderTree)
const segmentPath =
parentPath === null
? stringifySegment(segment)
: createChildSegmentPath(parentPath, key!, segment)
let moduleInfo: RouteTree['module'] = null
if (layoutOrPageMod !== undefined) {
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig =
(layoutOrPageMod as AppSegmentConfig).unstable_instant ?? null
const rawFactory: unknown = (layoutOrPageMod as any)
.__debugCreateInstantConfigStack
const createInstantStack: (() => Error) | null =
typeof rawFactory === 'function' ? (rawFactory as () => Error) : null
moduleInfo = {
type: modType!,
instantConfig,
conventionPath: conventionPath!,
createInstantStack,
}
if (isInsideParallelSlot) {
// For now, we ignore parallel routes for purposes of finding configs to validate
// and finding shared layout parents.
if (instantConfig !== null) {
console.error(
`${conventionPath}: \`unstable_instant\` validation is not fully implemented for parallel routes yet.`
)
}
} else {
if (modType === 'layout') {
// All layouts will be checked as navigation parents, so
// if a layout has a prefetch config, we'll check navigations into it
// because we'll be navigating from its parents.
if (instantConfig !== null) {
if (instantConfig === false) {
// we don't want to validate navigations into this segment,
// but still want to validate inside it.
navigationParents = []
} else {
const isRootLayout = parentLayoutPath === null
if (isRootLayout && instantConfig.prefetch === 'runtime') {
const message = `${conventionPath}: \`unstable_instant\` with mode 'runtime' is not supported in root layouts.`
const error =
createInstantStack !== null
? createInstantStack()
: new Error()
error.message = message
throw error
}
const task: ValidationTask = {
target: segmentPath,
parents: navigationParents,
}
validationTasks.push(task)
navigationParents = []
}
}
navigationParents.push(segmentPath)
} else if (modType === 'page') {
if (instantConfig !== null) {
if (instantConfig === false) {
navigationParents = []
} else {
const task: ValidationTask = {
target: segmentPath,
parents: navigationParents,
}
validationTasks.push(task)
navigationParents = []
}
}
}
if (instantConfig && typeof instantConfig === 'object') {
segmentsWithInstantConfigs.push(segmentPath)
}
}
}
const parentLayoutPathForChildren =
modType === 'layout' ? segmentPath : parentLayoutPath
let slots: RouteTree['slots'] = null
for (const parallelRouteKey in parallelRoutes) {
const childLoaderTree = parallelRoutes[parallelRouteKey]
const isChildInParallelSlot =
isInsideParallelSlot || parallelRouteKey !== 'children'
slots ??= {}
slots[parallelRouteKey] = await visit(
childLoaderTree,
segmentPath,
parallelRouteKey,
parentLayoutPathForChildren,
isChildInParallelSlot
)
}
const treeNode: RouteTree = {
path: segmentPath,
segment,
module: moduleInfo,
slots,
}
treeNodes.set(segmentPath, treeNode)
return treeNode
}
const routeTree = await visit(rootLoaderTree, null, null, null, false)
return {
tree: routeTree,
treeNodes,
validationTasks,
segmentsWithInstantConfigs,
}
}
function traverseRootSeedDataSegments(
initialRSCPayload: InitialRSCPayload,
processSegment: (
......@@ -650,18 +494,13 @@ function writeChunk(
* to provide extra debug info.
* */
export async function createCombinedPayloadStream(
createPayload: (
extraChunksReleaseSignal: AbortSignal
) => Promise<InitialRSCPayload>,
payload: InitialRSCPayload,
extraChunksAbortController: AbortController,
renderSignal: AbortSignal,
clientReferenceManifest: ClientReferenceManifest,
startTime: number,
isDebugChannelEnabled: boolean
) {
const extraChunksAbortController = new AbortController()
const payload = await createPayload(extraChunksAbortController.signal)
// Collect all the chunks so that we're not dependent on timing of the render.
let isRenderable = true
......@@ -743,90 +582,6 @@ export async function createCombinedPayloadStream(
}
}
/**
* Builds a combined RSC payload to represent what we'd render in the browser
* when the specified navigation navigation is started, assuming that all the new segments
* segments were prefetched.
*
* ### Background
*
* For a client navigation, we conceptually split the segments into two groups:
*
* #### Outer: the shared parent segments
* These are common between the old view and the new one.
* They're meant to be fully resolved, since the browser already loaded them before.
*
* #### Inner: the new subtree(s)
* These segments are unique to the new view. For these segments, we first display
* prefetched content (either static or runtime, depending on the configuration).
*
* When validating a navigation, we're validating that rendering the inner segments
* (which are going to be partial) won't block, i.e. any holes are properly guarded with Suspense.
* */
export async function createCombinedPayload(
initialRSCPayload: InitialRSCPayload,
cache: SegmentCache,
validationRouteTree: RouteTree,
/**
* The innermost segment that is shared. Anything below will be in the new subtree.
*
* TODO(instant-validation):
* this is too limited, and cannot support multiple parallel slots
* being in the new subtree at once.
* */
navigationParent: SegmentPath,
releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes,
/** Only used when retrying a failed validation to see what caused a dynamic hole. */
useRuntimeStageForPartialSegments: boolean,
/** mutable out-param - Which stages are actually used in the resulting payload */
usedSegmentKinds: Set<SegmentStage>
): Promise<InitialRSCPayload> {
const { flightRouterState } = getRootDataFromPayload(initialRSCPayload)
const combinedSeedData = await createValidationSeedData(
cache,
validationRouteTree,
navigationParent,
releaseSignal,
boundaryState,
clientReferenceManifest,
stageEndTimes,
useRuntimeStageForPartialSegments,
usedSegmentKinds
)
// If we did a runtime prefetch for this navigation, then we'd get a runtime-stage head.
// Otherwise, we'd only have the `/_head` segment prefetch which is static.
// TODO(instant-validation): not sure about this as a way of detecting runtime prefetches
// (in the presence of `useRuntimeStageForPartialSegments`), but maybe it's actually correct?
const headStage = usedSegmentKinds.has(RenderStage.Runtime)
? RenderStage.Runtime
: RenderStage.Static
debug?.(` <head> - ${RenderStage[headStage]}`)
const head = await createValidationHead(
cache,
releaseSignal,
clientReferenceManifest,
stageEndTimes,
headStage
)
const combinedRSCPayload: InitialRSCPayload = {
...initialRSCPayload,
f: [
// We expect the root path to only have three elements.
[
flightRouterState satisfies FlightRouterState,
combinedSeedData satisfies CacheNodeSeedData,
head satisfies HeadData,
],
],
}
return combinedRSCPayload
}
function getRootDataFromPayload(initialRSCPayload: InitialRSCPayload) {
// FlightDataPath is an unsound type, hence the additional checks.
const flightDataPaths = initialRSCPayload.f
......@@ -843,155 +598,6 @@ function getRootDataFromPayload(initialRSCPayload: InitialRSCPayload) {
return { flightRouterState, seedData, head }
}
function createValidationSeedData(
cache: SegmentCache,
rootRouteTree: RouteTree,
navigationParent: SegmentPath,
releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes,
useRuntimeStageForPartialSegments: boolean,
usedSegmentKinds: Set<SegmentStage>
): Promise<CacheNodeSeedData> {
type TraversalState =
| { kind: 'shared-tree' }
| { kind: 'new-tree'; isInsideRuntimePrefetch: boolean }
async function createSeedDataFromValidationTreeImpl(
routeTree: RouteTree,
state: TraversalState
) {
const { path, slots } = routeTree
let stage: SegmentStage
let nextState: TraversalState
switch (state.kind) {
case 'shared-tree': {
stage = RenderStage.Dynamic
if (path === navigationParent) {
// We reached the last shared segment. Everything below is a new subtree.
nextState = { kind: 'new-tree', isInsideRuntimePrefetch: false }
} else {
nextState = state
}
break
}
case 'new-tree': {
if (!state.isInsideRuntimePrefetch) {
// We're not already inside a runtime prefetch, so by default we prefetch statically.
// Check if we need to switch to runtime prefetching instead.
const prefetchConfig = routeTree.module?.instantConfig
if (
prefetchConfig &&
typeof prefetchConfig === 'object' &&
prefetchConfig.prefetch === 'runtime'
) {
// We have a runtime prefetch config. The client router will
// prefetch this segment and all segments below using a runtime prefetch.
stage = RenderStage.Runtime
nextState = { kind: 'new-tree', isInsideRuntimePrefetch: true }
} else {
// No runtime prefetch config. Continue using static prefetching.
//
// Note that we can also get here for `unstable_instant = false` with a `prefetch: 'static'` parent.
// `false` doesn't currently affect router behavior, so we act like it's not there.
//
// If the initial validation failed, we retry the render and use the runtime stage
// for static segments. This lets us discriminate runtime and dynamic holes.
stage = useRuntimeStageForPartialSegments
? RenderStage.Runtime
: RenderStage.Static
nextState = state
}
} else {
// We're already inside a runtime prefetch, so we stay this way.
// Note that we can also get here for `unstable_instant = false` with a `prefetch: 'runtime'` parent.
// `false` doesn't currently affect router behavior, so we act like it's not there.
stage = RenderStage.Runtime
nextState = state
}
break
}
default: {
state satisfies never
throw new InvariantError(
`Unexpected state while traversing route tree: ${(state as any).kind}`
)
}
}
debug?.(` ${path || '/'} - ${RenderStage[stage]}`)
const segmentCacheItem = cache.segments.get(path)
if (!segmentCacheItem) {
throw new InvariantError(`Missing segment data: ${path}`)
}
// TODO: for runtime-only validations, empty segments can throw this off
// and make us retry even though there's no *real* static segments in the tree
usedSegmentKinds.add(stage)
let segmentData = await deserializeFromChunks<SegmentData>(
segmentCacheItem.chunks[stage],
segmentCacheItem.chunks[RenderStage.Dynamic],
segmentCacheItem.debugChunks,
releaseSignal,
clientReferenceManifest,
stage === RenderStage.Dynamic
? null
: { startTime: undefined, endTime: stageEndTimes[stage] }
)
// We place the validation boundary right below the shared parent segment
// This means that a dynamic hole is accepted as long as it has a Suspense boundary
// in the new subtree (i.e. it wouldn't block the navigation).
const isInnermostSharedParent =
state.kind === 'shared-tree' && nextState.kind === 'new-tree'
if (isInnermostSharedParent) {
debug?.(
` ['${path}' is the innermost shared parent, adding validation boundary below it]`
)
const boundaryId = path
boundaryState.expectedIds.add(boundaryId)
segmentData = {
...segmentData,
node: (
// When we wrap the node in a context provider,
// the first OuterLayoutRouter inside it will see it and place a validation boundary.
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- bundled in the server layer
<PlaceValidationBoundaryBelowThisLevel
id={boundaryId}
key="c" /* matching `cacheNodeKey` */
>
{segmentData.node}
</PlaceValidationBoundaryBelowThisLevel>
),
}
}
const slotsSeedData: CacheNodeSeedDataSlots = {}
if (slots) {
for (const parallelRouteKey in slots) {
slotsSeedData[parallelRouteKey] =
await createSeedDataFromValidationTreeImpl(
slots[parallelRouteKey],
nextState
)
}
}
return getCacheNodeSeedDataFromSegment(segmentData, slotsSeedData)
}
return createSeedDataFromValidationTreeImpl(
rootRouteTree,
// Root layouts are always shared. Navigating to a new root layout is an MPA navigation.
{ kind: 'shared-tree' }
)
}
async function createValidationHead(
cache: SegmentCache,
releaseSignal: AbortSignal,
......@@ -1125,3 +731,324 @@ type SegmentCacheItem = {
chunks: StageChunks
debugChunks: Uint8Array[] | null
}
type TreeResult = {
seedData: CacheNodeSeedData
requiresInstantUI: boolean
createInstantStack: (() => Error) | null
}
/**
* Whether this segment consumes a URL depth level. Each URL depth
* represents a potential navigation boundary.
*
* The root segment ('') consumes depth 0. Regular segments like
* 'dashboard' consume the next depth — whether or not they have a
* layout. Route groups, __PAGE__, __DEFAULT__, and /_not-found don't
* consume a depth — they share the boundary of their parent.
*/
function segmentConsumesURLDepth(segment: Segment): boolean {
// Dynamic segments (tuples) always consume a URL depth.
if (typeof segment !== 'string') return true
// Route groups, pages, defaults, and not-found don't consume a depth.
if (
segment.startsWith(PAGE_SEGMENT_KEY) ||
isGroupSegment(segment) ||
segment === DEFAULT_SEGMENT_KEY ||
segment === NOT_FOUND_SEGMENT_KEY
) {
return false
}
// Everything else consumes a depth, including the root segment ''.
return true
}
/**
* Builds a combined RSC payload for validation at a given URL depth.
*
* Walks the LoaderTree directly, loading modules and counting
* URL-contributing layouts. When `depth` URL segments have been
* consumed, the boundary flips from shared (dynamic stage) to new
* (static/runtime stage). As the new subtree is built, we check for
* instant configs. If none are found, returns null — no validation
* needed at this depth or deeper.
*
* This combines module loading, tree walking, config discovery, and
* payload construction into a single pass.
*/
export type ValidationPayloadResult = {
payload: InitialRSCPayload
/** Whether errors from this payload could be ambiguous between runtime
* API access (cookies, headers) and uncached IO (connection, fetch).
* True when some segments used Static stage. False when all segments
* used Runtime stage and errors are definitively from uncached IO. */
hasAmbiguousErrors: boolean
createInstantStack: (() => Error) | null
}
export async function createCombinedPayloadAtDepth(
initialRSCPayload: InitialRSCPayload,
cache: SegmentCache,
initialLoaderTree: LoaderTree,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
query: NextParsedUrlQuery | null,
depth: number,
releaseSignal: AbortSignal,
boundaryState: ValidationBoundaryTracking,
clientReferenceManifest: ClientReferenceManifest,
stageEndTimes: StageEndTimes,
useRuntimeStageForPartialSegments: boolean
): Promise<ValidationPayloadResult | null> {
let hasStaticSegments = false
let hasRuntimeSegments = false
function getSegment(loaderTree: LoaderTree): Segment {
const dynamicParam = getDynamicParamFromSegment(loaderTree)
if (dynamicParam) {
return dynamicParam.treeSegment
}
const segment = loaderTree[0]
return query ? addSearchParamsIfPageSegment(segment, query) : segment
}
async function buildSharedTreeSeedData(
loaderTree: LoaderTree,
parentPath: SegmentPath | null,
key: string | null,
urlDepthConsumed: number
): Promise<TreeResult> {
const { parallelRoutes } = parseLoaderTree(loaderTree)
const segment = getSegment(loaderTree)
const path: SegmentPath =
parentPath === null
? stringifySegment(segment)
: createChildSegmentPath(parentPath, key!, segment)
debug?.(` ${path || '/'} - Dynamic`)
const segmentCacheItem = cache.segments.get(path)
if (!segmentCacheItem) {
throw new InvariantError(`Missing segment data: ${path}`)
}
const segmentData = await deserializeFromChunks<SegmentData>(
segmentCacheItem.chunks[RenderStage.Dynamic],
segmentCacheItem.chunks[RenderStage.Dynamic],
segmentCacheItem.debugChunks,
releaseSignal,
clientReferenceManifest,
null
)
const consumesDepth = segmentConsumesURLDepth(segment)
if (consumesDepth && urlDepthConsumed === depth) {
debug?.(` ['${path}' is the boundary]`)
boundaryState.expectedIds.add(path)
const wrappedSegmentData: SegmentData = {
...segmentData,
node: (
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- bundled in the server layer
<PlaceValidationBoundaryBelowThisLevel id={path} key="c">
{segmentData.node}
</PlaceValidationBoundaryBelowThisLevel>
),
}
const slots: CacheNodeSeedDataSlots = {}
let requiresInstantUI = false
let createInstantStack: (() => Error) | null = null
for (const parallelRouteKey in parallelRoutes) {
const result = await buildNewTreeSeedData(
parallelRoutes[parallelRouteKey],
path,
parallelRouteKey,
false /* isInsideRuntimePrefetch */
)
slots[parallelRouteKey] = result.seedData
if (result.requiresInstantUI) {
requiresInstantUI = true
if (createInstantStack === null) {
createInstantStack = result.createInstantStack
}
}
}
return {
seedData: getCacheNodeSeedDataFromSegment(wrappedSegmentData, slots),
requiresInstantUI,
createInstantStack,
}
}
// Not the boundary yet — keep walking the shared tree.
const slots: CacheNodeSeedDataSlots = {}
let requiresInstantUI = false
let createInstantStack: (() => Error) | null = null
for (const parallelRouteKey in parallelRoutes) {
const result = await buildSharedTreeSeedData(
parallelRoutes[parallelRouteKey],
path,
parallelRouteKey,
consumesDepth ? urlDepthConsumed + 1 : urlDepthConsumed
)
slots[parallelRouteKey] = result.seedData
if (result.requiresInstantUI) {
requiresInstantUI = true
if (createInstantStack === null) {
createInstantStack = result.createInstantStack
}
}
}
return {
seedData: getCacheNodeSeedDataFromSegment(segmentData, slots),
requiresInstantUI,
createInstantStack,
}
}
async function buildNewTreeSeedData(
lt: LoaderTree,
parentPath: SegmentPath | null,
key: string | null,
isInsideRuntimePrefetch: boolean
): Promise<TreeResult> {
const { parallelRoutes } = parseLoaderTree(lt)
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(lt)
const segment = getSegment(lt)
const path: SegmentPath =
parentPath === null
? stringifySegment(segment)
: createChildSegmentPath(parentPath, key!, segment)
let instantConfig: Instant | null = null
let localCreateInstantStack: (() => Error) | null = null
if (layoutOrPageMod !== undefined) {
instantConfig =
(layoutOrPageMod as AppSegmentConfig).unstable_instant ?? null
if (instantConfig && typeof instantConfig === 'object') {
const rawFactory: unknown = (layoutOrPageMod as any)
.__debugCreateInstantConfigStack
localCreateInstantStack =
typeof rawFactory === 'function' ? (rawFactory as () => Error) : null
}
}
let childIsInsideRuntimePrefetch = isInsideRuntimePrefetch
let stage: SegmentStage
if (!isInsideRuntimePrefetch) {
if (
instantConfig &&
typeof instantConfig === 'object' &&
instantConfig.prefetch === 'runtime'
) {
stage = RenderStage.Runtime
childIsInsideRuntimePrefetch = true
hasRuntimeSegments = true
} else {
if (useRuntimeStageForPartialSegments) {
stage = RenderStage.Runtime
hasRuntimeSegments = true
} else {
stage = RenderStage.Static
hasStaticSegments = true
}
}
} else {
stage = RenderStage.Runtime
hasRuntimeSegments = true
}
debug?.(` ${path || '/'} - ${RenderStage[stage]}`)
const segmentCacheItem = cache.segments.get(path)
if (!segmentCacheItem) {
throw new InvariantError(`Missing segment data: ${path}`)
}
const segmentData = await deserializeFromChunks<SegmentData>(
segmentCacheItem.chunks[stage],
segmentCacheItem.chunks[RenderStage.Dynamic],
segmentCacheItem.debugChunks,
releaseSignal,
clientReferenceManifest,
{ startTime: undefined, endTime: stageEndTimes[stage] }
)
// Build children first, then determine requiresInstantUI.
const slots: CacheNodeSeedDataSlots = {}
let childrenRequireInstantUI = false
let childCreateInstantStack: (() => Error) | null = null
for (const parallelRouteKey in parallelRoutes) {
const result = await buildNewTreeSeedData(
parallelRoutes[parallelRouteKey],
path,
parallelRouteKey,
childIsInsideRuntimePrefetch
)
slots[parallelRouteKey] = result.seedData
if (result.requiresInstantUI) {
childrenRequireInstantUI = true
if (childCreateInstantStack === null) {
childCreateInstantStack = result.createInstantStack
}
}
}
// Local config takes precedence over children.
let requiresInstantUI: boolean
let createInstantStack: (() => Error) | null
if (instantConfig === false) {
requiresInstantUI = false
createInstantStack = null
} else if (instantConfig && typeof instantConfig === 'object') {
requiresInstantUI = true
createInstantStack = localCreateInstantStack
} else {
requiresInstantUI = childrenRequireInstantUI
createInstantStack = childCreateInstantStack
}
return {
seedData: getCacheNodeSeedDataFromSegment(segmentData, slots),
requiresInstantUI,
createInstantStack,
}
}
const { seedData, requiresInstantUI, createInstantStack } =
await buildSharedTreeSeedData(
initialLoaderTree,
null /* parentPath */,
null /* key */,
0 /* urlDepthConsumed */
)
if (!requiresInstantUI) {
return null
}
const { flightRouterState } = getRootDataFromPayload(initialRSCPayload)
const headStage = hasRuntimeSegments
? RenderStage.Runtime
: RenderStage.Static
const head = await createValidationHead(
cache,
releaseSignal,
clientReferenceManifest,
stageEndTimes,
headStage
)
const payload: InitialRSCPayload = {
...initialRSCPayload,
f: [[flightRouterState, seedData, head]],
}
return {
payload,
hasAmbiguousErrors: hasStaticSegments,
createInstantStack,
}
}
......@@ -159,6 +159,31 @@ export default async function Page() {
</li>
</ul>
<h2>Route Groups</h2>
<ul>
<li>
<DebugLinks href="/suspense-in-root/static/route-group-config-only" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/route-group-config-and-segment-config" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/route-group-segment-config-only" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/route-group-config-with-deeper-segment/inner" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/route-group-deeper-segment-config/inner" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/route-group-shared-boundary" />
</li>
<li>
<DebugLinks href="/suspense-in-root/static/route-group-shared-boundary/foo" />
</li>
</ul>
<h2>Disable Validation</h2>
<ul>
<li>
......
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function GroupLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>
This is a route group layout that also has unstable_instant (static)
</em>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export default async function Page() {
await cookies()
return (
<main>
<p>This page awaits cookies() without Suspense</p>
</main>
)
}
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function Layout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a URL-contributing layout with unstable_instant (static)</em>
<hr />
{children}
</div>
)
}
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function GroupLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a route group layout with unstable_instant (static)</em>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export default async function Page() {
await cookies()
return (
<main>
<p>This page awaits cookies() without Suspense</p>
</main>
)
}
import { ReactNode } from 'react'
export default function InnerLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a URL-contributing layout with no config</em>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export default async function Page() {
await cookies()
return (
<main>
<p>This page awaits cookies() without Suspense</p>
</main>
)
}
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function GroupLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a route group layout with unstable_instant (static)</em>
<hr />
{children}
</div>
)
}
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function InnerLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a URL-contributing layout with unstable_instant (static)</em>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export default async function Page() {
await cookies()
return (
<main>
<p>This page awaits cookies() without Suspense</p>
</main>
)
}
import { ReactNode } from 'react'
export default function GroupLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a route group layout with no config</em>
<hr />
{children}
</div>
)
}
import { ReactNode } from 'react'
export default function GroupLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a route group layout with no config</em>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
export default async function Page() {
await cookies()
return (
<main>
<p>This page awaits cookies() without Suspense</p>
</main>
)
}
import { ReactNode } from 'react'
export const unstable_instant = { prefetch: 'static' }
export default function Layout({ children }: { children: ReactNode }) {
return (
<div>
<em>This is a URL-contributing layout with unstable_instant (static)</em>
<hr />
{children}
</div>
)
}
import { cookies } from 'next/headers'
import { ReactNode } from 'react'
// This layout awaits cookies() without its own Suspense boundary.
// When (outer)/layout is shared (e.g. navigating from /foo to /),
// there is no Suspense above this layout in the new tree, so
// the navigation will be blocking.
export default async function InnerLayout({
children,
}: {
children: ReactNode
}) {
await cookies()
return (
<div>
<em>Inner route group layout (awaits cookies, no Suspense)</em>
{children}
</div>
)
}
import Link from 'next/link'
export default function Page() {
return (
<main>
<p>Index page inside (inner) route group</p>
<Link href="/suspense-in-root/static/route-group-shared-boundary/foo">
./foo
</Link>
</main>
)
}
import Link from 'next/link'
export default function FooPage() {
return (
<main>
<p>Foo page (sibling of inner route group)</p>
<Link href="/suspense-in-root/static/route-group-shared-boundary">
./
</Link>
</main>
)
}
import { ReactNode, Suspense } from 'react'
// The unstable_instant config makes this route eligible for validation.
// The Suspense here covers children in the validation render (where both
// (outer) and (inner) are in the new tree), but in a real /foo → / client
// navigation, (outer)/layout is shared and its Suspense doesn't apply.
export const unstable_instant = { prefetch: 'static' }
export default function OuterLayout({ children }: { children: ReactNode }) {
return (
<div>
<em>Outer route group layout (has Suspense around children)</em>
<Suspense fallback={<div>Loading outer...</div>}>{children}</Suspense>
</div>
)
}
......@@ -13,7 +13,7 @@ import {
import { Playwright } from '../../../lib/next-webdriver'
describe('instant validation', () => {
const { next, skipped, isNextDev } = nextTestSetup({
const { next, skipped, isNextDev, isTurbopack } = nextTestSetup({
files: __dirname,
skipDeployment: true,
env: {
......@@ -989,50 +989,96 @@ describe('instant validation', () => {
})
describe('invalid - missing suspense in parallel slot', () => {
// The "caused by" source differs between bundlers due to parallel
// route key iteration order: turbopack finds children (page.tsx)
// first, webpack finds @slot/layout.tsx first.
it('index', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/missing-suspense-in-parallel-route'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/missing-suspense-in-parallel-route/page.tsx (3:33) @ unstable_instant
> 3 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/missing-suspense-in-parallel-route/page.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
if (isTurbopack) {
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/missing-suspense-in-parallel-route/page.tsx (3:33) @ unstable_instant
> 3 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/missing-suspense-in-parallel-route/page.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
To fix this:
Provide a fallback UI using <Suspense> around this component.
Provide a fallback UI using <Suspense> around this component.
or
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/page.tsx (4:16) @ IndexSlot
> 4 | await cookies()
| ^",
"stack": [
"IndexSlot app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/page.tsx (4:16)",
],
}
`)
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/page.tsx (4:16) @ IndexSlot
> 4 | await cookies()
| ^",
"stack": [
"IndexSlot app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/page.tsx (4:16)",
],
}
`)
} else {
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/layout.tsx (1:33) @ unstable_instant
> 1 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/layout.tsx (1:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/page.tsx (4:16) @ IndexSlot
> 4 | await cookies()
| ^",
"stack": [
"IndexSlot app/suspense-in-root/static/missing-suspense-in-parallel-route/@slot/page.tsx (4:16)",
],
}
`)
}
})
it('subpage', async () => {
......@@ -1532,6 +1578,280 @@ describe('instant validation', () => {
})
})
describe('route groups', () => {
it('invalid - config on route group layout - cookies() blocks below', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/route-group-config-only'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/route-group-config-only/(group)/layout.tsx (3:33) @ unstable_instant
> 3 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/route-group-config-only/(group)/layout.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/route-group-config-only/(group)/page.tsx (4:16) @ Page
> 4 | await cookies()
| ^",
"stack": [
"Page app/suspense-in-root/static/route-group-config-only/(group)/page.tsx (4:16)",
],
}
`)
})
it('invalid - config on both route group and segment layout - cookies() blocks below', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/route-group-config-and-segment-config'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/route-group-config-and-segment-config/(group)/layout.tsx (3:33) @ unstable_instant
> 3 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/route-group-config-and-segment-config/(group)/layout.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/route-group-config-and-segment-config/(group)/page.tsx (4:16) @ Page
> 4 | await cookies()
| ^",
"stack": [
"Page app/suspense-in-root/static/route-group-config-and-segment-config/(group)/page.tsx (4:16)",
],
}
`)
})
it('invalid - config on segment layout - cookies() blocks through route group below', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/route-group-segment-config-only'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/route-group-segment-config-only/layout.tsx (3:33) @ unstable_instant
> 3 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/route-group-segment-config-only/layout.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/route-group-segment-config-only/(group)/page.tsx (4:16) @ Page
> 4 | await cookies()
| ^",
"stack": [
"Page app/suspense-in-root/static/route-group-segment-config-only/(group)/page.tsx (4:16)",
],
}
`)
})
it('invalid - config on route group layout - cookies() blocks in deeper segment', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/route-group-config-with-deeper-segment/inner'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/route-group-config-with-deeper-segment/(group)/layout.tsx (3:33) @ unstable_instant
> 3 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/route-group-config-with-deeper-segment/(group)/layout.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/route-group-config-with-deeper-segment/(group)/inner/page.tsx (4:16) @ Page
> 4 | await cookies()
| ^",
"stack": [
"Page app/suspense-in-root/static/route-group-config-with-deeper-segment/(group)/inner/page.tsx (4:16)",
],
}
`)
})
it('invalid - config on segment layout inside route group - cookies() blocks below', async () => {
const browser = await navigateTo(
'/suspense-in-root/static/route-group-deeper-segment-config/inner'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/static/route-group-deeper-segment-config/(group)/inner/layout.tsx (3:33) @ unstable_instant
> 3 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/static/route-group-deeper-segment-config/(group)/inner/layout.tsx (3:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1078",
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/static/route-group-deeper-segment-config/(group)/inner/page.tsx (4:16) @ Page
> 4 | await cookies()
| ^",
"stack": [
"Page app/suspense-in-root/static/route-group-deeper-segment-config/(group)/inner/page.tsx (4:16)",
],
}
`)
})
})
describe('route group shared boundary', () => {
// When navigating from /foo to /, (outer)/layout is shared — its
// Suspense doesn't apply to the new tree. (inner)/layout awaits
// cookies() without its own Suspense, so the navigation should
// block and produce a validation error. However, the depth-based
// validation treats both (outer) and (inner) as new at the same
// URL depth, so (outer)'s Suspense appears to cover (inner) and
// the error is missed.
it.failing(
'invalid - route group boundary is shared but validation treats it as new',
async () => {
// Navigate to /foo first
const browser = await next.browser(
'/suspense-in-root/static/route-group-shared-boundary/foo'
)
await browser.elementByCss('main')
// Client-navigate to the index page where (inner)/layout blocks
await browser
.elementByCss(
'a[href="/suspense-in-root/static/route-group-shared-boundary"]'
)
.click()
await retry(async () => {
expect(await browser.url()).toContain(
'/suspense-in-root/static/route-group-shared-boundary'
)
expect(await browser.url()).not.toContain('/foo')
})
// We expect a redbox because (inner)/layout blocks without
// Suspense in the new tree. This assertion will fail until
// the validation algorithm accounts for route group boundaries.
// NOTE: Use waitForRedbox instead of toDisplayCollapsedRedbox to
// avoid snapshot tracking — Jest counts snapshot mismatches
// globally even inside it.failing, causing a non-zero exit code.
await waitForRedbox(browser)
}
)
})
describe('disabling validation', () => {
it('in a layout', async () => {
const browser = await navigateTo(
......
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