Unverified Commit 0e6ab3f5 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Prefetch Inlining] Generate size-based hints on server (#90891)

Part 1 of 2. This commit adds the server-side infrastructure for
size-based segment bundling but does not change any observable behavior.
The client-side changes that actually consume bundled responses are in
the next commit.

At build time, a measurement pass renders each segment's prefetch
response, measures its gzip size, and decides which segments should be
bundled together vs fetched separately. The decisions are persisted to a
manifest and embedded into the route tree prefetch response so the
client can act on them.

The decisions are computed once at build and remain fixed for the
lifetime of the deployment. They are not recomputed during
ISR/revalidation — if they could change, the client would need to
re-fetch the route tree after every revalidation, defeating the purpose
of caching it independently.

Refer to the next commit for a full description of the design and
motivation.

## Config

experimental.prefetchInlining accepts either a boolean or an object with
threshold overrides (maxSize, maxBundleSize). When true, the default
thresholds are used (2KB per-segment, 10KB total budget). The auto
behavior will eventually become the default. The config will remain
available for overriding thresholds.
parent 834c41ef
......@@ -7,6 +7,7 @@ import type {
import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin'
import type { CacheControl, Revalidate } from '../server/lib/cache-control'
import type { PrefetchHints } from '../shared/lib/app-router-types'
import '../lib/setup-exception-listeners'
......@@ -61,6 +62,7 @@ import {
IMAGES_MANIFEST,
PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD,
PREFETCH_HINTS,
PRERENDER_MANIFEST,
REACT_LOADABLE_MANIFEST,
ROUTES_MANIFEST,
......@@ -1853,6 +1855,7 @@ export default async function build(
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json'
),
path.join(SERVER_DIRECTORY, PREFETCH_HINTS),
]
: []),
...(pagesDir && bundler !== Bundler.Turbopack
......@@ -2739,6 +2742,11 @@ export default async function build(
preview: previewProps,
}
// Accumulate per-route segment inlining decisions for
// prefetch-hints.json. First-writer-wins: if multiple param
// combinations exist for the same route pattern, use the first one.
const prefetchHints: Record<string, PrefetchHints> = {}
const tbdPrerenderRoutes: string[] = []
const { i18n } = config
......@@ -3194,6 +3202,11 @@ export default async function build(
initialCacheControl: cacheControl,
})
// Collect prefetch hints (first-writer-wins per page)
if (metadata.prefetchHints && !(page in prefetchHints)) {
prefetchHints[page] = metadata.prefetchHints
}
if (cacheControl.revalidate !== 0) {
const normalizedRoute = normalizePagePath(route.pathname)
......@@ -3369,6 +3382,11 @@ export default async function build(
builtSegmentDataRoute
)
}
// Collect prefetch hints (first-writer-wins per page)
if (metadata?.prefetchHints && !(page in prefetchHints)) {
prefetchHints[page] = metadata.prefetchHints
}
}
pageInfos.set(route.pathname, {
......@@ -3958,6 +3976,10 @@ export default async function build(
config.experimental.allowedRevalidateHeaderKeys
await writePrerenderManifest(distDir, prerenderManifest)
await writeManifest(
path.join(distDir, SERVER_DIRECTORY, PREFETCH_HINTS),
prefetchHints
)
await writeClientSsgManifest(prerenderManifest, {
distDir,
buildId,
......
......@@ -738,7 +738,7 @@ export async function handler(
nextConfig.experimental.optimisticRouting
),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining),
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
cachedNavigations: Boolean(
nextConfig.experimental.cachedNavigations
......
......@@ -163,7 +163,7 @@ async function requestHandler(
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining),
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
cachedNavigations: Boolean(nextConfig.experimental.cachedNavigations),
clientTraceMetadata:
......
......@@ -69,6 +69,13 @@ export function createInitialRouterState({
// NOTE: The metadataVaryPath isn't used for anything currently because the
// head is embedded into the CacheNode tree, but eventually we'll lift it out
// and store it on the top-level state object.
//
// TODO: For statically-generated-at-build-time HTML pages, the
// FlightRouterState baked into the initial RSC payload won't have the
// correct segment inlining hints (ParentInlinedIntoSelf, InlinedIntoChild)
// because those are computed after the pre-render. The client will need to
// fetch the correct hints from the route tree prefetch (/_tree) response
// before acting on inlining decisions.
const acc = { metadataVaryPath: null }
const initialRouteTree = convertRootFlightRouterStateToRouteTree(
initialTree,
......
......@@ -100,6 +100,7 @@ export async function exportAppPage(
fetchTags,
fetchMetrics,
segmentData,
prefetchHints,
renderResumeDataCache,
} = metadata
......@@ -218,6 +219,7 @@ export async function exportAppPage(
headers,
postponed,
segmentPaths,
prefetchHints,
}
fileWriter.append(
......@@ -231,6 +233,7 @@ export async function exportAppPage(
? meta
: {
segmentPaths: meta.segmentPaths,
prefetchHints: meta.prefetchHints,
},
hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed),
......
import type { OutgoingHttpHeaders } from 'node:http'
import type { PrefetchHints } from '../../shared/lib/app-router-types'
export type RouteMetadata = {
status: number | undefined
headers: OutgoingHttpHeaders | undefined
postponed: string | undefined
segmentPaths: Array<string> | undefined
prefetchHints: PrefetchHints | undefined
}
......@@ -11,6 +11,7 @@ import type {
FlightData,
InitialRSCPayload,
FlightDataPath,
PrefetchHints,
} from '../../shared/lib/app-router-types'
import type { Readable } from 'node:stream'
import {
......@@ -618,6 +619,7 @@ async function generateDynamicRSCPayload(
rootLayoutIncluded: false,
preloadCallbacks,
MetadataOutlet,
hintTree: ctx.renderOpts.prefetchHints?.[ctx.pagePath] ?? null,
})
).map((path) => path.slice(1)) // remove the '' (root) segment
}
......@@ -1667,8 +1669,10 @@ async function getRSCPayload(
workStore,
} = ctx
const hints = ctx.renderOpts.prefetchHints?.[ctx.pagePath] ?? null
const initialTree = await createFlightRouterStateFromLoaderTree(
tree,
hints,
getDynamicParamFromSegment,
query
)
......@@ -1848,8 +1852,10 @@ async function getErrorRSCPayload(
createElement(Metadata, null)
)
const errorHints = ctx.renderOpts.prefetchHints?.[ctx.pagePath] ?? null
const initialTree = await createFlightRouterStateFromLoaderTree(
tree,
errorHints,
getDynamicParamFromSegment,
query
)
......@@ -6320,11 +6326,13 @@ async function prerenderToStream(
? metadata.flightData.subarray(1)
: metadata.flightData
metadata.segmentData = await collectSegmentData(
await collectSegmentData(
flightData,
finalServerPrerenderStore,
ComponentMod,
renderOpts
renderOpts,
ctx.pagePath,
metadata
)
if (serverIsDynamic) {
......@@ -6574,11 +6582,13 @@ async function prerenderToStream(
if (shouldGenerateStaticFlightData(workStore)) {
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
await collectSegmentData(
flightData,
ssrPrerenderStore,
ComponentMod,
renderOpts
renderOpts,
ctx.pagePath,
metadata
)
}
......@@ -6783,11 +6793,13 @@ async function prerenderToStream(
if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer(reactServerResult.asStream())
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
await collectSegmentData(
flightData,
prerenderLegacyStore,
ComponentMod,
renderOpts
renderOpts,
ctx.pagePath,
metadata
)
}
......@@ -6951,11 +6963,13 @@ async function prerenderToStream(
reactServerPrerenderResult.asStream()
)
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
await collectSegmentData(
flightData,
prerenderLegacyStore,
ComponentMod,
renderOpts
renderOpts,
ctx.pagePath,
metadata
)
}
......@@ -7075,8 +7089,10 @@ async function collectSegmentData(
fullPageDataBuffer: Buffer,
prerenderStore: PrerenderStore,
ComponentMod: AppPageModule,
renderOpts: RenderOpts
): Promise<Map<string, Buffer> | undefined> {
renderOpts: RenderOpts,
pagePath: string,
metadata: AppPageRenderResultMetadata
): Promise<void> {
// Per-segment prefetch data
//
// All of the segments for a page are generated simultaneously, including
......@@ -7107,13 +7123,45 @@ async function collectSegmentData(
const selectStaleTime = createSelectStaleTime(renderOpts.experimental)
const staleTime = selectStaleTime(prerenderStore.stale)
return await ComponentMod.collectSegmentData(
// Resolve prefetch hints. At runtime (next start / ISR), the precomputed
// hints are already loaded from the prefetch-hints.json manifest. During
// build, compute them by measuring segment gzip sizes and write them to
// metadata so the build pipeline can persist them to the manifest.
let hints: PrefetchHints | null
const prefetchInlining = renderOpts.experimental.prefetchInlining
if (!prefetchInlining) {
hints = null
} else if (renderOpts.isBuildTimePrerendering) {
// Build time: compute fresh hints and store in metadata for the manifest.
hints = await ComponentMod.collectPrefetchHints(
fullPageDataBuffer,
staleTime,
clientModules,
serverConsumerManifest,
prefetchInlining.maxSize,
prefetchInlining.maxBundleSize
)
metadata.prefetchHints = hints
} else {
// Runtime: use hints from the manifest. Never compute fresh hints
// during ISR/revalidation.
hints = renderOpts.prefetchHints?.[pagePath] ?? null
}
// Pass the resolved hints so collectSegmentData can union them into
// the TreePrefetch. During the initial build the FlightRouterState in
// the buffer doesn't have inlining hints yet (they were just computed
// above), so we need to merge them in here. At runtime/ISR the hints
// are already embedded in the FlightRouterState, so this is null.
metadata.segmentData = await ComponentMod.collectSegmentData(
renderOpts.cacheComponents,
fullPageDataBuffer,
staleTime,
clientModules,
serverConsumerManifest,
renderOpts.experimental.prefetchInlining
Boolean(renderOpts.experimental.prefetchInlining),
hints
)
}
......
......@@ -5,7 +5,9 @@ import type {
InitialRSCPayload,
DynamicParamTypesShort,
HeadData,
PrefetchHints,
} from '../../shared/lib/app-router-types'
import { PrefetchHint } from '../../shared/lib/app-router-types'
import { readVaryParams } from '../../shared/lib/segment-cache/vary-params-decoding'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import type { ManifestNode } from '../../build/webpack/plugins/flight-manifest-plugin'
......@@ -93,9 +95,8 @@ export type SegmentPrefetch = {
* slots so all segments for a route can be bundled into a single response.
*
* This is a separate type from SegmentPrefetch because the inlined flow is
* temporary — eventually inlining will be the default behavior (controlled by
* a size heuristic rather than a boolean flag), and the per-segment and inlined
* paths will merge.
* still gated behind a feature flag. Eventually inlining will always be
* enabled, and the per-segment and inlined paths will merge.
*/
export type InlinedSegmentPrefetch = {
segment: SegmentPrefetch
......@@ -141,13 +142,42 @@ function onSegmentPrerenderError(error: unknown) {
}
}
/**
* Extract the FlightRouterState, seed data, and head from a prerendered
* InitialRSCPayload. Returns null if the payload doesn't match the expected
* shape (single path with 3 elements).
*/
function extractFlightData(initialRSCPayload: InitialRSCPayload): {
buildId: string | undefined
flightRouterState: FlightRouterState
seedData: CacheNodeSeedData
head: HeadData
} | null {
const flightDataPaths = initialRSCPayload.f
// FlightDataPath is an unsound type, hence the additional checks.
if (flightDataPaths.length !== 1 && flightDataPaths[0].length !== 3) {
console.error(
'Internal Next.js error: InitialRSCPayload does not match the expected ' +
'shape for a prerendered page during segment prefetch generation.'
)
return null
}
return {
buildId: initialRSCPayload.b,
flightRouterState: flightDataPaths[0][0],
seedData: flightDataPaths[0][1],
head: flightDataPaths[0][2],
}
}
export async function collectSegmentData(
isCacheComponentsEnabled: boolean,
fullPageDataBuffer: Buffer,
staleTime: number,
clientModules: ManifestNode,
serverConsumerManifest: any,
prefetchInlining: boolean
prefetchInlining: boolean,
hints: PrefetchHints | null
): Promise<Map<SegmentRequestKey, Buffer>> {
// Traverse the router tree and generate a prefetch response for each segment.
......@@ -196,6 +226,7 @@ export async function collectSegmentData(
segmentTasks={segmentTasks}
onCompletedProcessingRouteTree={onCompletedProcessingRouteTree}
prefetchInlining={prefetchInlining}
hints={hints}
/>,
clientModules,
{
......@@ -222,6 +253,311 @@ export async function collectSegmentData(
return resultMap
}
/**
* Compute prefetch hints for a route by measuring segment sizes and deciding
* which segments should be inlined. Only runs at build time. The results are
* written to prefetch-hints.json and loaded at server startup.
*
* This is a separate pass from collectSegmentData so that the inlining
* decisions can be fed back into collectSegmentData to control which segments
* are output as separate entries vs. inlined into their parent.
*/
export async function collectPrefetchHints(
fullPageDataBuffer: Buffer,
staleTime: number,
clientModules: ManifestNode,
serverConsumerManifest: any,
maxSize: number,
maxBundleSize: number
): Promise<PrefetchHints> {
// Warm up the module cache, same as collectSegmentData.
try {
await createFromReadableStream(streamFromBuffer(fullPageDataBuffer), {
findSourceMapURL,
serverConsumerManifest,
})
await waitAtLeastOneReactRenderTask()
} catch {}
// Decode the Flight data to walk the route tree.
const initialRSCPayload: InitialRSCPayload = await createFromReadableStream(
createUnclosingPrefetchStream(streamFromBuffer(fullPageDataBuffer)),
{
findSourceMapURL,
serverConsumerManifest,
}
)
const flightData = extractFlightData(initialRSCPayload)
if (flightData === null) {
return { hints: 0, slots: null }
}
const { buildId, flightRouterState, seedData, head } = flightData
// Measure the head (metadata/viewport) gzip size so the main traversal
// can decide whether to inline it into a page's bundle.
const headVaryParamsThenable = initialRSCPayload.h
const headVaryParams =
headVaryParamsThenable !== null
? readVaryParams(headVaryParamsThenable)
: null
const [, headBuffer] = await renderSegmentPrefetch(
buildId,
staleTime,
head,
HEAD_REQUEST_KEY,
headVaryParams,
clientModules
)
const headGzipSize = await getGzipSize(headBuffer)
// Mutable accumulator: the first page leaf that can fit the head sets
// this to true. Once set, subsequent leaves skip the check.
const headInlineState = { inlined: false }
// Walk the tree with the parent-first, child-decides algorithm.
const { node } = await collectPrefetchHintsImpl(
flightRouterState,
buildId,
staleTime,
seedData,
clientModules,
ROOT_SEGMENT_REQUEST_KEY,
null, // root has no parent to inline
maxSize,
maxBundleSize,
headGzipSize,
headInlineState
)
if (!headInlineState.inlined) {
// No page could accept the head. Set HeadOutlined on the root so the
// client knows to fetch the head separately.
node.hints |= PrefetchHint.HeadOutlined
}
return node
}
// Measure a segment's gzip size and decide whether it should be inlined.
//
// These hints are computed once during build and never change for the
// lifetime of that deployment. The client can assume that hints delivered as
// part of one request will be the same during a subsequent request, given
// the same build ID. There's no skew to worry about as long as the build
// itself is consistent.
//
// In the Segment Cache, we split page prefetches into multiple requests so
// that each one can be cached and deduped independently. However, some
// segments are small enough that the potential caching benefits are not worth
// the additional network overhead. For these, we inline a parent's data into
// one of its children's responses, avoiding a separate request. The parent
// is inlined into the child (not the other way around) because the parent's
// response is more likely to be shared across multiple pages. The child's
// response is already page-specific, so adding the parent's data there
// doesn't meaningfully reduce deduplication. It's similar to how JS bundlers
// decide whether to inline a module into a chunk.
//
// The algorithm is parent-first, child-decides: the parent measures itself
// and passes its gzip size down. Each child decides whether to accept. A
// child rejects if the parent exceeds maxSize or if accepting would push
// the cumulative inlined bytes past maxBundleSize. This produces
// both ParentInlinedIntoSelf (on the child) and InlinedIntoChild (on the
// parent) in a single pass.
async function collectPrefetchHintsImpl(
route: FlightRouterState,
buildId: string | undefined,
staleTime: number,
seedData: CacheNodeSeedData | null,
clientModules: ManifestNode,
// TODO: Consider persisting the computed requestKey into the hints output
// so it doesn't need to be recomputed during the build. This might also
// suggest renaming prefetch-hints.json to something like
// segment-manifest.json, since it would contain more than just hints.
requestKey: SegmentRequestKey,
parentGzipSize: number | null,
maxSize: number,
maxBundleSize: number,
headGzipSize: number,
headInlineState: { inlined: boolean }
): Promise<{
node: PrefetchHints
// Total inlined bytes accumulated along the deepest accepting path in this
// subtree. Used by ancestors for budget checks.
inlinedBytes: number
}> {
// Render current segment and measure its gzip size.
let currentGzipSize: number | null = null
if (seedData !== null) {
const varyParamsThenable = seedData[4]
const varyParams =
varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null
const [, buffer] = await renderSegmentPrefetch(
buildId,
staleTime,
seedData[0],
requestKey,
varyParams,
clientModules
)
currentGzipSize = await getGzipSize(buffer)
}
// Only offer this segment to its children for inlining if its gzip size
// is below maxSize. Segments above this get their own response.
const sizeToInline =
currentGzipSize !== null && currentGzipSize < maxSize
? currentGzipSize
: null
// Process children serially (not in parallel) to ensure deterministic
// results. Since this only runs at build time and the rendering is just
// re-encoding cached prerenders, this won't impact build times. Each child
// receives our gzip size and decides whether to inline us. Once a child
// accepts, we stop offering to remaining siblings — the parent is only
// inlined into one child. In parallel routes, this avoids duplicating the
// parent's data across multiple sibling responses.
const children = route[1]
const seedDataChildren = seedData !== null ? seedData[1] : null
let slots: Record<string, PrefetchHints> | null = null
let didInlineIntoChild = false
let acceptingChildInlinedBytes = 0
// Track the smallest inlinedBytes across all children so we know how much
// budget remains along the best path. When our own parent asks whether we
// can accept its data, the parent's bytes would flow through to the child
// with the most remaining headroom.
let smallestChildInlinedBytes = Infinity
let hasChildren = false
for (const parallelRouteKey in children) {
hasChildren = true
const childRoute = children[parallelRouteKey]
const childSegment = childRoute[0]
const childSeedData =
seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null
const childRequestKey = appendSegmentRequestKeyPart(
requestKey,
parallelRouteKey,
createSegmentRequestKeyPart(childSegment)
)
const childResult = await collectPrefetchHintsImpl(
childRoute,
buildId,
staleTime,
childSeedData,
clientModules,
childRequestKey,
// Once a child has accepted us, stop offering to remaining siblings.
didInlineIntoChild ? null : sizeToInline,
maxSize,
maxBundleSize,
headGzipSize,
headInlineState
)
if (slots === null) {
slots = {}
}
slots[parallelRouteKey] = childResult.node
if (childResult.node.hints & PrefetchHint.ParentInlinedIntoSelf) {
// This child accepted our data — it will include our segment's
// response in its own. No need to track headroom anymore since
// we already know which child we're inlined into.
didInlineIntoChild = true
acceptingChildInlinedBytes = childResult.inlinedBytes
} else if (!didInlineIntoChild) {
// Track the child with the most remaining headroom. Used below
// when deciding whether to accept our own parent's data.
if (childResult.inlinedBytes < smallestChildInlinedBytes) {
smallestChildInlinedBytes = childResult.inlinedBytes
}
}
}
// Leaf segment: no children have consumed any budget yet.
if (!hasChildren) {
smallestChildInlinedBytes = 0
}
// Mark this segment as InlinedIntoChild if one of its children accepted.
// This means this segment doesn't need its own prefetch response — its
// data is included in the accepting child's response instead.
let hints = 0
if (didInlineIntoChild) {
hints |= PrefetchHint.InlinedIntoChild
}
// inlinedBytes represents the total gzipped bytes of parent data inlined
// into the deepest "inlining target" along this branch. It starts at 0 at
// the leaves and grows as parents are inlined going back up the tree. If a
// child accepted us, our size is already counted in that child's value.
let inlinedBytes = didInlineIntoChild
? acceptingChildInlinedBytes
: smallestChildInlinedBytes
// At leaf nodes (pages), try to inline the head (metadata/viewport) into
// this page's response. The head is treated like an additional inlined
// entry — it counts against the same total budget. Only the first page
// that has room gets the head; subsequent pages skip via the shared
// headInlineState accumulator.
if (!hasChildren && !headInlineState.inlined) {
if (inlinedBytes + headGzipSize < maxBundleSize) {
hints |= PrefetchHint.HeadInlinedIntoSelf
inlinedBytes += headGzipSize
headInlineState.inlined = true
}
}
// Decide whether to accept our own parent's data. Two conditions:
//
// 1. The parent offered us a size (parentGzipSize is not null). It's null
// when the parent is too large to inline or when this is the root.
//
// 2. The total inlined bytes along this branch wouldn't exceed the budget.
// Even if each segment is individually small, at some point it no
// longer makes sense to keep adding bytes because the combined response
// is unique per URL and can't be deduped.
//
// A node can be both InlinedIntoChild and ParentInlinedIntoSelf. This
// happens in multi-level chains: GP → P → C where all are small. C
// accepts P (P is InlinedIntoChild), then P also accepts GP (P is
// ParentInlinedIntoSelf). The result: C's response includes both P's
// and GP's data. The parent's data flows through to the deepest
// accepting descendant.
if (parentGzipSize !== null) {
if (inlinedBytes + parentGzipSize < maxBundleSize) {
hints |= PrefetchHint.ParentInlinedIntoSelf
inlinedBytes += parentGzipSize
}
}
return {
node: { hints, slots },
inlinedBytes,
}
}
// We use gzip size rather than raw size because it better reflects the actual
// transfer cost. The inlining trade-off is about whether the overhead of an
// additional HTTP request (connection setup, headers, round trip) is worth
// the deduplication benefit of keeping a segment separate. Below some
// compressed size, the request overhead dominates and inlining is better.
// Above it, the deduplication benefit of a cacheable standalone response
// wins out.
async function getGzipSize(buffer: Buffer): Promise<number> {
const stream = new Blob([new Uint8Array(buffer)])
.stream()
.pipeThrough(new CompressionStream('gzip'))
const compressedBlob = await new Response(stream).blob()
return compressedBlob.size
}
async function PrefetchTreeData({
isClientParamParsingEnabled,
fullPageDataBuffer,
......@@ -231,6 +567,7 @@ async function PrefetchTreeData({
segmentTasks,
onCompletedProcessingRouteTree,
prefetchInlining,
hints,
}: {
isClientParamParsingEnabled: boolean
fullPageDataBuffer: Buffer
......@@ -240,6 +577,7 @@ async function PrefetchTreeData({
segmentTasks: Array<Promise<[SegmentRequestKey, Buffer]>>
onCompletedProcessingRouteTree: () => void
prefetchInlining: boolean
hints: PrefetchHints | null
}): Promise<RootTreePrefetch | null> {
// We're currently rendering a Flight response for the route tree prefetch.
// Inside this component, decode the Flight stream for the whole page. This is
......@@ -254,20 +592,11 @@ async function PrefetchTreeData({
}
)
const buildId = initialRSCPayload.b
// FlightDataPath is an unsound type, hence the additional checks.
const flightDataPaths = initialRSCPayload.f
if (flightDataPaths.length !== 1 && flightDataPaths[0].length !== 3) {
console.error(
'Internal Next.js error: InitialRSCPayload does not match the expected ' +
'shape for a prerendered page during segment prefetch generation.'
)
const flightData = extractFlightData(initialRSCPayload)
if (flightData === null) {
return null
}
const flightRouterState: FlightRouterState = flightDataPaths[0][0]
const seedData: CacheNodeSeedData = flightDataPaths[0][1]
const head: HeadData = flightDataPaths[0][2]
const { buildId, flightRouterState, seedData, head } = flightData
// Extract the head vary params from the decoded response.
// The head vary params thenable should be fulfilled by now; if not, treat
......@@ -291,7 +620,8 @@ async function PrefetchTreeData({
clientModules,
ROOT_SEGMENT_REQUEST_KEY,
segmentTasks,
prefetchInlining
prefetchInlining,
hints
)
if (prefetchInlining) {
......@@ -355,7 +685,8 @@ function collectSegmentDataImpl(
clientModules: ManifestNode,
requestKey: SegmentRequestKey,
segmentTasks: Array<Promise<[string, Buffer]>>,
prefetchInlining: boolean
prefetchInlining: boolean,
hintTree: PrefetchHints | null
): TreePrefetch {
// Metadata about the segment. Sent as part of the tree prefetch. Null if
// there are no children.
......@@ -374,6 +705,10 @@ function collectSegmentDataImpl(
parallelRouteKey,
createSegmentRequestKeyPart(childSegment)
)
const childHintTree =
hintTree !== null && hintTree.slots !== null
? (hintTree.slots[parallelRouteKey] ?? null)
: null
const childTree = collectSegmentDataImpl(
isClientParamParsingEnabled,
childRoute,
......@@ -383,7 +718,8 @@ function collectSegmentDataImpl(
clientModules,
childRequestKey,
segmentTasks,
prefetchInlining
prefetchInlining,
childHintTree
)
if (slotMetadata === null) {
slotMetadata = {}
......@@ -391,7 +727,14 @@ function collectSegmentDataImpl(
slotMetadata[parallelRouteKey] = childTree
}
const prefetchHints = route[4] ?? 0
// Union the hints already embedded in the FlightRouterState with the
// separately-computed build-time hints. During the initial build, the
// FlightRouterState was produced before collectPrefetchHints ran, so
// inlining hints (ParentInlinedIntoSelf, InlinedIntoChild) won't be in
// route[4] yet. On subsequent renders the hints are already in the
// FlightRouterState, so the union is idempotent.
const prefetchHints =
(route[4] ?? 0) | (hintTree !== null ? hintTree.hints : 0)
// Determine which params this segment varies on.
// Read the vary params thenable directly from the seed data. By the time
......
......@@ -2,6 +2,7 @@ import type { LoaderTree } from '../lib/app-dir-module'
import {
PrefetchHint,
type FlightRouterState,
type PrefetchHints,
} from '../../shared/lib/app-router-types'
import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
......@@ -9,6 +10,7 @@ import type { AppSegmentConfig } from '../../build/segment-config/app/app-segmen
async function createFlightRouterStateFromLoaderTreeImpl(
loaderTree: LoaderTree,
hintTree: PrefetchHints | null,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any,
didFindRootLayout: boolean
......@@ -29,6 +31,20 @@ async function createFlightRouterStateFromLoaderTreeImpl(
: undefined
let prefetchHints = 0
// Union in the precomputed build-time hints (e.g. segment inlining
// decisions) if available. When hints are not available (e.g. dev mode or
// if prefetch-hints.json was not generated), we fall through and still
// compute the other hints below. In the future this should be a build
// error, but for now we gracefully degrade.
//
// TODO: Move more of the hints computation (IsRootLayout, instant config,
// loading boundary detection) into the build-time measurement step in
// collectPrefetchHints, so this function only needs to union the
// precomputed bitmask rather than re-derive hints on every render.
if (hintTree !== null) {
prefetchHints |= hintTree.hints
}
// Mark the first segment that has a layout as the "root" layout
if (!didFindRootLayout && typeof layout !== 'undefined') {
didFindRootLayout = true
......@@ -49,8 +65,13 @@ async function createFlightRouterStateFromLoaderTreeImpl(
const children: FlightRouterState[1] = {}
for (const parallelRouteKey in parallelRoutes) {
// Look up the child hint node by parallel route key, traversing the
// hint tree in parallel with the loader tree.
const childHintNode = hintTree?.slots?.[parallelRouteKey] ?? null
const child = await createFlightRouterStateFromLoaderTreeImpl(
parallelRoutes[parallelRouteKey],
childHintNode,
getDynamicParamFromSegment,
searchParams,
didFindRootLayout
......@@ -84,12 +105,14 @@ async function createFlightRouterStateFromLoaderTreeImpl(
export async function createFlightRouterStateFromLoaderTree(
loaderTree: LoaderTree,
hintTree: PrefetchHints | null,
getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any
): Promise<FlightRouterState> {
const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl(
loaderTree,
hintTree,
getDynamicParamFromSegment,
searchParams,
didFindRootLayout
......@@ -98,6 +121,7 @@ export async function createFlightRouterStateFromLoaderTree(
export async function createRouteTreePrefetch(
loaderTree: LoaderTree,
hintTree: PrefetchHints | null,
getDynamicParamFromSegment: GetDynamicParamFromSegment
): Promise<FlightRouterState> {
// Search params should not be added to page segment's cache key during a
......@@ -107,6 +131,7 @@ export async function createRouteTreePrefetch(
const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl(
loaderTree,
hintTree,
getDynamicParamFromSegment,
searchParams,
didFindRootLayout
......
......@@ -40,7 +40,10 @@ export { RootLayoutBoundary } from '../../lib/framework/boundary-components'
export { preloadStyle, preloadFont, preconnect } from './rsc/preloads'
export { Postpone } from './rsc/postpone'
export { taintObjectReference } from './rsc/taint'
export { collectSegmentData } from './collect-segment-data'
export {
collectSegmentData,
collectPrefetchHints,
} from './collect-segment-data'
export const InstantValidation = () => {
if (
......
......@@ -3,6 +3,7 @@ import type { ServerRuntime, SizeLimit } from '../../types'
import type {
ExperimentalConfig,
NextConfigComplete,
PrefetchInliningConfig,
} from '../../server/config-shared'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type { ParsedUrlQuery } from 'querystring'
......@@ -19,6 +20,7 @@ import type { BaseNextRequest } from '../base-http'
import type { IncomingMessage } from 'http'
import type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'
import type { PrefetchHints } from '../../shared/lib/app-router-types'
const dynamicParamTypesSchema = s.enums([
'c',
......@@ -160,7 +162,7 @@ export interface RenderOptsPartial {
dynamicOnHover: boolean
optimisticRouting: boolean
inlineCss: boolean
prefetchInlining: boolean
prefetchInlining: PrefetchInliningConfig
authInterrupts: boolean
cachedNavigations: boolean
......@@ -199,6 +201,12 @@ export interface RenderOptsPartial {
*/
reactMaxHeadersLength: number | undefined
/**
* Per-route prefetch hints from prefetch-hints.json.
* Loaded at server startup from the build output.
*/
prefetchHints?: Record<string, PrefetchHints>
isStaticGeneration?: boolean
/**
......
......@@ -2,6 +2,7 @@ import type {
FlightDataPath,
FlightDataSegment,
FlightRouterState,
PrefetchHints,
Segment,
HeadData,
} from '../../shared/lib/app-router-types'
......@@ -37,6 +38,7 @@ export async function walkTreeWithFlightRouterState({
ctx,
preloadCallbacks,
MetadataOutlet,
hintTree,
}: {
loaderTreeToFilter: LoaderTree
parentParams: { [key: string]: string | string[] }
......@@ -50,6 +52,7 @@ export async function walkTreeWithFlightRouterState({
ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks
MetadataOutlet: React.ComponentType
hintTree: PrefetchHints | null
}): Promise<FlightDataPath[]> {
const {
renderOpts: { nextFontManifest, experimental },
......@@ -151,10 +154,12 @@ export async function walkTreeWithFlightRouterState({
? // Route tree prefetch requests contain some extra information
await createRouteTreePrefetch(
loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment
)
: await createFlightRouterStateFromLoaderTree(
loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment,
query
)
......@@ -181,10 +186,12 @@ export async function walkTreeWithFlightRouterState({
const routerState = parsedRequestHeaders.isRouteTreePrefetchRequest
? await createRouteTreePrefetch(
loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment
)
: await createFlightRouterStateFromLoaderTree(
loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment,
query
)
......@@ -212,6 +219,7 @@ export async function walkTreeWithFlightRouterState({
const routerState = await createFlightRouterStateFromLoaderTree(
// Create router state using the slice of the loaderTree
loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment,
query
)
......@@ -290,6 +298,7 @@ export async function walkTreeWithFlightRouterState({
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
preloadCallbacks,
MetadataOutlet,
hintTree: hintTree?.slots?.[parallelRouteKey] ?? null,
})
for (const subPath of subPaths) {
......@@ -329,10 +338,15 @@ export async function createFullTreeFlightDataForNavigation({
renderOpts: { experimental },
query,
getDynamicParamFromSegment,
pagePath,
} = ctx
const hintTreeForInitialRender =
ctx.renderOpts.prefetchHints?.[pagePath] ?? null
const routerState = await createFlightRouterStateFromLoaderTree(
loaderTree,
hintTreeForInitialRender,
getDynamicParamFromSegment,
query
)
......
......@@ -584,6 +584,7 @@ export default abstract class Server<
},
onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this),
prefetchHints: {},
reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength,
logServerFunctions:
typeof this.nextConfig.logging === 'object' &&
......
......@@ -224,7 +224,15 @@ export const experimentalSchema = {
dynamicOnHover: z.boolean().optional(),
optimisticRouting: z.boolean().optional(),
varyParams: z.boolean().optional(),
prefetchInlining: z.boolean().optional(),
prefetchInlining: z
.union([
z.boolean(),
z.object({
maxSize: z.number().optional(),
maxBundleSize: z.number().optional(),
}),
])
.optional(),
disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(),
cacheComponents: z.boolean().optional(),
......
......@@ -16,6 +16,14 @@ import { INFINITE_CACHE } from '../lib/constants'
import { isStableBuild } from '../shared/lib/errors/canary-only-config-error'
import type { FallbackRouteParam } from '../build/static-paths/types'
/**
* Resolved form of the prefetchInlining config after normalization in
* config.ts. User input (true, partial objects) is converted to this shape.
*/
export type PrefetchInliningConfig =
| false
| { maxSize: number; maxBundleSize: number }
export type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & {
images: Required<ImageConfigComplete>
typescript: TypeScriptConfig
......@@ -24,7 +32,10 @@ export type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & {
// override NextConfigComplete.experimental.htmlLimitedBots to string
// because it's not defined in NextConfigComplete.experimental
htmlLimitedBots: string | undefined
experimental: ExperimentalConfig
experimental: ExperimentalConfig & {
// Normalized by config.ts: true and partial objects become resolved objects
prefetchInlining?: PrefetchInliningConfig
}
// The root directory of the distDir. In development mode, this is the parent directory of `distDir`
// since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't
// traverse into the output directory.
......@@ -407,7 +418,12 @@ export interface ExperimentalConfig {
dynamicOnHover?: boolean
optimisticRouting?: boolean
varyParams?: boolean
prefetchInlining?: boolean
prefetchInlining?:
| boolean
| {
maxSize?: number
maxBundleSize?: number
}
preloadEntriesOnStart?: boolean
clientRouterFilter?: boolean
clientRouterFilterRedirects?: boolean
......
......@@ -380,6 +380,24 @@ function assignDefaultsAndValidate(
},
}
// Normalize prefetchInlining: true | { maxSize?, maxBundleSize? } into a
// resolved object with concrete defaults, so consumers don't have to
// resolve the values themselves.
if (result.experimental.prefetchInlining) {
const raw = result.experimental.prefetchInlining
const maxSize = typeof raw === 'object' ? (raw.maxSize ?? 2_048) : 2_048
const maxBundleSize =
typeof raw === 'object' ? (raw.maxBundleSize ?? 10_240) : 10_240
result.experimental.prefetchInlining = {
// Clamp Infinity to a finite value so the config survives
// JSON.stringify (used by output: standalone).
maxSize: Number.isFinite(maxSize) ? maxSize : Number.MAX_SAFE_INTEGER,
maxBundleSize: Number.isFinite(maxBundleSize)
? maxBundleSize
: Number.MAX_SAFE_INTEGER,
}
}
// ensure correct default is set for api-resolver revalidate handling
if (!result.experimental.trustHostHeader && ciEnvironment.hasNextSupport) {
result.experimental.trustHostHeader = true
......
......@@ -379,6 +379,7 @@ export default class FileSystemCache implements CacheHandler {
status: data.status,
postponed: undefined,
segmentPaths: undefined,
prefetchHints: undefined,
}
writer.append(
......@@ -432,6 +433,7 @@ export default class FileSystemCache implements CacheHandler {
status: data.status,
postponed: data.postponed,
segmentPaths,
prefetchHints: undefined,
}
writer.append(
......
......@@ -39,6 +39,7 @@ import {
PAGES_MANIFEST,
BUILD_ID_FILE,
MIDDLEWARE_MANIFEST,
PREFETCH_HINTS,
PRERENDER_MANIFEST,
ROUTES_MANIFEST,
CLIENT_PUBLIC_FILES_PATH,
......@@ -111,6 +112,7 @@ import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite'
import type { ServerOnInstrumentationRequestError } from './app-render/types'
import type { PrefetchHints } from '../shared/lib/app-router-types'
import { RouteKind } from './route-kind'
import { InvariantError } from '../shared/lib/invariant-error'
import { AwaiterOnce } from './after/awaiter'
......@@ -201,6 +203,10 @@ export default class NextNodeServer extends BaseServer<
installGlobalBehaviors(this.nextConfig)
// Load prefetch hints from the build output. This must happen before
// any render to ensure segment inlining decisions are available.
this.renderOpts.prefetchHints = this.getPrefetchHints()
const isDev = options.dev ?? false
this.isDev = isDev
this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm)
......@@ -1906,6 +1912,28 @@ export default class NextNodeServer extends BaseServer<
return this._cachedPreviewManifest
}
private _cachedPrefetchHints: Record<string, PrefetchHints> | undefined
protected getPrefetchHints(): Record<string, PrefetchHints> {
if (this._cachedPrefetchHints) {
return this._cachedPrefetchHints
}
this._cachedPrefetchHints =
(loadManifest(
join(
/* turbopackIgnore: true */ this.distDir,
SERVER_DIRECTORY,
PREFETCH_HINTS
),
true,
undefined,
false,
true // handleMissing: don't crash if the file doesn't exist
) as Record<string, PrefetchHints>) ?? {}
return this._cachedPrefetchHints
}
protected getRoutesManifest(): NormalizedRouteManifest | undefined {
return getTracer().trace(
NextNodeServerSpan.getRoutesManifest,
......
import type { OutgoingHttpHeaders, ServerResponse } from 'http'
import type { CacheControl } from './lib/cache-control'
import type { FetchMetrics } from './base-http'
import type { PrefetchHints } from '../shared/lib/app-router-types'
import {
chainStreams,
......@@ -47,6 +48,13 @@ export type AppPageRenderResultMetadata = {
segmentData?: Map<string, Buffer>
/**
* Per-route prefetch hints computed at build time (e.g. segment inlining
* decisions based on gzip sizes). Written to prefetch-hints.json by the
* build pipeline.
*/
prefetchHints?: PrefetchHints
/**
* In development, the resume data cache is warmed up before the render. This
* is attached to the metadata so that it can be used during the render. When
......
......@@ -166,6 +166,18 @@ export const enum PrefetchHint {
SubtreeHasLoadingBoundary = 0b01000,
// This segment is the root layout of the application.
IsRootLayout = 0b10000,
// This segment's response includes its parent's data inlined into it.
// Set at build time by the segment size measurement pass.
ParentInlinedIntoSelf = 0b100000,
// This segment's data is inlined into one of its children — don't fetch
// it separately. Set at build time by the segment size measurement pass.
InlinedIntoChild = 0b1000000,
// On a __PAGE__: this page's response includes the head (metadata/viewport)
// at the end of its SegmentPrefetch[] array.
HeadInlinedIntoSelf = 0b10000000,
// On the root hint node: the head was NOT inlined into any page — fetch
// it separately. Absence of this bit means the head is bundled into a page.
HeadOutlined = 0b100000000,
}
/**
......@@ -239,6 +251,23 @@ export type FlightDataPath =
*/
export type FlightData = Array<FlightDataPath> | string
/**
* Per-route prefetch hints computed at build time. Mirrors the shape of the
* loader tree so hints can be traversed in parallel during router state
* creation. Each node stores a bitmask of PrefetchHint flags
* (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size
* measurement pass.
*
* Persisted to prefetch-hints.json as Record<string, PrefetchHints> (keyed
* by route pattern) and loaded at server startup.
*/
export type PrefetchHints = {
/** Bitmask of PrefetchHint flags for this segment. */
hints: number
/** Child hint nodes, keyed by parallel route key. */
slots: Record<string, PrefetchHints> | null
}
export type ActionResult = Promise<any>
export type InitialRSCPayload = {
......
......@@ -95,6 +95,7 @@ export const NEXT_FONT_MANIFEST = 'next-font-manifest'
export const EXPORT_MARKER = 'export-marker.json'
export const EXPORT_DETAIL = 'export-detail.json'
export const PRERENDER_MANIFEST = 'prerender-manifest.json'
export const PREFETCH_HINTS = 'prefetch-hints.json'
export const ROUTES_MANIFEST = 'routes-manifest.json'
export const IMAGES_MANIFEST = 'images-manifest.json'
export const SERVER_FILES_MANIFEST = 'required-server-files'
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// Test fixture for max prefetch inlining. With Infinity thresholds, all
// segments are bundled into a single response per route, similar to how
// prefetching worked before the Segment Cache (pre-Next 16).
import { LinkAccordion } from '../components/link-accordion'
export default function Home() {
return (
<div>
<h1>Home</h1>
<ul>
<li>
<LinkAccordion href="/shared/a/b/c">Route A</LinkAccordion>
</li>
<li>
<LinkAccordion href="/shared/a/d/e">Route B</LinkAccordion>
</li>
<li>
<LinkAccordion href="/shared/a/b/c" id="duplicate-a">
Route A (duplicate)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dynamic/hello">Dynamic Route</LinkAccordion>
</li>
</ul>
</div>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
id,
}: {
href: LinkProps['href']
children: React.ReactNode
id?: string
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={id ?? href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
// Tests prefetch inlining with maxSize and maxBundleSize set to Infinity,
// which inlines all segments into a single response per route. This
// approximates the behavior of pre-Segment Cache (pre-Next 16) prefetching,
// where all prefetch data was bundled into one response. The tradeoff is that
// you lose the benefits of per-layout deduplication across routes.
//
// This is a special case of the general prefetch inlining feature tested in
// the sibling `prefetch-inlining` directory. We may consolidate these tests
// in the future.
describe('max prefetch inlining', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('disabled in development', () => {})
return
}
it('bundles all segment data into a single request per route', async () => {
// The test app has two routes that are 5 segments deep:
// /shared/a/b/c and /shared/a/d/e
// Without inlining, prefetching each route would issue one request per
// segment plus one for the head (6+ requests). With inlining enabled,
// all segment data is bundled into a single response, so revealing a
// link should produce at most 2 prefetch requests per route: one for
// /_tree and one for the inlined segment data.
let rscRequestCount = 0
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
p.on('request', (request: Playwright.Request) => {
if (request.headers()['rsc']) {
rscRequestCount++
}
})
},
})
const act = createRouterAct(page!)
// Reveal the first link to trigger a prefetch of /shared/a/b/c
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/shared/a/b/c"]')
.click()
},
{
includes: 'Page C',
}
)
// Snapshot the request count before revealing the second link
const countBeforeSecondPrefetch = rscRequestCount
// Reveal the second link to trigger a prefetch of /shared/a/d/e
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/shared/a/d/e"]')
.click()
},
{
includes: 'Page E',
}
)
// The delta should be at most 2 requests (/_tree + /_inlined).
// Without inlining, there would be 6+ individual segment requests.
const delta = rscRequestCount - countBeforeSecondPrefetch
expect(delta).toBeLessThanOrEqual(2)
// Navigate to the second route. Because the data was fully prefetched,
// there should be no additional requests.
await act(async () => {
await browser.elementByCss('a[href="/shared/a/d/e"]').click()
}, 'no-requests')
// Verify the page rendered correctly
const text = await browser.elementByCss('#page-e').text()
expect(text).toBe('Page E')
})
it('works with dynamic routes', async () => {
// Regression test: the build previously failed with
// "Invariant: missing __PAGE__ segmentPath" when prefetchInlining was
// combined with dynamic routes.
const $ = await next.render$('/dynamic/hello')
expect($('#dynamic-page').text()).toBe('hello')
})
it('deduplicates inlined prefetch requests for the same route', async () => {
// Two links point to the same route (/shared/a/b/c). When the first
// link is revealed, its prefetch spawns an inlined request. While
// that request is still pending, revealing the second link should
// not spawn any additional requests because the segments are already
// Pending from the first task.
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page!)
await act(
async () => {
// Reveal the first link, blocking its response so the prefetch
// stays in-flight.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/shared/a/b/c"]')
.click()
}, 'block')
// While the first prefetch is still pending, reveal a second
// link to the same route. This should not spawn any new
// requests because the segments are already Pending.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="duplicate-a"]')
.click()
}, 'no-requests')
},
{
includes: 'Page C',
}
)
// Navigate to the route. Because the data was fully prefetched,
// no additional requests are needed.
await act(async () => {
await browser.elementByCss('a[href="/shared/a/b/c"]').click()
}, 'no-requests')
const text = await browser.elementByCss('#page-c').text()
expect(text).toBe('Page C')
})
})
/**
* Setting both thresholds to Infinity inlines all segments into a single
* response per route, approximating pre-Segment Cache (pre-Next 16)
* prefetching behavior where all data was bundled into one response. The
* tradeoff is that per-layout deduplication across routes is lost.
*
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
prefetchInlining: {
maxSize: Infinity,
maxBundleSize: Infinity,
},
},
}
module.exports = nextConfig
import { LinkAccordion } from '../components/link-accordion'
export default function Home() {
return (
<div>
<h1>Home</h1>
<ul>
<li>
<LinkAccordion href="/shared/a/b/c">Route A</LinkAccordion>
</li>
<li>
<LinkAccordion href="/shared/a/d/e">Route B</LinkAccordion>
</li>
<li>
<LinkAccordion href="/shared/a/b/c" id="duplicate-a">
Route A (duplicate)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dynamic/hello">Dynamic Route</LinkAccordion>
</li>
</ul>
</div>
)
export default function Page() {
return <p>hello world</p>
}
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
export default function Page() {
return <p>Deep page</p>
}
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
import { ReactNode } from 'react'
import { NoInline } from '../../../components/no-inline'
// This layout renders large content that depends on the route param.
// In a fallback shell render, `await params` causes postponement so
// the segment output is small. In a concrete render the full content
// appears, pushing the segment above the 2KB gzip inlining threshold.
// If hints were incorrectly based on the fallback shell, this layout
// would appear small and get inlined — the test catches that.
export default async function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<NoInline />
<p>{`Dynamic layout for: ${slug}`}</p>
{children}
</div>
)
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return <p>Dynamic page: {slug}</p>
}
export function generateStaticParams() {
return [{ slug: 'hello' }, { slug: 'world' }]
}
import { ReactNode } from 'react'
import { NoInline } from '../../components/no-inline'
export default function LargeLayout({ children }: { children: ReactNode }) {
return (
<div>
<NoInline />
{children}
</div>
)
}
export default function Page() {
return <p>Outlined test page</p>
}
export default function Sidebar() {
return <p>Sidebar content</p>
}
import { ReactNode } from 'react'
export default function ParallelLayout({
children,
sidebar,
}: {
children: ReactNode
sidebar: ReactNode
}) {
return (
<div>
<main>{children}</main>
<aside>{sidebar}</aside>
</div>
)
}
export default function Page() {
return <p>Main content</p>
}
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
import { ReactNode } from 'react'
import { NoInline } from '../../../components/no-inline'
export default function LargeLayout({ children }: { children: ReactNode }) {
return (
<div>
<NoInline />
{children}
</div>
)
}
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}
import { ReactNode } from 'react'
export default function SmallChainLayout({
children,
}: {
children: ReactNode
}) {
return <div>{children}</div>
}
export default function SmallChainPage() {
return <p>Small chain page</p>
}
......@@ -6,11 +6,9 @@ import { useState } from 'react'
export function LinkAccordion({
href,
children,
id,
}: {
href: LinkProps['href']
children: React.ReactNode
id?: string
}) {
const [isVisible, setIsVisible] = useState(false)
return (
......@@ -19,7 +17,7 @@ export function LinkAccordion({
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={id ?? href}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
......
'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 { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
// Bit values from PrefetchHint enum (const enum, so we duplicate values here)
const ParentInlinedIntoSelf = 0b100000 // 32
const InlinedIntoChild = 0b1000000 // 64
// Matches the shape of RootTreePrefetch / TreePrefetch from collect-segment-
// data.tsx. We only declare the fields we need.
type TreePrefetch = {
name: string
prefetchHints: number
slots: null | { [key: string]: TreePrefetch }
}
type RootTreePrefetch = {
tree: TreePrefetch
}
/**
* Renders the TreePrefetch as an ASCII tree showing inlining decisions.
* Segments marked with "⇣ inlined" have their data included in a descendant's
* response instead of being fetched separately. Validates that parent/child
* hints are consistent (every InlinedIntoChild parent must have a child with
* ParentInlinedIntoSelf, and vice versa).
*/
// "outlined ■" is the fixed-width tag (10 chars). Inlined segments show just
// the arrow, right-aligned to match.
const OUTLINED_TAG = 'outlined \u25A0'
const INLINED_TAG = '\u21E3'.padStart(OUTLINED_TAG.length)
function renderInliningTree(tree: TreePrefetch): string {
const lines: string[] = []
collectNodes(tree, '', true, false, lines)
return '\n' + lines.join('\n') + '\n'
}
function collectNodes(
node: TreePrefetch,
prefix: string,
isLast: boolean,
hasParent: boolean,
lines: string[],
slotKey?: string
): void {
const inlinedIntoChild = (node.prefetchHints & InlinedIntoChild) !== 0
const _parentInlined = (node.prefetchHints & ParentInlinedIntoSelf) !== 0
const slotPrefix =
slotKey !== undefined && slotKey !== 'children' ? `@${slotKey}/` : ''
const name = hasParent ? `${slotPrefix}"${node.name}"` : 'root'
const tag = inlinedIntoChild ? INLINED_TAG : OUTLINED_TAG
const connector = hasParent
? isLast
? '\u2514\u2500\u2500 '
: '\u251C\u2500\u2500 '
: ''
lines.push(`${tag} ${prefix}${connector}${name}`)
// Validate consistency between parent and children.
if (node.slots) {
const children = Object.values(node.slots)
const childrenWithParentInlined = children.filter(
(c) => (c.prefetchHints & ParentInlinedIntoSelf) !== 0
)
if (inlinedIntoChild && childrenWithParentInlined.length === 0) {
throw new Error(
`"${node.name}" has InlinedIntoChild but no child has ParentInlinedIntoSelf`
)
}
if (!inlinedIntoChild && childrenWithParentInlined.length > 0) {
const names = childrenWithParentInlined.map((c) => c.name).join(', ')
throw new Error(
`"${node.name}" does not have InlinedIntoChild but child(ren) ${names} ` +
`have ParentInlinedIntoSelf`
)
}
const childPrefix =
prefix + (hasParent ? (isLast ? ' ' : '\u2502 ') : '')
const keys = Object.keys(node.slots)
const hasMultipleSlots = keys.length > 1
for (let i = 0; i < keys.length; i++) {
collectNodes(
node.slots[keys[i]],
childPrefix,
i === keys.length - 1,
true,
lines,
hasMultipleSlots ? keys[i] : undefined
)
}
}
}
// Temporary helper: fetches the route tree prefetch response and parses the
// RootTreePrefetch object out of it. This will be replaced by end-to-end
// tests that assert on actual client prefetch request behavior once the
// client-side changes are done.
async function fetchRouteTreePrefetch(
next: any,
pathname: string
): Promise<RootTreePrefetch> {
const res = await next.fetch(pathname, {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
'Next-Router-Segment-Prefetch': '/_tree',
},
})
const text = await res.text()
// The Flight response for a plain JSON object (no React nodes) is a single
// line: `0:{"tree":...,"staleTime":...}`. Strip the row ID prefix and parse.
const jsonStr = text.slice(text.indexOf(':') + 1)
return JSON.parse(jsonStr)
}
describe('prefetch inlining', () => {
const { next, isNextDev } = nextTestSetup({
const { next, isNextDev, isTurbopack } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('disabled in development', () => {})
it('prefetch hints are only computed during build', () => {})
return
}
it('bundles all segment data into a single request per route', async () => {
// The test app has two routes that are 5 segments deep:
// /shared/a/b/c and /shared/a/d/e
// Without inlining, prefetching each route would issue one request per
// segment plus one for the head (6+ requests). With inlining enabled,
// all segment data is bundled into a single response, so revealing a
// link should produce at most 2 prefetch requests per route: one for
// /_tree and one for the inlined segment data.
let rscRequestCount = 0
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
p.on('request', (request: Playwright.Request) => {
if (request.headers()['rsc']) {
rscRequestCount++
}
})
},
})
const act = createRouterAct(page!)
// Reveal the first link to trigger a prefetch of /shared/a/b/c
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/shared/a/b/c"]')
.click()
},
{
includes: 'Page C',
}
)
it('small chain: inlines multiple ancestors into deepest child', async () => {
// Root → child layout → page, all with minimal content (well under the
// 2KB gzip threshold). Both the root and child layout are small enough
// to be inlined into the page's response. The entire chain fits within
// the 10KB total budget, so everything collapses into a single fetch
// for the page segment.
const data = await fetchRouteTreePrefetch(next, '/test-small-chain')
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
⇣ root
⇣ └── "test-small-chain"
outlined ■ └── "__PAGE__"
"
`)
})
// Snapshot the request count before revealing the second link
const countBeforeSecondPrefetch = rscRequestCount
// Reveal the second link to trigger a prefetch of /shared/a/d/e
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/shared/a/d/e"]')
.click()
},
{
includes: 'Page E',
}
)
it('outlined: large segment breaks the inlining chain', async () => {
// Root → large layout (> 2KB gzipped) → page. The large layout exceeds
// the per-segment inlining threshold so it can't be inlined into the
// page. Root is still small enough for the large layout to accept, so
// root gets inlined into the large layout's response. The page is
// fetched separately since its parent was too large.
const data = await fetchRouteTreePrefetch(next, '/test-outlined')
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
⇣ root
outlined ■ └── "test-outlined"
outlined ■ └── "__PAGE__"
"
`)
})
// The delta should be at most 2 requests (/_tree + /_inlined).
// Without inlining, there would be 6+ individual segment requests.
const delta = rscRequestCount - countBeforeSecondPrefetch
expect(delta).toBeLessThanOrEqual(2)
it('parallel routes: parent inlines into one slot only', async () => {
// Layout with two parallel slots (children + @sidebar), all small. The
// layout can only be inlined into one child — the first slot that
// accepts (children). The @sidebar slot doesn't receive the parent's
// data and is fetched independently.
//
// Turbopack and webpack produce slightly different route tree structures
// for parallel routes (turbopack adds a "(slot)" intermediate segment),
// so we use separate snapshots for each.
// Turbopack and webpack produce slightly different route tree structures
// for parallel routes. Turbopack adds a "(slot)" intermediate segment
// for the @sidebar slot; webpack puts __PAGE__ directly under it.
const data = await fetchRouteTreePrefetch(next, '/test-parallel')
if (isTurbopack) {
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
⇣ root
⇣ └── "test-parallel"
outlined ■ ├── "__PAGE__"
⇣ └── @sidebar/"(slot)"
outlined ■ └── "__PAGE__"
"
`)
} else {
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
⇣ root
⇣ └── "test-parallel"
⇣ ├── @sidebar/"(slot)"
outlined ■ │ └── "__PAGE__"
outlined ■ └── "__PAGE__"
"
`)
}
})
// Navigate to the second route. Because the data was fully prefetched,
// there should be no additional requests.
await act(async () => {
await browser.elementByCss('a[href="/shared/a/d/e"]').click()
}, 'no-requests')
it('home: root inlines directly into page', async () => {
// Simplest possible case: root layout + page. Root is small and inlines
// into the page.
const data = await fetchRouteTreePrefetch(next, '/')
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
⇣ root
outlined ■ └── "__PAGE__"
"
`)
})
// Verify the page rendered correctly
const text = await browser.elementByCss('#page-e').text()
expect(text).toBe('Page E')
it('restart: large segment in the middle creates two inlining groups', async () => {
// root (small) → test-restart (small) → large-middle (> 2KB) → after
// (small) → page (small). The large segment can't be inlined into its
// children, splitting the tree into two inlining groups:
// [root, test-restart] → large-middle's response, and [after] → page's
// response.
const data = await fetchRouteTreePrefetch(
next,
'/test-restart/large-middle/after'
)
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
⇣ root
⇣ └── "test-restart"
outlined ■ └── "large-middle"
⇣ └── "after"
outlined ■ └── "__PAGE__"
"
`)
})
it('works with dynamic routes', async () => {
// Regression test: the build previously failed with
// "Invariant: missing __PAGE__ segmentPath" when prefetchInlining was
// combined with dynamic routes.
const $ = await next.render$('/dynamic/hello')
expect($('#dynamic-page').text()).toBe('hello')
it('deep chain: all small segments inline to the leaf', async () => {
// root → test-deep → a → b → c → page, all small. Every segment in
// the chain inlines down to the page, producing a single fetch.
const data = await fetchRouteTreePrefetch(next, '/test-deep/a/b/c')
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
⇣ root
⇣ └── "test-deep"
⇣ └── "a"
⇣ └── "b"
⇣ └── "c"
outlined ■ └── "__PAGE__"
"
`)
})
it('deduplicates inlined prefetch requests for the same route', async () => {
// Two links point to the same route (/shared/a/b/c). When the first
// link is revealed, its prefetch spawns an inlined request. While
// that request is still pending, revealing the second link should
// not spawn any additional requests because the segments are already
// Pending from the first task.
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page!)
await act(
async () => {
// Reveal the first link, blocking its response so the prefetch
// stays in-flight.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/shared/a/b/c"]')
.click()
}, 'block')
// While the first prefetch is still pending, reveal a second
// link to the same route. This should not spawn any new
// requests because the segments are already Pending.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="duplicate-a"]')
.click()
}, 'no-requests')
},
{
includes: 'Page C',
}
)
it('dynamic route: hints are based on concrete params, not fallback shell', async () => {
// The [slug] layout renders large content gated behind `await params`. In
// the fallback shell, `await params` suspends so the segment appears small.
// In a concrete render the full content is included, pushing it above the
// 2KB threshold. If hints were incorrectly based on the fallback, the
// layout would get inlined. Instead it should be outlined because the
// concrete render is large.
const data = await fetchRouteTreePrefetch(next, '/test-dynamic/hello')
const helloTree = renderInliningTree(data.tree)
// Navigate to the route. Because the data was fully prefetched,
// no additional requests are needed.
await act(async () => {
await browser.elementByCss('a[href="/shared/a/b/c"]').click()
}, 'no-requests')
expect(helloTree).toMatchInlineSnapshot(`
"
⇣ root
⇣ └── "test-dynamic"
outlined ■ └── "slug"
outlined ■ └── "__PAGE__"
"
`)
const text = await browser.elementByCss('#page-c').text()
expect(text).toBe('Page C')
// Different param value should produce the same hints (keyed by route
// pattern, not concrete path)
const data2 = await fetchRouteTreePrefetch(next, '/test-dynamic/world')
expect(renderInliningTree(data2.tree)).toBe(helloTree)
})
})
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