Unverified Commit 6a39e9d2 authored by Josh Story's avatar Josh Story Committed by GitHub

[Cache Components] Exclude dynamic params from prerenders when no…

[Cache Components] Exclude dynamic params from prerenders when no generateStaticParams values is provided (#95872)

Fixes an issue in self-hosted and Vercel Adapter that causes some routes
that prerender static pages to include more route params than expected
when running in Cache Components.

For all Next.js environments any route matching a root param not already
in the cache will result in a prerender that includes all params
regardless of whether they were omitted from generateStaticParams.

For Vercel Adapter environments any route without a fallback that has an
empty shell during the build will prerender misses with all params
regardless of whether they were omitted from generateStaticParams.

This change fixes both issues and introduces a comprehensive test matrix
to catch regressions in these kinds of prerender decisions in the future

closes NAR-882
parent 203177bb
......@@ -1585,6 +1585,7 @@ export async function handleBuildComplete({
const canEmitPartialFallback =
partialFallback && fallbackRootParams?.length === 0
let htmlAllowQuery = allowQuery
let didFilterBlockingAllowQuery = false
// We only want to vary on the shell contents if there is a fallback
// present and able to be served.
......@@ -1615,6 +1616,35 @@ export async function handleBuildComplete({
)
: []
}
} else if (
fallback === null &&
isAppPage &&
renderingMode === RenderingMode.PARTIALLY_STATIC &&
routesManifest.rsc.clientParamParsing &&
remainingPrerenderableParams !== undefined
) {
// BLOCKING entries (no servable fallback) still cache their
// on-demand renders, so the same cache-key contract applies as for
// partial fallbacks: only params that `generateStaticParams` can
// still provide may partition the cache — root params (which are
// always provided) and the remaining prerenderable params.
// Including a never-prerenderable param would create a cache entry
// per param value and resolve the param into the cached content,
// so it must be stripped from the request instead, which defers it
// to a per-request resume.
const prerenderableQueryKeys = new Set<string>()
for (const paramName of fallbackRootParams ?? []) {
prerenderableQueryKeys.add(`${NEXT_QUERY_PARAM_PREFIX}${paramName}`)
}
for (const param of remainingPrerenderableParams) {
prerenderableQueryKeys.add(
`${NEXT_QUERY_PARAM_PREFIX}${param.paramName}`
)
}
htmlAllowQuery = allowQuery.filter((routeKey) =>
prerenderableQueryKeys.has(routeKey)
)
didFilterBlockingAllowQuery = true
}
const initialOutput: AdapterOutput['PRERENDER'] = {
......@@ -1699,6 +1729,12 @@ export async function handleBuildComplete({
if (routesManifest.rsc.clientParamParsing) {
dataAllowQuery = htmlAllowQuery
}
} else if (didFilterBlockingAllowQuery) {
// Blocking entries have no fallback shell whose presence could
// make the data route vary differently from the HTML route: the
// on-demand data render is cached under the same
// prerenderable-params-only contract.
dataAllowQuery = htmlAllowQuery
}
if (renderingMode === RenderingMode.PARTIALLY_STATIC) {
......
......@@ -585,6 +585,7 @@ export async function handler(
(prerenderInfo.fallbackRootParams?.length ?? 0) > 0
let ssgCacheKey: string | null = null
let usesCompletedShellCacheKey = false
if (
!isDraftMode &&
isSSG &&
......@@ -597,17 +598,19 @@ export async function handler(
// partial fallbacks we instead derive the cache key from the shell
// that matched this request so `/prefix/[one]/[two]` can specialize into
// `/prefix/c/[two]` without promoting all the way to `/prefix/c/foo`.
// This includes entries with unresolved ROOT params: those requests are
// served blocking (no shell can be shared across root branches), but
// the entry they produce is still keyed by the completed shell — root
// params and any other prerenderable params resolve into the key while
// params that `generateStaticParams` can never provide stay as
// placeholders and must not partition the cache.
const fallbackPathname = prerenderMatch
? typeof prerenderInfo?.fallback === 'string'
? prerenderInfo.fallback
: prerenderMatch.source
: null
if (
fallbackPathname &&
prerenderInfo?.fallbackRouteParams?.length &&
!hasUnresolvedRootFallbackParams
) {
if (fallbackPathname && prerenderInfo?.fallbackRouteParams?.length) {
if (remainingPrerenderableParams.length > 0) {
const completedShellCacheKey = buildCompletedShellCacheKey(
fallbackPathname,
......@@ -618,10 +621,10 @@ export async function handler(
// If applying the current request params doesn't make the shell any
// more complete, then this shell is already at its most complete
// form and should remain shared rather than creating a new cache entry.
ssgCacheKey =
completedShellCacheKey !== fallbackPathname
? completedShellCacheKey
: null
if (completedShellCacheKey !== fallbackPathname) {
ssgCacheKey = completedShellCacheKey
usesCompletedShellCacheKey = true
}
}
} else {
ssgCacheKey = resolvedPathname
......@@ -1494,9 +1497,22 @@ export async function handler(
effectiveFallbackRouteParams.length <
(prerenderInfo?.fallbackRouteParams?.length ?? 0)
? createOpaqueFallbackRouteParams(effectiveFallbackRouteParams)
: isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null
: // A render cached under a completed shell cache key must keep
// deferring the params the key leaves as placeholders (the
// ones `generateStaticParams` can never provide) so they
// resume per request instead of baking into the shared entry.
// This is the blocking analog of the background shell
// upgrade above and is likewise self-hosted only: in minimal
// mode the platform proxy owns this contract by stripping
// never-prerenderable params from the request, which defers
// them through the placeholder handling instead.
!isMinimalMode &&
usesCompletedShellCacheKey &&
remainingFallbackRouteParams.length > 0
? createOpaqueFallbackRouteParams(remainingFallbackRouteParams)
: isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null
// For staged dynamic rendering (Cached Navigations) and debug static
// shell rendering, pass the fallback params via request meta so the
......
import { ReactNode } from 'react'
// Root layout for the demo index page. Every matrix branch hosts its own
// root layout (the with-root-param branches place theirs inside [lang]), so
// the index needs one of its own via this route group.
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// Demo index for the cache-components route matrix. Every layout and page
// renders a Boundary: a border marking the segment plus a color badge
// derived from performance.now() at render time.
//
// How to read the badges when reloading a URL:
// - colors CHANGE on every reload -> the region is re-rendered (resumed)
// per request.
// - colors STAY THE SAME -> the region is served from a cached
// render. Whether that is correct depends on the matrix: params that
// generateStaticParams can complete MAY be prerendered; params it never
// provides must NOT be.
//
// Every page links to its variants along all dimensions (lang, category,
// shell topology, branch, matrix), so any starting point can reach the
// whole matrix.
export default function Page() {
return (
<main style={{ fontFamily: 'monospace', lineHeight: 1.8, padding: 16 }}>
<h1>cache components route matrix</h1>
<p>
Reload each page a few times and watch the color badges. Changing color
= re-rendered per request. Frozen color = served from a cached render.
</p>
<h2>partial-static-param — lang and category enumerated, id never</h2>
<ul>
<li>
<a href="/partial-static-param/with-root-param/empty-shell/fr/toys/123">
with-root-param/empty-shell/fr/toys/123
</a>{' '}
— BUG (all modes): non-enumerated root param, ALL badges freeze
</li>
<li>
<a href="/partial-static-param/without-root-param/empty-shell/en/toys/123">
without-root-param/empty-shell/en/toys/123
</a>{' '}
— correct self-hosted (all badges cycle); BUG on Vercel (freezes once
HIT)
</li>
<li>
<a href="/partial-static-param/without-root-param/non-empty-shell/en/toys/123">
without-root-param/non-empty-shell/en/toys/123
</a>{' '}
— shell badges stable, [id] region cycles (the healthy split)
</li>
</ul>
<h2>fully-static-param — a complete instance (en/shoes/1) enumerated</h2>
<ul>
<li>
<a href="/fully-static-param/without-root-param/empty-shell/en/shoes/1">
without-root-param/empty-shell/en/shoes/1
</a>{' '}
— fully prerendered at build: ALL badges frozen is CORRECT here
</li>
<li>
<a href="/fully-static-param/without-root-param/empty-shell/en/shoes/2">
without-root-param/empty-shell/en/shoes/2
</a>{' '}
— id is prerenderable: completes to a per-URL prerender on demand
(classic blocking ISR), frozen after first load is CORRECT
</li>
</ul>
<h2>dynamic-param — no generateStaticParams at all</h2>
<ul>
<li>
<a href="/dynamic-param/without-root-param/empty-shell/anything/at/all">
without-root-param/empty-shell/anything/at/all
</a>{' '}
— nothing prerenderable: one shared entry for every URL, all badges
cycle on every load
</li>
<li>
<a href="/dynamic-param/without-root-param/non-empty-shell/anything/at/all">
without-root-param/non-empty-shell/anything/at/all
</a>{' '}
— shared generic shell (stable shell badges for every URL), params
always resumed
</li>
</ul>
</main>
)
}
import { VariantControls } from '../../../../components/variant-controls'
// TOMBSTONE: dynamic-param + root params is not a possible combination, but
// it IS a reachable control state in the variant switcher, so this page
// exists to explain the gap instead of 404ing.
export const instant = false
export default async function Page({
params,
}: {
params: Promise<{ slug?: string[] }>
}) {
// Every route follows the same positional scheme —
// /<scenario>/<root-param>/<shell>/<lang>/<category>/<id> — so the
// catch-all receives [shell, lang, category, id]. Recover the dimensions
// so the controls can navigate away with everything else preserved.
const { slug = [] } = await params
const [tree = 'empty-shell', lang = 'fr', category = 'toys', id = '1'] = slug
return (
<main style={{ fontFamily: 'monospace', lineHeight: 1.8, padding: 16 }}>
<h1>this combination cannot exist</h1>
<p>
You have selected the <strong>dynamic-param</strong> matrix with{' '}
<strong>root params</strong> enabled — a combination that is not
actually possible in a Next.js app:
</p>
<ul>
<li>
the dynamic-param matrix has no <code>generateStaticParams</code>{' '}
anywhere (that is its defining property), and
</li>
<li>
root params are required to be provided by{' '}
<code>generateStaticParams</code> — the build fails with &quot;A
required root parameter was not provided&quot; if a root param has no
enumerated value, because the document itself varies by a root param
and there is no mechanism to defer it.
</li>
</ul>
<p>
So a route whose root layout lives inside a param segment must enumerate
at least one value for that param, which would make it the
partial-static-param (or fully-static-param) matrix. Uncheck{' '}
<em>root params</em> or switch matrices to return to a real page.
</p>
<VariantControls
params={Promise.resolve({ lang, category, id })}
matrix="dynamic-param"
tree={tree}
branch="with-root-param"
/>
</main>
)
}
import { ReactNode } from 'react'
// Root layout for the dynamic-param/with-root-param TOMBSTONE. Note the
// placement: this root layout sits ABOVE the catch-all segment, so the
// segment params are NOT root params — which is exactly why this route can
// build while the combination it documents cannot: a real
// with-root-param branch would put the root layout inside [lang], and root
// params must be provided by generateStaticParams, which the dynamic-param
// matrix doesn't have.
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Empty-shell tree of the DYNAMIC-param matrix: there is NO
// generateStaticParams anywhere on this route, so no param is ever
// prerenderable and nothing may be completed on demand. A single shared
// entry must serve every URL of this route, with every param resumed per
// request. (There is no with-root-param branch in this matrix: root params
// without generateStaticParams are a build error.)
//
// The params are read outside of any Suspense boundary, so the only shell
// is empty and downgrades to a blocking route. `instant = false` opts the
// route out of requiring an instant shell.
export const instant = false
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Id params={params} />
<VariantControls
params={params}
matrix="dynamic-param"
tree="empty-shell"
branch="without-root-param"
/>
</Boundary>
)
}
import { Boundary } from '../../../../../../components/boundary'
// Reads `category` with NO Suspense boundary (the empty-shell tree's
// convention). The rendered content is identical to the non-empty-shell
// tree's [category] layout — the only difference is the missing Suspense
// boundary.
export default async function CategoryLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
import { Boundary } from '../../../../../components/boundary'
// Reads `lang` with NO Suspense boundary (the empty-shell tree's
// convention): whenever `lang` is deferred, the postpone propagates to the
// root and the shell stays empty. The rendered content is identical to the
// non-empty-shell tree's [lang] layout — the only difference is the missing
// Suspense boundary.
export default async function LangLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<Boundary name={`[lang] layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Non-empty-shell tree of the DYNAMIC-param matrix: the same content as the
// empty-shell tree's page, but with Suspense boundaries around all param
// reads, so the route's single shell carries static content. There is NO
// generateStaticParams anywhere: no param is ever prerenderable, so the
// generic shell can never specialize — one shared entry serves every URL,
// with every param resumed per request.
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Suspense
fallback={
<Boundary name="[id] region (loading...)">
<div id="id-fallback" data-fallback>
loading id...
</div>
</Boundary>
}
>
<Id params={params} />
</Suspense>
{/* The nav needs the current id, so it awaits params — it gets its
own Suspense boundary to keep the page shell param-free. */}
<Suspense fallback={null}>
<VariantControls
params={params}
matrix="dynamic-param"
tree="non-empty-shell"
branch="without-root-param"
/>
</Suspense>
</Boundary>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../../components/boundary'
// `category` is read in its own Suspense boundary (`lang` is read by the
// [lang] layout above): shells where it is concrete render it statically,
// and generic shells show `#category-fallback`. This makes the served
// shell's specialization observable from the static part of the response.
// The Boundary badge shows whether this segment was re-rendered for the
// current request.
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ category: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[category] layout (loading...)">
<div id="category-fallback" data-fallback>
loading category...
</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../components/boundary'
// Reads `lang` in its own Suspense boundary (the non-empty-shell tree's
// convention): shells where `lang` is concrete render it statically, and
// generic shells show the fallback. The rendered content is identical to
// the empty-shell tree's [lang] layout — the only difference is the
// Suspense boundary.
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<Boundary name={`[lang] layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[lang] layout (loading...)">
<div data-fallback>loading lang...</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Empty-shell tree of the FULLY-static-param matrix, under a root param.
// The segment layouts provide `lang` and `category`, and this page's
// generateStaticParams provides `id`, so a complete instance (en/shoes/1)
// is enumerated and ALL params are prerenderable: on-demand completion may
// resolve everything, and fully-frozen badge values across requests are
// CORRECT here.
//
// The params are still read outside of any Suspense boundary, so shells
// with a deferred param are empty and downgrade to blocking routes.
// `instant = false` opts the route out of requiring an instant shell.
export async function generateStaticParams() {
return [{ id: '1' }]
}
export const instant = false
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Id params={params} />
<VariantControls
params={params}
matrix="fully-static-param"
tree="empty-shell"
branch="with-root-param"
/>
</Boundary>
)
}
import { Boundary } from '../../../../../../components/boundary'
export async function generateStaticParams() {
return [{ category: 'shoes' }]
}
// Reads `category` with NO Suspense boundary (the empty-shell tree's
// convention). The rendered content is identical to the non-empty-shell
// tree's [category] layout — the only difference is the missing Suspense
// boundary.
export default async function CategoryLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
import { Boundary } from '../../../../../components/boundary'
export async function generateStaticParams() {
return [{ lang: 'en' }]
}
// The ROOT layout lives inside [lang], making `lang` a ROOT param: the
// document itself (the html tag) varies by lang with no Suspense boundary.
// Root params must be provided by every generateStaticParams result — the
// build enforces this — so `lang` is always a prerenderable param.
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<html lang={lang}>
<body>
<Boundary name={`root layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
</body>
</html>
)
}
import { Suspense } from 'react'
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Non-empty-shell tree of the FULLY-static-param matrix, under a root
// param. Together with the segment layouts' generateStaticParams, this
// page's entries enumerate a complete instance (en/shoes/1), so ALL params
// are prerenderable: on-demand completion may resolve everything, and
// fully-frozen badge values across requests are CORRECT here.
export async function generateStaticParams() {
return [
{ lang: 'en' },
{ lang: 'en', category: 'shoes' },
{ lang: 'en', category: 'shoes', id: '1' },
]
}
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Suspense
fallback={
<Boundary name="[id] region (loading...)">
<div id="id-fallback" data-fallback>
loading id...
</div>
</Boundary>
}
>
<Id params={params} />
</Suspense>
{/* The nav needs the current id, so it awaits params — it gets its
own Suspense boundary to keep the page shell param-free. */}
<Suspense fallback={null}>
<VariantControls
params={params}
matrix="fully-static-param"
tree="non-empty-shell"
branch="with-root-param"
/>
</Suspense>
</Boundary>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../../components/boundary'
// `category` is read in its own Suspense boundary: shells where it is
// concrete render it statically, and generic shells show
// `#category-fallback`. This makes the served shell's specialization
// observable from the static part of the response. (`lang` is a root param
// and is part of the document itself, rendered by the root layout.)
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ category: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[category] layout (loading...)">
<div id="category-fallback" data-fallback>
loading category...
</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import { Boundary } from '../../../../../components/boundary'
export async function generateStaticParams() {
return [{ lang: 'en' }]
}
// The ROOT layout lives inside [lang], making `lang` a ROOT param: the
// document itself (the html tag) varies by lang with no Suspense boundary.
// Root params must be provided by every generateStaticParams result — the
// build enforces this — so `lang` is always a prerenderable param.
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<html lang={lang}>
<body>
<Boundary name={`root layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
</body>
</html>
)
}
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Empty-shell tree of the FULLY-static-param matrix: `generateStaticParams`
// enumerates a complete instance (en/shoes/1), so ALL params — including
// `id` — are prerenderable. On-demand requests may complete every param,
// producing a full static prerender per URL (classic blocking-ISR
// semantics): repeated badge values across requests are CORRECT here.
//
// The params are still read outside of any Suspense boundary, so shells
// with a deferred param are empty and downgrade to blocking routes.
// `instant = false` opts the route out of requiring an instant shell.
export async function generateStaticParams() {
return [
{ lang: 'en' },
{ lang: 'en', category: 'shoes' },
{ lang: 'en', category: 'shoes', id: '1' },
]
}
export const instant = false
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Id params={params} />
<VariantControls
params={params}
matrix="fully-static-param"
tree="empty-shell"
branch="without-root-param"
/>
</Boundary>
)
}
import { Boundary } from '../../../../../../components/boundary'
// Reads `category` with NO Suspense boundary (the empty-shell tree's
// convention). The rendered content is identical to the non-empty-shell
// tree's [category] layout — the only difference is the missing Suspense
// boundary.
export default async function CategoryLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
import { Boundary } from '../../../../../components/boundary'
// Reads `lang` with NO Suspense boundary (the empty-shell tree's
// convention): whenever `lang` is deferred, the postpone propagates to the
// root and the shell stays empty. The rendered content is identical to the
// non-empty-shell tree's [lang] layout — the only difference is the missing
// Suspense boundary.
export default async function LangLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<Boundary name={`[lang] layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Non-empty-shell tree of the FULLY-static-param matrix: the same content
// as the empty-shell tree's page, but with Suspense boundaries around all
// param reads. `generateStaticParams` enumerates a complete instance
// (en/shoes/1), so ALL params — including `id` — are prerenderable:
// on-demand completion may resolve everything, and fully-frozen badge
// values across requests are CORRECT here.
export async function generateStaticParams() {
return [
{ lang: 'en' },
{ lang: 'en', category: 'shoes' },
{ lang: 'en', category: 'shoes', id: '1' },
]
}
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Suspense
fallback={
<Boundary name="[id] region (loading...)">
<div id="id-fallback" data-fallback>
loading id...
</div>
</Boundary>
}
>
<Id params={params} />
</Suspense>
{/* The nav needs the current id, so it awaits params — it gets its
own Suspense boundary to keep the page shell param-free. */}
<Suspense fallback={null}>
<VariantControls
params={params}
matrix="fully-static-param"
tree="non-empty-shell"
branch="without-root-param"
/>
</Suspense>
</Boundary>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../../components/boundary'
// `category` is read in its own Suspense boundary (`lang` is read by the
// [lang] layout above): shells where it is concrete render it statically,
// and generic shells show `#category-fallback`. This makes the served
// shell's specialization observable from the static part of the response.
// The Boundary badge shows whether this segment was re-rendered for the
// current request.
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ category: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[category] layout (loading...)">
<div id="category-fallback" data-fallback>
loading category...
</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../components/boundary'
// Reads `lang` in its own Suspense boundary (the non-empty-shell tree's
// convention): shells where `lang` is concrete render it statically, and
// generic shells show the fallback. The rendered content is identical to
// the empty-shell tree's [lang] layout — the only difference is the
// Suspense boundary.
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<Boundary name={`[lang] layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[lang] layout (loading...)">
<div data-fallback>loading lang...</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Empty-shell variant under a root param: the params are read outside of
// any Suspense boundary (here and in the segment layouts above), so the
// postpone propagates to the root and every build-time shell is empty.
// `instant = false` opts the route out of requiring an instant (non-empty)
// shell.
//
// The rendered content is identical to the non-empty-shell tree's page —
// the only difference is that nothing here is wrapped in Suspense.
//
// The segment layouts above provide `lang` (required for root params) and
// partially cover `category` via their generateStaticParams; `id` is never
// provided, so `id` must never be resolved into a cached shell and must
// never be part of a cache key — including for requests whose `lang` value
// was not enumerated, which match the base route entry where `lang` is an
// unresolved root param.
export const instant = false
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Id params={params} />
<VariantControls
params={params}
matrix="partial-static-param"
tree="empty-shell"
branch="with-root-param"
/>
</Boundary>
)
}
import { Boundary } from '../../../../../../components/boundary'
export async function generateStaticParams() {
return [{ category: 'shoes' }]
}
// Reads `category` with NO Suspense boundary (the empty-shell tree's
// convention). The rendered content is identical to the non-empty-shell
// tree's [category] layout — the only difference is the missing Suspense
// boundary.
export default async function CategoryLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
import { Boundary } from '../../../../../components/boundary'
export async function generateStaticParams() {
return [{ lang: 'en' }]
}
// The ROOT layout lives inside [lang], making `lang` a ROOT param: the
// document itself (the html tag) varies by lang with no Suspense boundary.
// Root params must be provided by every generateStaticParams result — the
// build enforces this — so `lang` is always a prerenderable param.
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<html lang={lang}>
<body>
<Boundary name={`root layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
</body>
</html>
)
}
import { Suspense } from 'react'
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// Non-empty-shell variant under a root param: the same content as the
// empty-shell tree's page, but with Suspense boundaries around the non-root
// param reads (in this page and the [category] layout above), so shells
// contain static content and no empty-shell downgrade happens.
//
// `generateStaticParams` provides `lang` in every entry (required for root
// params) and partially covers `category`; `id` is never provided and must
// never resolve into a cached shell nor participate in a cache key.
//
// The page's own Boundary badge sits OUTSIDE the id Suspense boundary, so
// it belongs to the cached shell: its color is legitimately stable across
// requests, in contrast to the badge inside the deferred region.
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
}
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Suspense
fallback={
<Boundary name="[id] region (loading...)">
<div id="id-fallback" data-fallback>
loading id...
</div>
</Boundary>
}
>
<Id params={params} />
</Suspense>
{/* The nav needs the current id, so it awaits params — it gets its
own Suspense boundary to keep the page shell param-free. */}
<Suspense fallback={null}>
<VariantControls
params={params}
matrix="partial-static-param"
tree="non-empty-shell"
branch="with-root-param"
/>
</Suspense>
</Boundary>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../../components/boundary'
// `category` is read in its own Suspense boundary: shells where it is
// concrete render it statically, and generic shells show
// `#category-fallback`. This makes the served shell's specialization
// observable from the static part of the response. (`lang` is a root param
// and is part of the document itself, rendered by the root layout.)
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ category: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[category] layout (loading...)">
<div id="category-fallback" data-fallback>
loading category...
</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import { Boundary } from '../../../../../components/boundary'
export async function generateStaticParams() {
return [{ lang: 'en' }]
}
// The ROOT layout lives inside [lang], making `lang` a ROOT param: the
// document itself (the html tag) varies by lang with no Suspense boundary.
// Root params must be provided by every generateStaticParams result — the
// build enforces this — so `lang` is always a prerenderable param.
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<html lang={lang}>
<body>
<Boundary name={`root layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
</body>
</html>
)
}
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// This route intentionally produces EMPTY build-time shells: the params are
// read outside of any Suspense boundary (here and in the segment layouts
// above), so the postpone propagates to the root and none of the shells
// contain static content. `instant = false` opts the route out of requiring
// an instant (non-empty) shell.
//
// The rendered content is identical to the non-empty-shell tree's page —
// the only difference is that nothing here is wrapped in Suspense.
//
// `generateStaticParams` never provides `id`, so `id` must never be resolved
// into a cached shell and must never be part of a cache key: only `lang` and
// `category` can be completed into more specific shells on demand.
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
}
export const instant = false
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Id params={params} />
<VariantControls
params={params}
matrix="partial-static-param"
tree="empty-shell"
branch="without-root-param"
/>
</Boundary>
)
}
import { Boundary } from '../../../../../../components/boundary'
// Reads `category` with NO Suspense boundary (the empty-shell tree's
// convention). The rendered content is identical to the non-empty-shell
// tree's [category] layout — the only difference is the missing Suspense
// boundary.
export default async function CategoryLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
import { Boundary } from '../../../../../components/boundary'
// Reads `lang` with NO Suspense boundary (the empty-shell tree's
// convention): whenever `lang` is deferred, the postpone propagates to the
// root and the shell stays empty. The rendered content is identical to the
// non-empty-shell tree's [lang] layout — the only difference is the missing
// Suspense boundary.
export default async function LangLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<Boundary name={`[lang] layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { Boundary } from '../../../../../../../components/boundary'
import { VariantControls } from '../../../../../../../components/variant-controls'
// The non-empty-shell variant of the fixture: the same content as the
// empty-shell tree's page, but with Suspense boundaries around all param
// reads (in this page and the segment layouts above), so every shell for
// this route contains static content and no empty-shell downgrade happens.
//
// `generateStaticParams` covers `lang` and `category` but never `id`, so `id`
// must never resolve into a cached shell and must never be part of a cache
// key: only `lang` and `category` can be completed into more specific shells.
//
// The page's own Boundary badge sits OUTSIDE the id Suspense boundary, so
// it belongs to the cached shell: its color is legitimately stable across
// requests, in contrast to the badge inside the deferred region.
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
}
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
return (
<Boundary name={`[id] region (${id})`}>
<div id="id">{id}</div>
</Boundary>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<Boundary name="page shell">
<div id="static">static page content</div>
<Suspense
fallback={
<Boundary name="[id] region (loading...)">
<div id="id-fallback" data-fallback>
loading id...
</div>
</Boundary>
}
>
<Id params={params} />
</Suspense>
{/* The nav needs the current id, so it awaits params — it gets its
own Suspense boundary to keep the page shell param-free. */}
<Suspense fallback={null}>
<VariantControls
params={params}
matrix="partial-static-param"
tree="non-empty-shell"
branch="without-root-param"
/>
</Suspense>
</Boundary>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../../components/boundary'
// `category` is read in its own Suspense boundary (`lang` is read by the
// [lang] layout above): shells where it is concrete render it statically,
// and generic shells show `#category-fallback`. This makes the served
// shell's specialization observable from the static part of the response.
// The Boundary badge shows whether this segment was re-rendered for the
// current request.
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<Boundary name={`[category] layout (${category})`}>
<div id="category">{category}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ category: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[category] layout (loading...)">
<div id="category-fallback" data-fallback>
loading category...
</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import { Suspense, type ReactNode } from 'react'
import { Boundary } from '../../../../../components/boundary'
// Reads `lang` in its own Suspense boundary (the non-empty-shell tree's
// convention): shells where `lang` is concrete render it statically, and
// generic shells show the fallback. The rendered content is identical to
// the empty-shell tree's [lang] layout — the only difference is the
// Suspense boundary.
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<Boundary name={`[lang] layout (${lang})`}>
<div id="lang">{lang}</div>
{children}
</Boundary>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ lang: string }>
}) {
return (
<Suspense
fallback={
<Boundary name="[lang] layout (loading...)">
<div data-fallback>loading lang...</div>
</Boundary>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import type { ReactNode } from 'react'
// Synchronous pseudo-RNG seeded from a per-render timestamp. Both the
// number and the derived color change on every render, so a frozen color
// visually proves a stored render is being replayed from the cache, while
// a changing color proves the region is re-rendered per request.
// `performance.now()` is prerenderable (unlike dynamic IO), so badges in
// cached shell regions legitimately keep a stable color — the bug is when
// regions that should be per-request are stable too.
function pseudoRandomColor(seed: number): string {
// Integerize with sub-millisecond precision so consecutive renders get
// distinct seeds, then scramble (mulberry32-style) so nearby seeds
// produce visually distant hues.
let t = Math.floor(seed * 1000) >>> 0
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
const n = (t ^ (t >>> 14)) >>> 0
return `hsl(${n % 360}deg 85% 55%)`
}
// The badge is deliberately a CHILDLESS component: during a resume, React
// only replays the component path that leads to postponed holes, and a
// subtree with no hole below it is never re-executed. Because Badge wraps
// no children it can never be on a hole path, so it runs exactly once per
// genuine render of its region. A frozen color therefore always means
// "this output came from a stored render", and a changing color always
// means "this region was truly re-rendered" — replay can't muddy either
// signal.
function Badge({ name }: { name: string }) {
const renderedAt = performance.now()
const color = pseudoRandomColor(renderedAt)
// The visible color and rendered-at text must reflect the value that was
// SERVED in the HTML, even though the inlined hydration (flight) payload
// is regenerated fresh per request and React reconciles the DOM against
// it after load. Three facts make that possible:
//
// 1. Inline scripts execute when the parser inserts them; React patching
// a script element's text later does NOT re-execute it. So the paint
// command below runs exactly once, with the served value baked in.
// 2. React never patches attributes or style properties it didn't render:
// the script paints via `data-value`, `title`, and the
// `--badge-color` custom property — none of which appear in the JSX —
// so post-hydration updates leave them alone. The dot's background is
// the constant string `var(--badge-color)`, which compares equal on
// every update and is never rewritten.
// 3. The visible number is rendered by CSS (`content: attr(data-value)`),
// not as a React-managed text node, so there is no text mismatch for
// hydration to "fix".
//
// The `if not already set` guard means a freshly inserted script (e.g. a
// client-side navigation mounting new badge elements) paints its own
// fresh value, while re-executions against an already-painted badge are
// no-ops.
const paint = `{const s=document.currentScript;const el=s&&s.previousElementSibling;if(el&&!el.getAttribute('data-value')){el.setAttribute('data-value',${JSON.stringify(
renderedAt.toFixed(3)
)});el.setAttribute('title',${JSON.stringify(
String(renderedAt)
)});el.style.setProperty('--badge-color',${JSON.stringify(color)});}}`
return (
<span
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 8,
}}
>
<style>{`[data-badge]::after{content:' rendered-at ' attr(data-value);opacity:0.6;font-weight:normal}`}</style>
<span data-badge={name} suppressHydrationWarning>
<span
style={{
display: 'inline-block',
width: 16,
height: 16,
borderRadius: '50%',
background: 'var(--badge-color)',
border: '1px solid #0003',
verticalAlign: 'middle',
}}
/>
</span>
<script
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: paint }}
/>
</span>
)
}
// A visible wrapper for a layout or page: a border marking the segment's
// extent plus the render-provenance Badge. The wrapper itself renders
// nothing time-dependent — the badge owns the timestamp — so it doesn't
// matter that the wrapper is replayed on resume (it wraps children and is
// therefore always on the hole path). Deliberately uses no element ids so
// it can never collide with the test selectors (#rendered-at, #category,
// ...).
export function Boundary({
name,
children,
}: {
name: string
children?: ReactNode
}) {
return (
<div
data-boundary={name}
style={{
border: '2px solid #94a3b8',
borderRadius: 8,
padding: 12,
margin: 8,
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
fontFamily: 'monospace',
fontSize: 12,
marginBottom: 8,
}}
>
<strong>{name}</strong>
<Badge name={name} />
</div>
{children}
</div>
)
}
'use client'
import { use } from 'react'
// Interactive variant switcher: every dimension of the route matrix is a
// control whose checked state derives from the server-rendered scenario
// (the current URL), and changing a control navigates to the equivalent
// URL with the new dimension value.
//
// Navigation is a FULL page load (window.location, not router.push): the
// badge paint scripts describe initial-HTML render provenance, and client
// navigations re-render content from flight data without re-executing
// them, which breaks the UI's coherence. This whole fixture is a test of
// initial HTML loading, so every control change reloads the document.
//
// - lang and category are RADIOS between their prerendered value (the one
// generateStaticParams enumerates in the partial/fully matrices) and a
// canonical non-prerendered value. A current value that is neither (e.g.
// a probe-generated unique value) reads as non-prerendered.
// - the matrix is a three-way RADIO.
// - the branch (root params) and shell topology are CHECKBOXES.
//
// Every combination is navigable — including dynamic-param with root
// params, which lands on a tombstone page explaining that the combination
// cannot exist.
//
// This component unwraps params with use(), so it inherits the params'
// disposition exactly like the previous server-component links did: on
// empty-shell pages it renders in the deferred region; on non-empty pages
// it must be wrapped in its own Suspense boundary so the page shell stays
// param-free.
const MATRICES = [
'partial-static-param',
'fully-static-param',
'dynamic-param',
] as const
const PRERENDERED_LANG = 'en'
const NOT_PRERENDERED_LANG = 'fr'
const PRERENDERED_CATEGORY = 'shoes'
const NOT_PRERENDERED_CATEGORY = 'toys'
const PRERENDERED_ID = '1'
const NOT_PRERENDERED_ID = '2'
type Matrix = (typeof MATRICES)[number]
type Branch = 'with-root-param' | 'without-root-param'
export function VariantControls({
params,
matrix,
tree,
branch,
}: {
params: Promise<{ lang: string; category: string; id: string }>
matrix: Matrix
tree: string
branch: Branch
}) {
const { lang, category, id } = use(params)
const current = { matrix, branch, tree, lang, category, id }
function hrefFor(dims: typeof current) {
// Trees that only exist in one place (e.g. empty-shell-dynamic in the
// standalone app) map to their closest equivalent when any dimension
// changes.
const targetTree =
dims.tree === tree && dims.matrix === matrix && dims.branch === branch
? dims.tree
: dims.tree === 'empty-shell-dynamic'
? 'empty-shell'
: dims.tree
// Every route follows the same positional scheme —
// /<scenario>/<root-param>/<shell>/<lang>/<category>/<id> — the
// with/without-root-param distinction lives entirely in where each
// branch's first layout sits (above [lang] or at [lang]).
return `/${dims.matrix}/${dims.branch}/${targetTree}/${dims.lang}/${dims.category}/${dims.id}`
}
function push(patch: Partial<typeof current>) {
window.location.assign(hrefFor({ ...current, ...patch }))
}
const langLabel = branch === 'with-root-param' ? 'root param' : 'lang'
const langIsPrerendered = lang === PRERENDERED_LANG
const categoryIsPrerendered = category === PRERENDERED_CATEGORY
return (
<nav
style={{
fontFamily: 'monospace',
fontSize: 12,
marginTop: 12,
borderTop: '1px dashed #94a3b8',
paddingTop: 8,
display: 'flex',
flexWrap: 'wrap',
gap: 16,
}}
>
<fieldset style={{ border: '1px solid #cbd5e1', padding: 6 }}>
<legend>{langLabel}</legend>
<label style={{ display: 'block' }}>
<input
type="radio"
name="variant-lang"
checked={langIsPrerendered}
onChange={() => push({ lang: PRERENDERED_LANG })}
/>{' '}
prerendered ({PRERENDERED_LANG})
</label>
<label style={{ display: 'block' }}>
<input
type="radio"
name="variant-lang"
checked={!langIsPrerendered}
onChange={() => push({ lang: NOT_PRERENDERED_LANG })}
/>{' '}
non-prerendered (
{lang === PRERENDERED_LANG ? NOT_PRERENDERED_LANG : lang})
</label>
</fieldset>
<fieldset style={{ border: '1px solid #cbd5e1', padding: 6 }}>
<legend>category</legend>
<label style={{ display: 'block' }}>
<input
type="radio"
name="variant-category"
checked={categoryIsPrerendered}
onChange={() => push({ category: PRERENDERED_CATEGORY })}
/>{' '}
prerendered ({PRERENDERED_CATEGORY})
</label>
<label style={{ display: 'block' }}>
<input
type="radio"
name="variant-category"
checked={!categoryIsPrerendered}
onChange={() => push({ category: NOT_PRERENDERED_CATEGORY })}
/>{' '}
non-prerendered (
{category === PRERENDERED_CATEGORY
? NOT_PRERENDERED_CATEGORY
: category}
)
</label>
</fieldset>
{/* Only the fully-static matrix enumerates an id value, so id
prerender-ness is only a real dimension there — the radios stay
visible but disabled elsewhere to teach exactly that. */}
<fieldset
style={{ border: '1px solid #cbd5e1', padding: 6 }}
disabled={matrix !== 'fully-static-param'}
title={
matrix !== 'fully-static-param'
? 'id is never prerenderable outside the fully-static-param matrix'
: undefined
}
>
<legend>id</legend>
<label style={{ display: 'block' }}>
<input
type="radio"
name="variant-id"
checked={id === PRERENDERED_ID}
onChange={() => push({ id: PRERENDERED_ID })}
/>{' '}
prerendered ({PRERENDERED_ID})
</label>
<label style={{ display: 'block' }}>
<input
type="radio"
name="variant-id"
checked={id !== PRERENDERED_ID}
onChange={() => push({ id: NOT_PRERENDERED_ID })}
/>{' '}
non-prerendered ({id === PRERENDERED_ID ? NOT_PRERENDERED_ID : id})
</label>
</fieldset>
<fieldset style={{ border: '1px solid #cbd5e1', padding: 6 }}>
<legend>matrix</legend>
{MATRICES.map((variantMatrix) => (
<label key={variantMatrix} style={{ display: 'block' }}>
<input
type="radio"
name="variant-matrix"
checked={matrix === variantMatrix}
onChange={() => push({ matrix: variantMatrix })}
/>{' '}
{variantMatrix}
</label>
))}
</fieldset>
<fieldset style={{ border: '1px solid #cbd5e1', padding: 6 }}>
<legend>structure</legend>
<label style={{ display: 'block' }}>
<input
type="checkbox"
checked={branch === 'with-root-param'}
onChange={(event) =>
push({
branch: event.target.checked
? 'with-root-param'
: 'without-root-param',
})
}
/>{' '}
root params
</label>
<label style={{ display: 'block' }}>
<input
type="checkbox"
checked={tree !== 'non-empty-shell'}
onChange={(event) =>
push({
tree: event.target.checked ? 'empty-shell' : 'non-empty-shell',
})
}
/>{' '}
empty shell
</label>
</fieldset>
</nav>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
// The partial matrix's steady-state expectations (on-demand shell
// specialization, entry sharing across never-prerenderable params)
// describe the partialFallback serving contract, which the adapter only
// emits for apps with Partial Prefetching enabled (vercel/next.js#96074).
partialPrefetching: true,
}
module.exports = nextConfig
......@@ -3,6 +3,10 @@
*/
const nextConfig = {
cacheComponents: true,
// Intermediate (resolved-root-param) entries in this fixture rely on the
// partialFallback serving contract, which the adapter only emits for
// apps with Partial Prefetching enabled (vercel/next.js#96074).
partialPrefetching: true,
}
module.exports = nextConfig
......@@ -42,22 +42,39 @@ describe('partial-fallback-root-blocking', () => {
// TODO: Re-enable once infra supports multiple layers of fallbacks
if (!isNextDeploy) {
it('should not reuse a shared shell cache entry for unknown root branches', async () => {
it('should serve unknown root branches with the root param resolved and other params deferred', async () => {
const firstResult = await fetchSplitHTML('/fr/two')
// The root param must resolve into the served shell — never another
// branch's value — because root params vary the document itself.
expect(firstResult.response.status).toBe(200)
expect(firstResult.static$('#lang-fallback').length).toBe(0)
expect(firstResult.static$('#lang').text()).toBe('fr')
expect(firstResult.static$('#slug').text()).toBe('two')
expect(firstResult.dynamicPart).toBe('')
// `slug` can never be provided by generateStaticParams, so the
// blocking render must not resolve it into the cached entry: it stays
// deferred in the shell and resumes per request — the same serving
// shape as the generated `en` branch below, except the first request
// blocks on creating the branch's entry instead of serving a
// build-time fallback.
expect(firstResult.static$('#slug-fallback').text()).toBe(
'loading slug...'
)
expect(firstResult.static$('#slug').length).toBe(0)
expect(firstResult.dynamicPart).toContain('<div id="slug">two</div>')
// A different slug on the same root branch is served from the same
// entry, with its own slug resumed.
const secondResult = await fetchSplitHTML('/fr/other')
expect(secondResult.response.status).toBe(200)
expect(secondResult.static$('#lang-fallback').length).toBe(0)
expect(secondResult.static$('#lang').text()).toBe('fr')
expect(secondResult.static$('#slug').text()).toBe('other')
expect(secondResult.dynamicPart).toBe('')
expect(secondResult.static$('#slug-fallback').text()).toBe(
'loading slug...'
)
expect(secondResult.static$('#slug').length).toBe(0)
expect(secondResult.dynamicPart).toContain('<div id="slug">other</div>')
})
}
......
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
// Contract tests for the allowQuery emitted for BLOCKING prerender entries
// (entries with no servable fallback). The fixture app has TWO root layouts:
//
// - `(standard)/` hosts routes below the root layout — no root params.
// - `with-root-param/[lang]/` hosts the root layout INSIDE [lang], making
// `lang` a ROOT param. Root params must be provided by every
// generateStaticParams result (the build enforces this), so `lang` is
// always prerenderable.
//
// The cache-key contract: a param may participate in allowQuery only if
// generateStaticParams can still complete it — root params (always covered)
// and partially-covered params qualify; params never returned by
// generateStaticParams do not. This applies to blocking entries the same as
// to fallback-backed entries: including a never-prerenderable param creates
// a cache entry per value and resolves the param into cached content.
//
// These assertions describe the desired output and are expected to fail
// until the adapter implements the key filtering for blocking entries (both
// the empty-shell downgrade case and the unresolved-root-param case).
describe('adapter-partial-fallback-blocking', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should exclude never-prerenderable params from allowQuery for blocking routes with empty shells', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const genericEmptyShellPrerender = outputs.prerenders.find(
(output) => output.pathname === '/empty-shell/[one]/[two]'
)
const genericEmptyShellDataPrerender = outputs.prerenders.find(
(output) => output.pathname === '/empty-shell/[one]/[two].rsc'
)
const genericEmptyShellSegmentPrerenders = outputs.prerenders.filter(
(output) =>
output.pathname.startsWith('/empty-shell/[one]/[two].segments/')
)
const generatedEmptyShellPrerender = outputs.prerenders.find(
(output) => output.pathname === '/empty-shell/a/[two]'
)
expect(genericEmptyShellPrerender).toBeDefined()
expect(genericEmptyShellDataPrerender).toBeDefined()
expect(genericEmptyShellSegmentPrerenders.length).toBeGreaterThan(0)
expect(generatedEmptyShellPrerender).toBeDefined()
// The generic route's empty build-time shell downgraded it to a blocking
// route (no servable fallback), but `two` is still never provided by
// generateStaticParams: an on-demand render must only complete `one`, so
// only `one` may be part of the cache key. Including `two` would create
// a cache entry per `two` value and resolve `two` into cached content.
expect(genericEmptyShellPrerender.config.allowQuery).toEqual(['nxtPone'])
expect(genericEmptyShellDataPrerender.config.allowQuery).toEqual([
'nxtPone',
])
for (const output of genericEmptyShellSegmentPrerenders) {
expect(output.config.allowQuery).toEqual(['nxtPone'])
}
// The generated route is already the most specific prerenderable shell
// (only the never-prerenderable `two` remains), so it stays a single
// shared entry.
expect(generatedEmptyShellPrerender.config.partialFallback).toBeUndefined()
expect(generatedEmptyShellPrerender.config.allowQuery).toEqual([])
})
it('should exclude never-prerenderable params from allowQuery for entries with a resolved root param', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const emptyShellPrerender = outputs.prerenders.find(
(output) =>
output.pathname === '/with-root-param/en/empty-shell/[category]/[id]'
)
const emptyShellDataPrerender = outputs.prerenders.find(
(output) =>
output.pathname ===
'/with-root-param/en/empty-shell/[category]/[id].rsc'
)
const nonEmptyShellPrerender = outputs.prerenders.find(
(output) =>
output.pathname ===
'/with-root-param/en/non-empty-shell/[category]/[id]'
)
const emptyShellLeafPrerender = outputs.prerenders.find(
(output) =>
output.pathname === '/with-root-param/en/empty-shell/shoes/[id]'
)
expect(emptyShellPrerender).toBeDefined()
expect(emptyShellDataPrerender).toBeDefined()
expect(nonEmptyShellPrerender).toBeDefined()
expect(emptyShellLeafPrerender).toBeDefined()
// With `lang` resolved at build time these entries behave exactly like
// the (standard) branch: the blocking (empty shell) entry must only key
// on `category`.
expect(emptyShellPrerender.config.allowQuery).toEqual(['nxtPcategory'])
expect(emptyShellDataPrerender.config.allowQuery).toEqual(['nxtPcategory'])
// The non-empty intermediate already works (regression guard).
expect(nonEmptyShellPrerender.config.allowQuery).toEqual(['nxtPcategory'])
expect(nonEmptyShellPrerender.config.partialFallback).toBe(true)
// The terminal shell stays a single shared entry.
expect(emptyShellLeafPrerender.config.allowQuery).toEqual([])
})
it('should exclude never-prerenderable params from allowQuery for entries with an unresolved root param', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const emptyShellBasePrerender = outputs.prerenders.find(
(output) =>
output.pathname ===
'/with-root-param/[lang]/empty-shell/[category]/[id]'
)
const emptyShellBaseDataPrerender = outputs.prerenders.find(
(output) =>
output.pathname ===
'/with-root-param/[lang]/empty-shell/[category]/[id].rsc'
)
const nonEmptyShellBasePrerender = outputs.prerenders.find(
(output) =>
output.pathname ===
'/with-root-param/[lang]/non-empty-shell/[category]/[id]'
)
expect(emptyShellBasePrerender).toBeDefined()
expect(emptyShellBaseDataPrerender).toBeDefined()
expect(nonEmptyShellBasePrerender).toBeDefined()
// An unresolved root param forces a blocking route, but that must not
// put `id` into the cache key: `lang` (root, always prerenderable) and
// `category` (prerenderable) form the key; `id` stays deferred.
expect(emptyShellBasePrerender.config.allowQuery).toEqual([
'nxtPlang',
'nxtPcategory',
])
expect(emptyShellBaseDataPrerender.config.allowQuery).toEqual([
'nxtPlang',
'nxtPcategory',
])
expect(nonEmptyShellBasePrerender.config.allowQuery).toEqual([
'nxtPlang',
'nxtPcategory',
])
})
})
// This route intentionally produces EMPTY build-time shells: the params are
// read outside of any Suspense boundary (and there is no loading.tsx), so the
// postpone propagates to the root. `instant = false` opts the route out of
// requiring an instant (non-empty) shell.
//
// The empty shells downgrade the generic route to a blocking route, but `two`
// is still never provided by `generateStaticParams`: an on-demand render may
// only complete `one`, so only `one` may participate in the cache key.
export function generateStaticParams() {
return [{ one: 'a' }]
}
export const instant = false
export default async function Page({
params,
}: {
params: Promise<{ one: string; two: string }>
}) {
const { one, two } = await params
return (
<div>
{one}:{two}
</div>
)
}
import { ReactNode } from 'react'
// Root layout for the (standard) branch: all params in this branch are
// below the root layout, so none of them are root params.
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// Empty-shell variant under a root param: the params are read outside of
// any Suspense boundary, so the postpone propagates to the root and every
// build-time shell is empty. `instant = false` opts the route out of
// requiring an instant (non-empty) shell.
//
// `generateStaticParams` provides `lang` in every entry (required for root
// params) and partially covers `category`; `id` is never provided, so `id`
// must never be resolved into a cached shell and must never be part of a
// cache key — including for requests whose `lang` value was not enumerated
// (e.g. /fr/...), which match the base route entry where `lang` is an
// unresolved root param.
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
}
export const instant = false
export default async function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
const { lang, category, id } = await params
// Per-render marker (prerenderable): must be re-rendered per request and
// never repeat across fetches — a repeated value proves a stored render
// is being replayed from the cache.
const renderedAt = performance.now()
return (
<div>
<div id="lang">{lang}</div>
<div id="category">{category}</div>
<div id="id">{id}</div>
<div id="rendered-at">{renderedAt}</div>
</div>
)
}
// The ROOT layout lives inside [lang], making `lang` a ROOT param: the
// document itself (the html tag) varies by lang with no Suspense boundary.
// Root params must be provided by every generateStaticParams result — the
// build enforces this — so `lang` is always a prerenderable param.
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ lang: string }>
}) {
const { lang } = await params
return (
<html lang={lang}>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
// Non-empty-shell variant under a root param: static page content plus
// Suspense boundaries around the non-root param reads, so shells contain
// static content and no empty-shell downgrade happens.
//
// `generateStaticParams` provides `lang` in every entry (required for root
// params) and partially covers `category`; `id` is never provided and must
// never resolve into a cached shell nor participate in a cache key.
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'en', category: 'shoes' }]
}
async function Id({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
// Per-render marker (prerenderable), read after `await params` so it
// belongs to the deferred region: it must be re-rendered (resumed) per
// request and never repeat across fetches.
const renderedAt = performance.now()
return (
<>
<div id="id">{id}</div>
<div id="rendered-at">{renderedAt}</div>
</>
)
}
export default function Page({
params,
}: {
params: Promise<{ lang: string; category: string; id: string }>
}) {
return (
<div>
<div id="static">static page content</div>
<Suspense
fallback={
<div id="id-fallback" data-fallback>
loading id...
</div>
}
>
<Id params={params} />
</Suspense>
</div>
)
}
import { Suspense, type ReactNode } from 'react'
// `category` is read in its own Suspense boundary: shells where it is
// concrete render it statically, and generic shells show
// `#category-fallback`. This makes the served shell's specialization
// observable from the static part of the response. (`lang` is a root param
// and is part of the document itself, rendered by the root layout.)
async function LayoutImpl({
children,
params,
}: {
children: ReactNode
params: Promise<{ category: string }>
}) {
const { category } = await params
return (
<div>
<div id="category">{category}</div>
{children}
</div>
)
}
export default function Layout(props: {
children: ReactNode
params: Promise<{ category: string }>
}) {
return (
<Suspense
fallback={
<div id="category-fallback" data-fallback>
loading category...
</div>
}
>
<LayoutImpl {...props} />
</Suspense>
)
}
import fs from 'fs/promises'
/** @type {import('next').NextAdapter } */
export default {
name: 'adapter-partial-fallback-blocking',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
// The resolved-root-param assertion covers the partial-fallback arm
// (intermediate shells emitting a filtered allowQuery +
// `partialFallback: true`), which the adapter only emits for apps with
// Partial Prefetching enabled (vercel/next.js#96074). The blocking-arm
// assertions are independent of this flag.
partialPrefetching: true,
adapterPath: require.resolve('./my-adapter.mjs'),
}
module.exports = nextConfig
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