Unverified Commit dfa7f4f7 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Attempt static prefetch before resorting to runtime (#96095)

If we're reasonably confident that a segment can be prefetched
statically without omitting data that would have been included during a
runtime prefetch (e.g. cookies), the client should attempt prefetch the
segment statically instead of going straight to a runtime request.

The decision for whether to do this is based on the
ShouldAttemptStaticPrefetch added in previous steps.

If it turns out the static response is not sufficient, then it will fall
back to a runtime request.

This makes prefetching cheaper for pages that are fully statically
renderable. We can make the optimization better in the future with more
reliable per-segment computation of the ShouldAttemptStaticPrefetch, but
the current approach should at least work for fully static pages, which
is what's most important.

This optimization applies during both the Shell phase and the
Speculative phase of the prefetching algorithm.
parent e70495c1
......@@ -545,14 +545,30 @@ export async function decodeStageUntilBoundary<T>(
byteLength: number,
headers: RequestHeaders | undefined
): Promise<T> {
// Buffer the truncated stream into a single chunk before passing it to
// Flight. This ensures all model data is available synchronously, which is
// required for readVaryParams to synchronously read the thenable status.
const { stream } = await createNonTaskyPrefetchResponseStream(
const { buffer } = await createNonTaskyPrefetchResponseStream(
responseBodyClone,
byteLength
)
return decodeBufferedStage<T>(buffer, headers)
}
/**
* Decodes already-buffered Flight response bytes as a stage payload. The
* bytes are delivered to Flight as a single chunk so all rows are processed
* synchronously in one call — required for the thenable-status reads that
* scope a response's late-resolving metadata (vary params, isPartial, ...)
* to this decode.
*/
export function decodeBufferedStage<T>(
buffer: Uint8Array,
headers: RequestHeaders | undefined
): Promise<T> {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(buffer)
controller.close()
},
})
return createFromNextReadableStream<T>(stream, headers, {
allowPartialStream: true,
})
......
......@@ -34,12 +34,26 @@ export const enum PrefetchPriority {
export const enum FetchStrategy {
// Deliberately ordered so we can easily compare two segments
// and determine if one segment is "more specific" than another
// (i.e. if it's likely that it contains more data)
// (i.e. if it's likely that it contains more data). See
// canNewFetchStrategyProvideMoreContent in cache.ts for what each tier can
// contain relative to the others.
//
// These numeric values are client-internal and never cross the wire — the
// `next-router-prefetch` request header values are mapped explicitly in
// fetchSegmentPrefetchesUsingDynamicRequest (cache.ts) — so the members can
// be renumbered freely as long as the relative order is preserved.
LoadingBoundary = 0,
RuntimeShell = 1,
PPR = 2,
PPRRuntime = 3,
Full = 4,
// The App Shell variant extracted from a static per-segment prefetch
// response: every segment's param-dependent content is reduced to pending
// references that render as the param fallback. Less complete than
// RuntimeShell — a static response can't include content that depends on
// session data (cookies, headers) — and less complete than PPR at concrete
// paths, which includes prerendered param-dependent content.
StaticShell = 1,
RuntimeShell = 2,
PPR = 3,
PPRRuntime = 4,
Full = 5,
}
/**
......
......@@ -299,11 +299,17 @@ export function getSegmentVaryPathForRequest(
// params that can be treated as Fallback. (Or perhaps the inverse.)
const originalVaryPath = tree.varyPath
if (fetchStrategy === FetchStrategy.RuntimeShell) {
// The Shell phase issues a runtime render with non-root params omitted. The
// resulting entry is reusable across all concrete values of those params, so
// we key it at the precomputed shell vary path (every non-root param
// substituted with Fallback; root params keep their concrete value).
if (
fetchStrategy === FetchStrategy.RuntimeShell ||
fetchStrategy === FetchStrategy.StaticShell
) {
// Both shell strategies produce the App Shell variant of a segment —
// RuntimeShell via a runtime render with non-root params omitted,
// StaticShell by truncating a static per-segment response at the shell
// byte boundary. Either way, the resulting entry is reusable across all
// concrete values of the non-root params, so we key it at the precomputed
// shell vary path (every non-root param substituted with Fallback; root
// params keep their concrete value).
return tree.shellVaryPath
}
......
......@@ -88,8 +88,9 @@ export type TreePrefetch = {
* walking the SegmentBundleNode linked list. The client's SegmentBundle
* linked list is constructed in the same order during scheduling, so the
* two are walked in parallel when the response arrives. A null element
* indicates a disabled segment (runtime prefetch or instant=false) that
* occupies a slot but carries no data.
* indicates a disabled segment (prefetch: 'force-disabled') that occupies a
* slot but carries no data. (Allow-runtime segments get real slots — the
* server emits static data for them unconditionally.)
*/
export type SegmentPrefetchResponse = {
buildId: string
......@@ -575,13 +576,6 @@ export async function collectPrefetchHints(
// Mutable accumulator: the first segment that accepts the head sets this
// to true. Once set, subsequent segments skip the check.
//
// When the route has any runtime prefetch segment, the head is only
// assigned to a runtime segment (since the runtime response already
// includes it). Static pages are skipped to avoid duplication.
const rootHints = flightRouterState[4] ?? 0
const subtreeHasRuntimePrefetch =
(rootHints & PrefetchHint.SubtreeHasRuntimePrefetch) !== 0
const headInlineState = { inlined: false }
// Walk the tree with the parent-first, child-decides algorithm.
......@@ -598,7 +592,6 @@ export async function collectPrefetchHints(
maxBundleSize,
headGzipSize,
headInlineState,
subtreeHasRuntimePrefetch,
rootVaryParamsIterable,
needsRuntimeRequest,
shellStageRelease
......@@ -657,7 +650,6 @@ async function collectPrefetchHintsImpl(
maxBundleSize: number,
headGzipSize: number,
headInlineState: { inlined: boolean },
routeHasRuntimePrefetch: boolean,
rootVaryParamsIterable: VaryParamsIterable | null,
needsRuntimeRequest: Promise<boolean>,
shellStageRelease: Promise<boolean>
......@@ -667,13 +659,18 @@ async function collectPrefetchHintsImpl(
// subtree. Used by ancestors for budget checks.
inlinedBytes: number
}> {
// Check if static prefetching is disabled for this segment (runtime
// prefetch or instant = false). Such segments act as transparent
// pass-throughs in the bundle chain: they contribute zero bytes of their
// own and pass parent data through to children. However, they cannot be
// the terminal of a chain — if no child accepts the parent data, the
// parent cannot be inlined into this segment because there's no static
// response to carry it. See the ParentInlinedIntoSelf check below.
// Check if static prefetching is disabled for this segment
// (prefetch: 'force-disabled' / instant = false). Such segments act as
// transparent pass-throughs in the bundle chain: they contribute zero
// bytes of their own and pass parent data through to children. However,
// they cannot be the terminal of a chain — if no child accepts the parent
// data, the parent cannot be inlined into this segment because there's no
// static response to carry it. See the ParentInlinedIntoSelf check below.
//
// Runtime-prefetch segments (prefetch: 'allow-runtime') are NOT disabled:
// they have static data — emitted unconditionally, so the client can
// attempt a static prefetch before deciding whether the runtime request is
// needed — and are measured and inlined like any other segment.
const isStaticPrefetchDisabled =
((route[4] ?? 0) & StaticPrefetchDisabled) !== 0
......@@ -764,7 +761,6 @@ async function collectPrefetchHintsImpl(
maxBundleSize,
headGzipSize,
headInlineState,
routeHasRuntimePrefetch,
rootVaryParamsIterable,
needsRuntimeRequest,
shellStageRelease
......@@ -813,39 +809,37 @@ async function collectPrefetchHintsImpl(
// Determine which segment is responsible for the head (metadata/viewport).
//
// When the route has any runtime prefetch segment, the head is only
// assigned to a runtime segment — the runtime response already includes
// the head, so assigning it to a static page would duplicate it.
//
// When the route has no runtime prefetch segments, the head is assigned
// to the first static page terminal that has budget room. Head can only
// be inlined into a page, not a layout, because pages may access
// additional params (e.g. searchParams) that layouts cannot.
// The head is assigned to the first page bundle terminal that has budget
// room; otherwise it's outlined as a standalone response (HeadOutlined,
// set by the caller). Head can only be inlined into a page, not a layout,
// because pages may access additional params (e.g. searchParams) that
// layouts cannot. It must be a bundle terminal because only bundle
// terminals emit a static response of their own (the head bundle is
// appended in collectSegmentDataImpl's standalone-task branch) —
// assigning the head to an inlined segment would leave it out of every
// static response.
//
// A disabled segment with PrefetchDisabled (instant = false) is never a
// valid target — it has no response at all.
const hasRuntimePrefetch =
((route[4] ?? 0) & PrefetchHint.HasRuntimePrefetch) !== 0
// A disabled segment (prefetch: 'force-disabled' / instant = false) is
// never a valid target — it has no response at all. A runtime-prefetch
// segment (prefetch: 'allow-runtime'), by contrast, DOES have a static
// response (see isStaticPrefetchDisabled above) and is an ordinary
// candidate. Runtime prefetching gets no special treatment here: whether
// the client will actually issue a runtime request can't be known at
// build time (a static prefetch attempt may prove sufficient and skip
// it), so the head must always be reachable through the static responses
// — inlined into one of them, or outlined.
const isBundleTerminal = !didInlineIntoChild && !isStaticPrefetchDisabled
const segment = route[0]
const isPageSegment =
typeof segment === 'string'
? segment === PAGE_SEGMENT_KEY
: segment[0] === PAGE_SEGMENT_KEY
if (!headInlineState.inlined) {
if (hasRuntimePrefetch) {
// Runtime prefetch segment — the runtime response includes the head.
// No budget cost since it's already part of that response.
if (!headInlineState.inlined && isBundleTerminal && isPageSegment) {
// The head counts against the bundle budget.
if (inlinedBytes + headGzipSize < maxBundleSize) {
hints |= PrefetchHint.HeadInlinedIntoSelf
inlinedBytes += headGzipSize
headInlineState.inlined = true
} else if (isBundleTerminal && isPageSegment && !routeHasRuntimePrefetch) {
// Static page terminal — only used when no runtime segments exist.
// The head counts against the bundle budget.
if (inlinedBytes + headGzipSize < maxBundleSize) {
hints |= PrefetchHint.HeadInlinedIntoSelf
inlinedBytes += headGzipSize
headInlineState.inlined = true
}
}
}
......@@ -1105,9 +1099,18 @@ function collectSegmentDataImpl(
// response as-is. Root params are forwarded separately, once per response.
const varyParams = seedData !== null ? seedData[4] : null
// If static prefetching is disabled for this segment (runtime prefetch or
// instant = false), it still participates in the bundle chain but with
// null data. The client will skip creating a cache entry for it.
// If static prefetching is disabled for this segment
// (prefetch: 'force-disabled' / instant = false), it still participates in
// the bundle chain but with null data. The client will skip creating a
// cache entry for it.
//
// Runtime-prefetch segments (prefetch: 'allow-runtime') are NOT disabled:
// their static data is emitted UNCONDITIONALLY — it can't be gated on the
// ShouldAttemptStaticPrefetch hint, because the client walks bundles
// positionally and the null-slot positions must be deterministic from
// build-time config alone. The client uses the data to attempt a static
// prefetch before deciding whether the segment's runtime request is
// actually needed.
const staticPrefetchDisabled = (prefetchHints & StaticPrefetchDisabled) !== 0
const rsc = seedData !== null && !staticPrefetchDisabled ? seedData[0] : null
......@@ -1284,9 +1287,9 @@ async function renderSegmentPrefetch(
while (node !== null) {
const elementRsc = node.rsc
if (elementRsc === null) {
// Static prefetching disabled (runtime prefetch or instant=false): a
// null placeholder keeps the array aligned with the client's bundle
// list, which skips a cache entry for the slot.
// Static prefetching disabled (prefetch: 'force-disabled'; allow-runtime
// segments carry real data): a null placeholder keeps the array aligned
// with the client's bundle list, which skips a cache entry for the slot.
data.push(null)
} else {
// We can determine if a segment contains only partial data if it takes
......
......@@ -125,7 +125,13 @@ async function createFlightRouterStateFromLoaderTreeImpl(
} else if (prefetchConfig === 'allow-runtime') {
// 'allow-runtime' participates in the two-phase (Shell then Speculative)
// prefetch flow, so it counts as Partial Prefetching. HasRuntimePrefetch
// additionally marks it as needing a runtime request pass.
// additionally marks the segment as requiring runtime completeness: the
// prefetch isn't done for this segment until an entry at least as
// complete as a runtime response exists. That doesn't disable static
// prefetching — the server emits static data for the segment
// unconditionally, and the scheduler may attempt a static prefetch first
// (per the ShouldAttemptStaticPrefetch hint), issuing the runtime
// request only if the static response proves insufficient.
prefetchHints |=
PrefetchHint.HasRuntimePrefetch |
PrefetchHint.SubtreeHasPartialPrefetching
......
......@@ -181,8 +181,16 @@ export type FlightRouterState = [
export type CompressedRefreshState = [url: string, renderedSearch: string]
export const enum PrefetchHint {
// This segment has a runtime prefetch enabled (via instant with
// prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.
// This segment has runtime prefetching enabled (prefetch: 'allow-runtime';
// no other config maps to this bit). Marks the segment as requiring
// RUNTIME COMPLETENESS: a prefetch isn't considered done for this segment
// until an entry at least as complete as a runtime response exists. It
// does NOT mean the segment lacks static data — the server emits static
// data for these segments unconditionally, and the scheduler may attempt a
// static prefetch first (per ShouldAttemptStaticPrefetch), issuing the
// runtime request only if the static response's own `needsRuntimeRequest`
// signal says it would return more. Per-segment only, does not propagate
// to ancestors.
HasRuntimePrefetch = 0b00001,
// This segment or one of its descendants opts into Partial Prefetching, i.e.
// uses the two-phase (Shell then Speculative) prefetch flow. Set when a
......@@ -218,8 +226,16 @@ export const enum PrefetchHint {
// re-fetched with correct hints. Only set during build-time prerendering,
// never at runtime.
InliningHintsStale = 0b1000000000,
// This segment has instant = false, opting out of all
// prefetching entirely (neither static nor runtime).
// This segment has prefetch = 'force-disabled'. The opt-out is passive
// and applies to this segment only: it never INITIATES a prefetch — no
// static data is emitted or fetched, and it's never the reason a runtime
// prefetch spawns — but it may ride along in a runtime response issued on
// another segment's behalf. Descendants prefetch normally.
//
// TODO: Also set as an internal fallback when the prefetch hints manifest
// is unavailable (see #91407 mitigations), which only means "no static
// prefetch data exists" — not a user opt-out. Split the fallback into its
// own bit so the two intents can diverge.
PrefetchDisabled = 0b10000000000,
// This segment or one of its descendants has runtime prefetch enabled
// (HasRuntimePrefetch). Propagates upward so the root reflects the
......@@ -262,16 +278,25 @@ export const enum PrefetchHint {
}
/**
* Bitmask for checking whether a segment's static prefetch is skipped. Matches
* if EITHER bit is set — i.e. the segment uses runtime prefetching
* (HasRuntimePrefetch) OR prefetching is disabled entirely (PrefetchDisabled,
* e.g. instant = false). The segment participates in the bundle chain
* but with null data.
* Bitmask for checking whether a segment's static prefetch is skipped — i.e.
* the server emits no static data for it (its slot in a segment bundle is
* null, and it participates in the bundle chain only as a pass-through) and
* the client never issues a static request for it.
*
* Static prefetching is disabled ONLY by `prefetch: 'force-disabled'`
* (PrefetchDisabled). Notably, `prefetch: 'allow-runtime'`
* (HasRuntimePrefetch) segments DO have static data: the server emits it
* unconditionally — it can't be gated on the
* ShouldAttemptStaticPrefetch hint, because null-slot positions in segment
* bundles must be deterministic from build-time config. HasRuntimePrefetch
* instead marks runtime completeness: a runtime request may still be needed
* for the segment, but the scheduler may attempt a static prefetch first
* (per the ShouldAttemptStaticPrefetch hint) and skip the runtime request if
* the static response proves sufficient.
*
* Usage: `(hints & StaticPrefetchDisabled) !== 0`
*/
export const StaticPrefetchDisabled =
PrefetchHint.HasRuntimePrefetch | PrefetchHint.PrefetchDisabled
export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled
/**
* The subset of PrefetchHint bits that propagate upward from a child segment to
......
......@@ -30,6 +30,11 @@ export default function Page() {
Runtime bailout
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/test-runtime-bailout" prefetch={true}>
Runtime bailout (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/test-stale-hints/nested/deep">
Stale hints
......
import { ReactNode, Suspense } from 'react'
// Small static layout. With prefetch inlining enabled, this layout's data
// should be bundled into the child's response. But since the child page uses
// runtime prefetching, the bundle needs to be flushed as a separate static
// prefetch instead.
// should be bundled into the child's response. The child page uses runtime
// prefetching (allow-runtime), but it still has a static response — the
// static parts that don't depend on runtime data — so the layout inlines
// into that bundle.
export default function RuntimeBailoutLayout({
children,
}: {
......
......@@ -6,9 +6,11 @@ import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: LinkProps['href']
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
......@@ -18,12 +20,30 @@ export function LinkAccordion({
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
data-prefetch={getPrefetchKind(prefetch)}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
function getPrefetchKind(prefetch: LinkProps['prefetch']) {
switch (prefetch) {
case false:
return 'disabled'
case undefined:
case null:
case 'auto':
return 'auto'
case true:
return 'true'
default:
prefetch satisfies never
}
}
import { Suspense } from 'react'
type Params = { slug: string }
// A fully static dynamic route: every param value is known via
// `generateStaticParams` and the page accesses no runtime data, so each URL
// is prerendered at build time and the route tree prefetch always carries
// the static-prefetch hint — the Shell phase attempts static per-segment
// prefetches for any URL of this route.
//
// The param-dependent content sits past the shell boundary of each
// prerender, so the App Shell — everything above it — is identical for every
// param value and is cached at a param-agnostic key. Prefetching ONE URL of
// the route therefore populates shell entries that are cache hits for every
// sibling URL: that cross-param reuse is what the consuming test pins.
export async function generateStaticParams() {
return [{ slug: 'one' }, { slug: 'two' }]
}
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<p id="page-content">Dynamic-param page shell text</p>
<Suspense fallback={<p id="slug-loading">Loading param content...</p>}>
<SlugContent params={params} />
</Suspense>
</main>
)
}
async function SlugContent({ params }: { params: Promise<Params> }) {
const { slug } = await params
return <p id="slug-content">{`Dynamic param content: ${slug}`}</p>
}
// A page that accesses no runtime data at all: no cookies, headers,
// searchParams, params, or `connection()`. Every prerender of this route is
// clean, so its route tree prefetch always carries the static-prefetch hint,
// and the static per-segment responses are always complete (a runtime
// request would return nothing more).
//
// Note the Shell phase is always permitted to issue a runtime shell request,
// so the absence of one in the test is attributable to the static shell
// attempt succeeding, not to configuration forbidding runtime requests.
export default function Page() {
return (
<main>
<p id="page-content">Fully static page content</p>
</main>
)
}
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>
<div>Root layout static text</div>
{children}
</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<h1>Home</h1>
<p>
Each link below points to a route that exercises a different combination
of the static-prefetch hint on the route tree and the per-segment
sufficiency signal. The links are hidden behind LinkAccordion checkboxes
so the tests control exactly when each prefetch fires.
</p>
<ul>
<li>
<LinkAccordion href="/fully-static">Fully static</LinkAccordion>
</li>
<li>
<LinkAccordion href="/uses-cookies">Uses cookies</LinkAccordion>
</li>
<li>
<LinkAccordion href="/uses-search-params?q=test">
Uses search params
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/uses-connection">Uses connection</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dynamic-param/one">
Dynamic param one
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dynamic-param/two">
Dynamic param two
</LinkAccordion>
</li>
{/* The speculative-* routes are allow-runtime (non-eager), so their
links use prefetch={true} to opt into the Speculative phase —
otherwise only their App Shell would be prefetched. */}
<li>
<LinkAccordion href="/speculative-static" prefetch={true}>
Speculative static
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/speculative-cookies" prefetch={true}>
Speculative cookies
</LinkAccordion>
</li>
</ul>
</main>
)
}
import { ReactNode } from 'react'
import { NoInline } from '../../components/no-inline'
// A static layout inflated past the inlining size threshold so it stays
// OUTLINED — it gets its own standalone static response instead of being
// bundled into the page's. Without it, this route's small intermediate
// segments would be bundled into the allow-runtime page's static response,
// and fetching THEM statically would deliver the page's content along for
// the ride — which would make the consuming test's "the page content must
// not arrive in any static response" rejection indistinguishable from a
// genuine static prefetch attempt of the page. Keeping the page's static
// response to itself preserves what that rejection pins: with the hint
// unset, the page segment is never statically prefetched.
export default function Layout({ children }: { children: ReactNode }) {
return (
<div>
<NoInline />
{children}
</div>
)
}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
// The Speculative-phase counterpart of app/uses-cookies/page.tsx: the page
// reads cookies directly in the shell stage of every prerender, so the
// route tree prefetch never carries the static-prefetch hint. With
// RUNTIME prefetching enabled (`allow-runtime`) the page segment requires
// runtime-completeness during the Speculative phase (which the consuming
// test enters via a `prefetch={true}` link), and with the hint unset the
// scheduler skips the static attempt entirely and issues the runtime
// prefetch directly. Unlike the uses-cookies fixture, the runtime prefetch
// of an allow-runtime segment RESOLVES the cookies() read, so the
// cookie-derived content itself arrives in the runtime response.
export const prefetch = 'allow-runtime'
async function CookieContent() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return (
<div id="speculative-cookie-content">{`Speculative-cookies cookie: ${value}`}</div>
)
}
export default function Page() {
return (
<main>
<p id="page-content">Speculative-cookies page shell text</p>
<Suspense
fallback={
<p id="speculative-cookie-loading">Loading speculative cookie...</p>
}
>
<CookieContent />
</Suspense>
</main>
)
}
// The Speculative-phase counterpart of app/fully-static/page.tsx: a page
// that accesses no runtime data at all, but opts into RUNTIME prefetching
// (`allow-runtime`). Such a segment requires runtime-completeness in every
// phase, and the Speculative phase only processes it when a link opts in
// (the consuming test uses `prefetch={true}`; non-eager routes are otherwise
// shell-only by design).
//
// Every prerender of this route is clean, so the route tree prefetch always
// carries the static-prefetch hint: the Speculative phase attempts a static
// prefetch of this segment instead of going straight to a runtime one. The
// static responses are always complete (a runtime request would return
// nothing more), so the attempt is sufficient and no runtime request fires
// at all — even though the segment is configured for runtime prefetching.
// (Note this relies on the server emitting static data for allow-runtime
// segments, which it now does unconditionally.)
export const prefetch = 'allow-runtime'
export default function Page() {
return (
<main>
<p id="page-content">Speculative-static page content</p>
</main>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
// A page whose only non-static data source is `connection()`. Unlike cookies
// or searchParams, `connection()` is *dynamic* data: it hangs during runtime
// prerenders too, and its hole can only be filled by the navigation-time
// dynamic request. It is therefore NOT recorded as a runtime-data access:
// the route tree prefetch carries the static-prefetch hint, and the static
// per-segment response — although partial — is sufficient (a runtime
// prefetch would have the exact same hole), so no runtime fallback should
// fire.
async function DynamicContent() {
await connection()
return <div id="connection-content">Connection content</div>
}
export default function Page() {
return (
<main>
<p id="page-content">Connection page shell text</p>
<Suspense
fallback={<p id="connection-loading">Loading connection content...</p>}
>
<DynamicContent />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
import { cookies } from 'next/headers'
// A page that reads cookies directly in the shell: every prerender records a
// runtime-data access during its shell stage, so the route tree prefetch
// never carries the static-prefetch hint. The client should go straight to a
// runtime shell prefetch without attempting a static one.
async function CookieContent() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return <div id="cookie-content">{`Cookie value: ${value}`}</div>
}
export default function Page() {
return (
<main>
<p id="page-content">Cookies page shell text</p>
<Suspense fallback={<p id="cookie-loading">Loading cookie...</p>}>
<CookieContent />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
// A page that observes its searchParams: like cookies, search params hang
// during a static prerender but resolve during a runtime one, so observing
// them is recorded as a runtime-data access in the shell stage of every
// prerender. The route tree prefetch never carries the static-prefetch hint
// and the client should go straight to a runtime shell prefetch without
// attempting a static one.
async function SearchContent({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
const { q } = await searchParams
return <div id="search-content">{`Query: ${q ?? 'none'}`}</div>
}
export default function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
return (
<main>
<p id="page-content">Search params page shell text</p>
<Suspense fallback={<p id="search-loading">Loading query...</p>}>
<SearchContent searchParams={searchParams} />
</Suspense>
</main>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
'use cache'
import { gzipSync } from 'zlib'
import { randomBytes } from 'crypto'
// Default size is 2 KB, the threshold used by Next to decide whether to inline
// a segment into the route tree prefetch.
export async function NoInline({ size = 2048 }: { size?: number }) {
let content = ''
let compressedLength = 0
let iterations = 0
while (compressedLength < size) {
const chunk =
iterations % 2 === 0
? '**Arbitrary hidden content to prevent this component from being inlined** '
: randomBytes(128).toString('base64') + ' '
content += chunk
compressedLength = gzipSync(content).length
iterations++
if (iterations > 10000) break
}
return <div style={{ display: 'none' }}>{content}</div>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// Opt every route into Partial Prefetching globally: segments without a
// per-segment `prefetch` export default to 'partial'. The speculative-*
// fixtures override this with `prefetch = 'allow-runtime'`.
partialPrefetching: true,
}
export default nextConfig
......@@ -751,14 +751,20 @@ describe('segment cache - vary params', () => {
{ includes: 'Page category:' }
)
// Second prefetch: same category, different itemId.
// The page segment is a cache hit since it only varies on category.
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-layout-split/electronics/tablet"]'
)
await toggle.click()
}, 'no-requests')
// Second prefetch: same category, different itemId. The page segment is a
// cache hit (it only varies on category), but the layout varies on itemId
// too, so it's a genuine miss and a runtime request is required for it.
// The page segment is not itself part of that batch — it rides along
// because rendering a segment on the server also renders its children.
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-layout-split/electronics/tablet"]'
)
await toggle.click()
},
{ includes: 'Layout: electronics/tablet' }
)
// Different category triggers a new page segment fetch
await act(
......
This diff is collapsed.
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