Unverified Commit 76df801a authored by Josh Story's avatar Josh Story Committed by GitHub

Instant Validation: Allow unconfigured slots to render optionally (#92126)

When validating an instant navigation we always report blocking data
regardless of which parallel slot it was found from because it will
block the navigation regardless. To prevent accidental disabling of
validation Next.js also requires that the expected validation boundary
is actually rendered during the validation SSR pass. if it isn't it is
considered an error. However it is not uncommon to have a slot that only
renders conditionally. If during validation a slot is not rendered but
that slot also does not explicitly have an instant config it is now
considered allowable and no error is presented.
parent e3b81e05
......@@ -4766,8 +4766,8 @@ async function validateInstantConfigs(
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)
for (const id of previousBoundaryState.requiredIds) {
boundaryState.requiredIds.add(id)
}
}
......
......@@ -53,7 +53,10 @@ import {
INSTANT_SLOT_MARKER_PREFIX,
INSTANT_SLOT_MARKER_SUFFIX,
} from './instant-validation/boundary-constants'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import {
type ValidationBoundaryTracking,
allRequiredBoundariesRendered,
} from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
const hasPostpone = typeof React.unstable_postpone === 'function'
......@@ -922,7 +925,7 @@ export function trackDynamicHoleInNavigation(
// If we managed to render all the validation boundaries, that means
// that the client holes aren't blocking validation and we can disregard them.
// Note that we don't even care whether they have suspense or not.
if (boundaryState.expectedIds.size === boundaryState.renderedIds.size) {
if (allRequiredBoundariesRendered(boundaryState)) {
dynamicValidation.hasAllowedClientDynamicAboveBoundary = true
dynamicValidation.hasAllowedDynamic = true // Holes outside the boundary contribute to allowing dynamic metadata
return
......@@ -1332,7 +1335,7 @@ export function getNavigationDisallowedDynamicReasons(
return validationPreventingErrors
}
if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) {
if (!allRequiredBoundariesRendered(boundaryState)) {
const { thrownErrorsOutsideBoundary } = dynamicValidation
const rootInstantStack = dynamicValidation.slotStacks[0]
if (thrownErrorsOutsideBoundary.length === 0) {
......
export type ValidationBoundaryTracking = {
expectedIds: Set<string>
requiredIds: Set<string>
renderedIds: Set<string>
}
export function createValidationBoundaryTracking(): ValidationBoundaryTracking {
return {
expectedIds: new Set(),
requiredIds: new Set(),
renderedIds: new Set(),
}
}
export function allRequiredBoundariesRendered(
state: ValidationBoundaryTracking
): boolean {
for (const id of state.requiredIds) {
if (!state.renderedIds.has(id)) {
return false
}
}
return true
}
......@@ -1021,7 +1021,6 @@ export async function createCombinedPayloadAtDepth(
debug?.(
` ['${path}' is the boundary (url=${nextUrlDepth}, group=${currentGroupDepth})]`
)
boundaryState.expectedIds.add(path)
const finalSegmentData: SegmentData = {
...segmentData,
node: (
......@@ -1061,6 +1060,13 @@ export async function createCombinedPayloadAtDepth(
}
}
// Only require this boundary to render if the subtree has an
// instant config. Unconfigured slot subtrees are allowed to not
// render (e.g. conditionally excluded by a layout).
if (requiresInstantUI) {
boundaryState.requiredIds.add(path)
}
wrapSlotsWithMarkers(slots, slotResults)
return {
......
......@@ -165,6 +165,24 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/parallel/slot-config-children-suspended" />
</li>
<li>
<DebugLinks href="/suspense-in-root/parallel/conditional-breadcrumbs/show-both/unblocked" />
</li>
<li>
<DebugLinks href="/suspense-in-root/parallel/conditional-breadcrumbs/show-both/blocked" />
</li>
<li>
<DebugLinks href="/suspense-in-root/parallel/conditional-breadcrumbs/show-only-children/unblocked" />
</li>
<li>
<DebugLinks href="/suspense-in-root/parallel/conditional-breadcrumbs/show-only-children/blocked" />
</li>
<li>
<DebugLinks href="/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/unblocked" />
</li>
<li>
<DebugLinks href="/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/blocked" />
</li>
</ul>
<h2>Head</h2>
......
import { cookies } from 'next/headers'
export default async function BreadcrumbsPage() {
await cookies()
return <nav>breadcrumbs (calls cookies)</nav>
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return <p>show-both/blocked — children page with instant config</p>
}
import { ReactNode } from 'react'
export default function Layout({
children,
breadcrumbs,
}: {
children: ReactNode
breadcrumbs: ReactNode
}) {
return (
<main>
<div>{breadcrumbs}</div>
{children}
</main>
)
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return <p>show-both/unblocked — children page with instant config</p>
}
import { cookies } from 'next/headers'
export default async function BreadcrumbsPage() {
await cookies()
return <nav>breadcrumbs (calls cookies)</nav>
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<p>show-only-breadcrumbs/blocked — children page with instant config</p>
)
}
import { ReactNode } from 'react'
export default function Layout({
breadcrumbs,
}: {
children: ReactNode
breadcrumbs: ReactNode
}) {
return <main>{breadcrumbs}</main>
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return (
<p>show-only-breadcrumbs/unblocked — children page with instant config</p>
)
}
import { cookies } from 'next/headers'
export default async function BreadcrumbsPage() {
await cookies()
return <nav>breadcrumbs (calls cookies)</nav>
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return <p>show-only-children/blocked — children page with instant config</p>
}
import { ReactNode } from 'react'
export default function Layout({
children,
}: {
children: ReactNode
breadcrumbs: ReactNode
}) {
return <main>{children}</main>
}
export const unstable_instant = { prefetch: 'static' }
export default function Page() {
return <p>show-only-children/unblocked — children page with instant config</p>
}
......@@ -493,5 +493,167 @@ describe('instant validation - parallel slot configs', () => {
}
})
})
describe('conditional slot rendering', () => {
it('valid - both slots render, no cookies', async () => {
const href =
'/suspense-in-root/parallel/conditional-breadcrumbs/show-both/unblocked'
if (isNextDev) {
const browser = await navigateTo(href)
await expectNoDevValidationErrors(browser, await browser.url())
} else {
const result = await prerender(href)
expectNoBuildValidationErrors(result)
}
})
it('valid - only configured children slot renders, no cookies', async () => {
const href =
'/suspense-in-root/parallel/conditional-breadcrumbs/show-only-children/unblocked'
if (isNextDev) {
const browser = await navigateTo(href)
await expectNoDevValidationErrors(browser, await browser.url())
} else {
const result = await prerender(href)
expectNoBuildValidationErrors(result)
}
})
it('valid - only configured children slot renders, breadcrumbs blocked', async () => {
const href =
'/suspense-in-root/parallel/conditional-breadcrumbs/show-only-children/blocked'
if (isNextDev) {
const browser = await navigateTo(href)
await expectNoDevValidationErrors(browser, await browser.url())
} else {
const result = await prerender(href)
expectNoBuildValidationErrors(result)
}
})
it('errors when both slots render and breadcrumbs calls cookies', async () => {
const href =
'/suspense-in-root/parallel/conditional-breadcrumbs/show-both/blocked'
if (isNextDev) {
const browser = await navigateTo(href)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/suspense-in-root/parallel/conditional-breadcrumbs/show-both/blocked/page.tsx (1:33) @ unstable_instant
> 1 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/parallel/conditional-breadcrumbs/show-both/blocked/page.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/parallel/conditional-breadcrumbs/show-both/@breadcrumbs/blocked/page.tsx (3:16) @ BreadcrumbsPage
> 3 | await cookies()
| ^",
"stack": [
"BreadcrumbsPage app/suspense-in-root/parallel/conditional-breadcrumbs/show-both/@breadcrumbs/blocked/page.tsx (3:16)",
],
}
`)
} else {
const result = await prerender(href)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/parallel/conditional-breadcrumbs/show-both/blocked": Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed outside of \`<Suspense>\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route
at div (<anonymous>)
at main (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
at a (<anonymous>)
Build-time instant validation failed for route "/suspense-in-root/parallel/conditional-breadcrumbs/show-both/blocked".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
}
})
it('errors when configured children slot is hidden, no cookies', async () => {
const href =
'/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/unblocked'
if (isNextDev) {
const browser = await navigateTo(href)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route "/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/unblocked": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/unblocked/page.tsx (1:33) @ unstable_instant
> 1 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/unblocked/page.tsx (1:33)",
],
}
`)
} else {
const result = await prerender(href)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/unblocked": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.
at ignore-listed frames
Build-time instant validation failed for route "/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/unblocked".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
}
})
it('errors when configured children slot is hidden, breadcrumbs blocked', async () => {
const href =
'/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/blocked'
if (isNextDev) {
const browser = await navigateTo(href)
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route "/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/blocked": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/blocked/page.tsx (1:33) @ unstable_instant
> 1 | export const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/blocked/page.tsx (1:33)",
],
}
`)
} else {
const result = await prerender(href)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/blocked": Could not validate \`unstable_instant\` because the target segment was prevented from rendering for an unknown reason.
at ignore-listed frames
Build-time instant validation failed for route "/suspense-in-root/parallel/conditional-breadcrumbs/show-only-breadcrumbs/blocked".
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
}
})
})
})
})
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