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 { ...@@ -7,6 +7,7 @@ import type {
import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin' import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin' import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin'
import type { CacheControl, Revalidate } from '../server/lib/cache-control' import type { CacheControl, Revalidate } from '../server/lib/cache-control'
import type { PrefetchHints } from '../shared/lib/app-router-types'
import '../lib/setup-exception-listeners' import '../lib/setup-exception-listeners'
...@@ -61,6 +62,7 @@ import { ...@@ -61,6 +62,7 @@ import {
IMAGES_MANIFEST, IMAGES_MANIFEST,
PAGES_MANIFEST, PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
PREFETCH_HINTS,
PRERENDER_MANIFEST, PRERENDER_MANIFEST,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
ROUTES_MANIFEST, ROUTES_MANIFEST,
...@@ -1853,6 +1855,7 @@ export default async function build( ...@@ -1853,6 +1855,7 @@ export default async function build(
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json' SERVER_REFERENCE_MANIFEST + '.json'
), ),
path.join(SERVER_DIRECTORY, PREFETCH_HINTS),
] ]
: []), : []),
...(pagesDir && bundler !== Bundler.Turbopack ...(pagesDir && bundler !== Bundler.Turbopack
...@@ -2739,6 +2742,11 @@ export default async function build( ...@@ -2739,6 +2742,11 @@ export default async function build(
preview: previewProps, 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 tbdPrerenderRoutes: string[] = []
const { i18n } = config const { i18n } = config
...@@ -3194,6 +3202,11 @@ export default async function build( ...@@ -3194,6 +3202,11 @@ export default async function build(
initialCacheControl: cacheControl, initialCacheControl: cacheControl,
}) })
// Collect prefetch hints (first-writer-wins per page)
if (metadata.prefetchHints && !(page in prefetchHints)) {
prefetchHints[page] = metadata.prefetchHints
}
if (cacheControl.revalidate !== 0) { if (cacheControl.revalidate !== 0) {
const normalizedRoute = normalizePagePath(route.pathname) const normalizedRoute = normalizePagePath(route.pathname)
...@@ -3369,6 +3382,11 @@ export default async function build( ...@@ -3369,6 +3382,11 @@ export default async function build(
builtSegmentDataRoute builtSegmentDataRoute
) )
} }
// Collect prefetch hints (first-writer-wins per page)
if (metadata?.prefetchHints && !(page in prefetchHints)) {
prefetchHints[page] = metadata.prefetchHints
}
} }
pageInfos.set(route.pathname, { pageInfos.set(route.pathname, {
...@@ -3958,6 +3976,10 @@ export default async function build( ...@@ -3958,6 +3976,10 @@ export default async function build(
config.experimental.allowedRevalidateHeaderKeys config.experimental.allowedRevalidateHeaderKeys
await writePrerenderManifest(distDir, prerenderManifest) await writePrerenderManifest(distDir, prerenderManifest)
await writeManifest(
path.join(distDir, SERVER_DIRECTORY, PREFETCH_HINTS),
prefetchHints
)
await writeClientSsgManifest(prerenderManifest, { await writeClientSsgManifest(prerenderManifest, {
distDir, distDir,
buildId, buildId,
......
...@@ -738,7 +738,7 @@ export async function handler( ...@@ -738,7 +738,7 @@ export async function handler(
nextConfig.experimental.optimisticRouting nextConfig.experimental.optimisticRouting
), ),
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining), prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts), authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
cachedNavigations: Boolean( cachedNavigations: Boolean(
nextConfig.experimental.cachedNavigations nextConfig.experimental.cachedNavigations
......
...@@ -163,7 +163,7 @@ async function requestHandler( ...@@ -163,7 +163,7 @@ async function requestHandler(
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover), dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting), optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),
inlineCss: Boolean(nextConfig.experimental.inlineCss), inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: Boolean(nextConfig.experimental.prefetchInlining), prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts), authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
cachedNavigations: Boolean(nextConfig.experimental.cachedNavigations), cachedNavigations: Boolean(nextConfig.experimental.cachedNavigations),
clientTraceMetadata: clientTraceMetadata:
......
...@@ -69,6 +69,13 @@ export function createInitialRouterState({ ...@@ -69,6 +69,13 @@ export function createInitialRouterState({
// NOTE: The metadataVaryPath isn't used for anything currently because the // 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 // head is embedded into the CacheNode tree, but eventually we'll lift it out
// and store it on the top-level state object. // 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 acc = { metadataVaryPath: null }
const initialRouteTree = convertRootFlightRouterStateToRouteTree( const initialRouteTree = convertRootFlightRouterStateToRouteTree(
initialTree, initialTree,
......
...@@ -100,6 +100,7 @@ export async function exportAppPage( ...@@ -100,6 +100,7 @@ export async function exportAppPage(
fetchTags, fetchTags,
fetchMetrics, fetchMetrics,
segmentData, segmentData,
prefetchHints,
renderResumeDataCache, renderResumeDataCache,
} = metadata } = metadata
...@@ -218,6 +219,7 @@ export async function exportAppPage( ...@@ -218,6 +219,7 @@ export async function exportAppPage(
headers, headers,
postponed, postponed,
segmentPaths, segmentPaths,
prefetchHints,
} }
fileWriter.append( fileWriter.append(
...@@ -231,6 +233,7 @@ export async function exportAppPage( ...@@ -231,6 +233,7 @@ export async function exportAppPage(
? meta ? meta
: { : {
segmentPaths: meta.segmentPaths, segmentPaths: meta.segmentPaths,
prefetchHints: meta.prefetchHints,
}, },
hasEmptyStaticShell: Boolean(postponed) && html === '', hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed), hasPostponed: Boolean(postponed),
......
import type { OutgoingHttpHeaders } from 'node:http' import type { OutgoingHttpHeaders } from 'node:http'
import type { PrefetchHints } from '../../shared/lib/app-router-types'
export type RouteMetadata = { export type RouteMetadata = {
status: number | undefined status: number | undefined
headers: OutgoingHttpHeaders | undefined headers: OutgoingHttpHeaders | undefined
postponed: string | undefined postponed: string | undefined
segmentPaths: Array<string> | undefined segmentPaths: Array<string> | undefined
prefetchHints: PrefetchHints | undefined
} }
...@@ -11,6 +11,7 @@ import type { ...@@ -11,6 +11,7 @@ import type {
FlightData, FlightData,
InitialRSCPayload, InitialRSCPayload,
FlightDataPath, FlightDataPath,
PrefetchHints,
} from '../../shared/lib/app-router-types' } from '../../shared/lib/app-router-types'
import type { Readable } from 'node:stream' import type { Readable } from 'node:stream'
import { import {
...@@ -618,6 +619,7 @@ async function generateDynamicRSCPayload( ...@@ -618,6 +619,7 @@ async function generateDynamicRSCPayload(
rootLayoutIncluded: false, rootLayoutIncluded: false,
preloadCallbacks, preloadCallbacks,
MetadataOutlet, MetadataOutlet,
hintTree: ctx.renderOpts.prefetchHints?.[ctx.pagePath] ?? null,
}) })
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
} }
...@@ -1667,8 +1669,10 @@ async function getRSCPayload( ...@@ -1667,8 +1669,10 @@ async function getRSCPayload(
workStore, workStore,
} = ctx } = ctx
const hints = ctx.renderOpts.prefetchHints?.[ctx.pagePath] ?? null
const initialTree = await createFlightRouterStateFromLoaderTree( const initialTree = await createFlightRouterStateFromLoaderTree(
tree, tree,
hints,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query
) )
...@@ -1848,8 +1852,10 @@ async function getErrorRSCPayload( ...@@ -1848,8 +1852,10 @@ async function getErrorRSCPayload(
createElement(Metadata, null) createElement(Metadata, null)
) )
const errorHints = ctx.renderOpts.prefetchHints?.[ctx.pagePath] ?? null
const initialTree = await createFlightRouterStateFromLoaderTree( const initialTree = await createFlightRouterStateFromLoaderTree(
tree, tree,
errorHints,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query
) )
...@@ -6320,11 +6326,13 @@ async function prerenderToStream( ...@@ -6320,11 +6326,13 @@ async function prerenderToStream(
? metadata.flightData.subarray(1) ? metadata.flightData.subarray(1)
: metadata.flightData : metadata.flightData
metadata.segmentData = await collectSegmentData( await collectSegmentData(
flightData, flightData,
finalServerPrerenderStore, finalServerPrerenderStore,
ComponentMod, ComponentMod,
renderOpts renderOpts,
ctx.pagePath,
metadata
) )
if (serverIsDynamic) { if (serverIsDynamic) {
...@@ -6574,11 +6582,13 @@ async function prerenderToStream( ...@@ -6574,11 +6582,13 @@ async function prerenderToStream(
if (shouldGenerateStaticFlightData(workStore)) { if (shouldGenerateStaticFlightData(workStore)) {
metadata.flightData = flightData metadata.flightData = flightData
metadata.segmentData = await collectSegmentData( await collectSegmentData(
flightData, flightData,
ssrPrerenderStore, ssrPrerenderStore,
ComponentMod, ComponentMod,
renderOpts renderOpts,
ctx.pagePath,
metadata
) )
} }
...@@ -6783,11 +6793,13 @@ async function prerenderToStream( ...@@ -6783,11 +6793,13 @@ async function prerenderToStream(
if (shouldGenerateStaticFlightData(workStore)) { if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer(reactServerResult.asStream()) const flightData = await streamToBuffer(reactServerResult.asStream())
metadata.flightData = flightData metadata.flightData = flightData
metadata.segmentData = await collectSegmentData( await collectSegmentData(
flightData, flightData,
prerenderLegacyStore, prerenderLegacyStore,
ComponentMod, ComponentMod,
renderOpts renderOpts,
ctx.pagePath,
metadata
) )
} }
...@@ -6951,11 +6963,13 @@ async function prerenderToStream( ...@@ -6951,11 +6963,13 @@ async function prerenderToStream(
reactServerPrerenderResult.asStream() reactServerPrerenderResult.asStream()
) )
metadata.flightData = flightData metadata.flightData = flightData
metadata.segmentData = await collectSegmentData( await collectSegmentData(
flightData, flightData,
prerenderLegacyStore, prerenderLegacyStore,
ComponentMod, ComponentMod,
renderOpts renderOpts,
ctx.pagePath,
metadata
) )
} }
...@@ -7075,8 +7089,10 @@ async function collectSegmentData( ...@@ -7075,8 +7089,10 @@ async function collectSegmentData(
fullPageDataBuffer: Buffer, fullPageDataBuffer: Buffer,
prerenderStore: PrerenderStore, prerenderStore: PrerenderStore,
ComponentMod: AppPageModule, ComponentMod: AppPageModule,
renderOpts: RenderOpts renderOpts: RenderOpts,
): Promise<Map<string, Buffer> | undefined> { pagePath: string,
metadata: AppPageRenderResultMetadata
): Promise<void> {
// Per-segment prefetch data // Per-segment prefetch data
// //
// All of the segments for a page are generated simultaneously, including // All of the segments for a page are generated simultaneously, including
...@@ -7107,13 +7123,45 @@ async function collectSegmentData( ...@@ -7107,13 +7123,45 @@ async function collectSegmentData(
const selectStaleTime = createSelectStaleTime(renderOpts.experimental) const selectStaleTime = createSelectStaleTime(renderOpts.experimental)
const staleTime = selectStaleTime(prerenderStore.stale) 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, renderOpts.cacheComponents,
fullPageDataBuffer, fullPageDataBuffer,
staleTime, staleTime,
clientModules, clientModules,
serverConsumerManifest, serverConsumerManifest,
renderOpts.experimental.prefetchInlining Boolean(renderOpts.experimental.prefetchInlining),
hints
) )
} }
......
...@@ -2,6 +2,7 @@ import type { LoaderTree } from '../lib/app-dir-module' ...@@ -2,6 +2,7 @@ import type { LoaderTree } from '../lib/app-dir-module'
import { import {
PrefetchHint, PrefetchHint,
type FlightRouterState, type FlightRouterState,
type PrefetchHints,
} from '../../shared/lib/app-router-types' } from '../../shared/lib/app-router-types'
import type { GetDynamicParamFromSegment } from './app-render' import type { GetDynamicParamFromSegment } from './app-render'
import { addSearchParamsIfPageSegment } from '../../shared/lib/segment' import { addSearchParamsIfPageSegment } from '../../shared/lib/segment'
...@@ -9,6 +10,7 @@ import type { AppSegmentConfig } from '../../build/segment-config/app/app-segmen ...@@ -9,6 +10,7 @@ import type { AppSegmentConfig } from '../../build/segment-config/app/app-segmen
async function createFlightRouterStateFromLoaderTreeImpl( async function createFlightRouterStateFromLoaderTreeImpl(
loaderTree: LoaderTree, loaderTree: LoaderTree,
hintTree: PrefetchHints | null,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any, searchParams: any,
didFindRootLayout: boolean didFindRootLayout: boolean
...@@ -29,6 +31,20 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -29,6 +31,20 @@ async function createFlightRouterStateFromLoaderTreeImpl(
: undefined : undefined
let prefetchHints = 0 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 // Mark the first segment that has a layout as the "root" layout
if (!didFindRootLayout && typeof layout !== 'undefined') { if (!didFindRootLayout && typeof layout !== 'undefined') {
didFindRootLayout = true didFindRootLayout = true
...@@ -49,8 +65,13 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -49,8 +65,13 @@ async function createFlightRouterStateFromLoaderTreeImpl(
const children: FlightRouterState[1] = {} const children: FlightRouterState[1] = {}
for (const parallelRouteKey in parallelRoutes) { 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( const child = await createFlightRouterStateFromLoaderTreeImpl(
parallelRoutes[parallelRouteKey], parallelRoutes[parallelRouteKey],
childHintNode,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
didFindRootLayout didFindRootLayout
...@@ -84,12 +105,14 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -84,12 +105,14 @@ async function createFlightRouterStateFromLoaderTreeImpl(
export async function createFlightRouterStateFromLoaderTree( export async function createFlightRouterStateFromLoaderTree(
loaderTree: LoaderTree, loaderTree: LoaderTree,
hintTree: PrefetchHints | null,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
searchParams: any searchParams: any
): Promise<FlightRouterState> { ): Promise<FlightRouterState> {
const didFindRootLayout = false const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl( return createFlightRouterStateFromLoaderTreeImpl(
loaderTree, loaderTree,
hintTree,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
didFindRootLayout didFindRootLayout
...@@ -98,6 +121,7 @@ export async function createFlightRouterStateFromLoaderTree( ...@@ -98,6 +121,7 @@ export async function createFlightRouterStateFromLoaderTree(
export async function createRouteTreePrefetch( export async function createRouteTreePrefetch(
loaderTree: LoaderTree, loaderTree: LoaderTree,
hintTree: PrefetchHints | null,
getDynamicParamFromSegment: GetDynamicParamFromSegment getDynamicParamFromSegment: GetDynamicParamFromSegment
): Promise<FlightRouterState> { ): Promise<FlightRouterState> {
// Search params should not be added to page segment's cache key during a // Search params should not be added to page segment's cache key during a
...@@ -107,6 +131,7 @@ export async function createRouteTreePrefetch( ...@@ -107,6 +131,7 @@ export async function createRouteTreePrefetch(
const didFindRootLayout = false const didFindRootLayout = false
return createFlightRouterStateFromLoaderTreeImpl( return createFlightRouterStateFromLoaderTreeImpl(
loaderTree, loaderTree,
hintTree,
getDynamicParamFromSegment, getDynamicParamFromSegment,
searchParams, searchParams,
didFindRootLayout didFindRootLayout
......
...@@ -40,7 +40,10 @@ export { RootLayoutBoundary } from '../../lib/framework/boundary-components' ...@@ -40,7 +40,10 @@ export { RootLayoutBoundary } from '../../lib/framework/boundary-components'
export { preloadStyle, preloadFont, preconnect } from './rsc/preloads' export { preloadStyle, preloadFont, preconnect } from './rsc/preloads'
export { Postpone } from './rsc/postpone' export { Postpone } from './rsc/postpone'
export { taintObjectReference } from './rsc/taint' export { taintObjectReference } from './rsc/taint'
export { collectSegmentData } from './collect-segment-data' export {
collectSegmentData,
collectPrefetchHints,
} from './collect-segment-data'
export const InstantValidation = () => { export const InstantValidation = () => {
if ( if (
......
...@@ -3,6 +3,7 @@ import type { ServerRuntime, SizeLimit } from '../../types' ...@@ -3,6 +3,7 @@ import type { ServerRuntime, SizeLimit } from '../../types'
import type { import type {
ExperimentalConfig, ExperimentalConfig,
NextConfigComplete, NextConfigComplete,
PrefetchInliningConfig,
} from '../../server/config-shared' } from '../../server/config-shared'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
...@@ -19,6 +20,7 @@ import type { BaseNextRequest } from '../base-http' ...@@ -19,6 +20,7 @@ import type { BaseNextRequest } from '../base-http'
import type { IncomingMessage } from 'http' import type { IncomingMessage } from 'http'
import type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache' import type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator' import type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'
import type { PrefetchHints } from '../../shared/lib/app-router-types'
const dynamicParamTypesSchema = s.enums([ const dynamicParamTypesSchema = s.enums([
'c', 'c',
...@@ -160,7 +162,7 @@ export interface RenderOptsPartial { ...@@ -160,7 +162,7 @@ export interface RenderOptsPartial {
dynamicOnHover: boolean dynamicOnHover: boolean
optimisticRouting: boolean optimisticRouting: boolean
inlineCss: boolean inlineCss: boolean
prefetchInlining: boolean prefetchInlining: PrefetchInliningConfig
authInterrupts: boolean authInterrupts: boolean
cachedNavigations: boolean cachedNavigations: boolean
...@@ -199,6 +201,12 @@ export interface RenderOptsPartial { ...@@ -199,6 +201,12 @@ export interface RenderOptsPartial {
*/ */
reactMaxHeadersLength: number | undefined 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 isStaticGeneration?: boolean
/** /**
......
...@@ -2,6 +2,7 @@ import type { ...@@ -2,6 +2,7 @@ import type {
FlightDataPath, FlightDataPath,
FlightDataSegment, FlightDataSegment,
FlightRouterState, FlightRouterState,
PrefetchHints,
Segment, Segment,
HeadData, HeadData,
} from '../../shared/lib/app-router-types' } from '../../shared/lib/app-router-types'
...@@ -37,6 +38,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -37,6 +38,7 @@ export async function walkTreeWithFlightRouterState({
ctx, ctx,
preloadCallbacks, preloadCallbacks,
MetadataOutlet, MetadataOutlet,
hintTree,
}: { }: {
loaderTreeToFilter: LoaderTree loaderTreeToFilter: LoaderTree
parentParams: { [key: string]: string | string[] } parentParams: { [key: string]: string | string[] }
...@@ -50,6 +52,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -50,6 +52,7 @@ export async function walkTreeWithFlightRouterState({
ctx: AppRenderContext ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
MetadataOutlet: React.ComponentType MetadataOutlet: React.ComponentType
hintTree: PrefetchHints | null
}): Promise<FlightDataPath[]> { }): Promise<FlightDataPath[]> {
const { const {
renderOpts: { nextFontManifest, experimental }, renderOpts: { nextFontManifest, experimental },
...@@ -151,10 +154,12 @@ export async function walkTreeWithFlightRouterState({ ...@@ -151,10 +154,12 @@ export async function walkTreeWithFlightRouterState({
? // Route tree prefetch requests contain some extra information ? // Route tree prefetch requests contain some extra information
await createRouteTreePrefetch( await createRouteTreePrefetch(
loaderTreeToFilter, loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment getDynamicParamFromSegment
) )
: await createFlightRouterStateFromLoaderTree( : await createFlightRouterStateFromLoaderTree(
loaderTreeToFilter, loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query
) )
...@@ -181,10 +186,12 @@ export async function walkTreeWithFlightRouterState({ ...@@ -181,10 +186,12 @@ export async function walkTreeWithFlightRouterState({
const routerState = parsedRequestHeaders.isRouteTreePrefetchRequest const routerState = parsedRequestHeaders.isRouteTreePrefetchRequest
? await createRouteTreePrefetch( ? await createRouteTreePrefetch(
loaderTreeToFilter, loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment getDynamicParamFromSegment
) )
: await createFlightRouterStateFromLoaderTree( : await createFlightRouterStateFromLoaderTree(
loaderTreeToFilter, loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query
) )
...@@ -212,6 +219,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -212,6 +219,7 @@ export async function walkTreeWithFlightRouterState({
const routerState = await createFlightRouterStateFromLoaderTree( const routerState = await createFlightRouterStateFromLoaderTree(
// Create router state using the slice of the loaderTree // Create router state using the slice of the loaderTree
loaderTreeToFilter, loaderTreeToFilter,
hintTree,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query
) )
...@@ -290,6 +298,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -290,6 +298,7 @@ export async function walkTreeWithFlightRouterState({
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
preloadCallbacks, preloadCallbacks,
MetadataOutlet, MetadataOutlet,
hintTree: hintTree?.slots?.[parallelRouteKey] ?? null,
}) })
for (const subPath of subPaths) { for (const subPath of subPaths) {
...@@ -329,10 +338,15 @@ export async function createFullTreeFlightDataForNavigation({ ...@@ -329,10 +338,15 @@ export async function createFullTreeFlightDataForNavigation({
renderOpts: { experimental }, renderOpts: { experimental },
query, query,
getDynamicParamFromSegment, getDynamicParamFromSegment,
pagePath,
} = ctx } = ctx
const hintTreeForInitialRender =
ctx.renderOpts.prefetchHints?.[pagePath] ?? null
const routerState = await createFlightRouterStateFromLoaderTree( const routerState = await createFlightRouterStateFromLoaderTree(
loaderTree, loaderTree,
hintTreeForInitialRender,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query query
) )
......
...@@ -584,6 +584,7 @@ export default abstract class Server< ...@@ -584,6 +584,7 @@ export default abstract class Server<
}, },
onInstrumentationRequestError: onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this), this.instrumentationOnRequestError.bind(this),
prefetchHints: {},
reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength, reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength,
logServerFunctions: logServerFunctions:
typeof this.nextConfig.logging === 'object' && typeof this.nextConfig.logging === 'object' &&
......
...@@ -224,7 +224,15 @@ export const experimentalSchema = { ...@@ -224,7 +224,15 @@ export const experimentalSchema = {
dynamicOnHover: z.boolean().optional(), dynamicOnHover: z.boolean().optional(),
optimisticRouting: z.boolean().optional(), optimisticRouting: z.boolean().optional(),
varyParams: 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(), disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(), disablePostcssPresetEnv: z.boolean().optional(),
cacheComponents: z.boolean().optional(), cacheComponents: z.boolean().optional(),
......
...@@ -16,6 +16,14 @@ import { INFINITE_CACHE } from '../lib/constants' ...@@ -16,6 +16,14 @@ import { INFINITE_CACHE } from '../lib/constants'
import { isStableBuild } from '../shared/lib/errors/canary-only-config-error' import { isStableBuild } from '../shared/lib/errors/canary-only-config-error'
import type { FallbackRouteParam } from '../build/static-paths/types' 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'>> & { export type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & {
images: Required<ImageConfigComplete> images: Required<ImageConfigComplete>
typescript: TypeScriptConfig typescript: TypeScriptConfig
...@@ -24,7 +32,10 @@ export type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & { ...@@ -24,7 +32,10 @@ export type NextConfigComplete = Required<Omit<NextConfig, 'configFile'>> & {
// override NextConfigComplete.experimental.htmlLimitedBots to string // override NextConfigComplete.experimental.htmlLimitedBots to string
// because it's not defined in NextConfigComplete.experimental // because it's not defined in NextConfigComplete.experimental
htmlLimitedBots: string | undefined 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` // 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 // since development builds use `{distDir}/dev`. This is used to ensure that the bundler doesn't
// traverse into the output directory. // traverse into the output directory.
...@@ -407,7 +418,12 @@ export interface ExperimentalConfig { ...@@ -407,7 +418,12 @@ export interface ExperimentalConfig {
dynamicOnHover?: boolean dynamicOnHover?: boolean
optimisticRouting?: boolean optimisticRouting?: boolean
varyParams?: boolean varyParams?: boolean
prefetchInlining?: boolean prefetchInlining?:
| boolean
| {
maxSize?: number
maxBundleSize?: number
}
preloadEntriesOnStart?: boolean preloadEntriesOnStart?: boolean
clientRouterFilter?: boolean clientRouterFilter?: boolean
clientRouterFilterRedirects?: boolean clientRouterFilterRedirects?: boolean
......
...@@ -380,6 +380,24 @@ function assignDefaultsAndValidate( ...@@ -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 // ensure correct default is set for api-resolver revalidate handling
if (!result.experimental.trustHostHeader && ciEnvironment.hasNextSupport) { if (!result.experimental.trustHostHeader && ciEnvironment.hasNextSupport) {
result.experimental.trustHostHeader = true result.experimental.trustHostHeader = true
......
...@@ -379,6 +379,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -379,6 +379,7 @@ export default class FileSystemCache implements CacheHandler {
status: data.status, status: data.status,
postponed: undefined, postponed: undefined,
segmentPaths: undefined, segmentPaths: undefined,
prefetchHints: undefined,
} }
writer.append( writer.append(
...@@ -432,6 +433,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -432,6 +433,7 @@ export default class FileSystemCache implements CacheHandler {
status: data.status, status: data.status,
postponed: data.postponed, postponed: data.postponed,
segmentPaths, segmentPaths,
prefetchHints: undefined,
} }
writer.append( writer.append(
......
...@@ -39,6 +39,7 @@ import { ...@@ -39,6 +39,7 @@ import {
PAGES_MANIFEST, PAGES_MANIFEST,
BUILD_ID_FILE, BUILD_ID_FILE,
MIDDLEWARE_MANIFEST, MIDDLEWARE_MANIFEST,
PREFETCH_HINTS,
PRERENDER_MANIFEST, PRERENDER_MANIFEST,
ROUTES_MANIFEST, ROUTES_MANIFEST,
CLIENT_PUBLIC_FILES_PATH, CLIENT_PUBLIC_FILES_PATH,
...@@ -111,6 +112,7 @@ import { formatDynamicImportPath } from '../lib/format-dynamic-import-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 type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite' import { isInterceptionRouteRewrite } from '../lib/is-interception-route-rewrite'
import type { ServerOnInstrumentationRequestError } from './app-render/types' import type { ServerOnInstrumentationRequestError } from './app-render/types'
import type { PrefetchHints } from '../shared/lib/app-router-types'
import { RouteKind } from './route-kind' import { RouteKind } from './route-kind'
import { InvariantError } from '../shared/lib/invariant-error' import { InvariantError } from '../shared/lib/invariant-error'
import { AwaiterOnce } from './after/awaiter' import { AwaiterOnce } from './after/awaiter'
...@@ -201,6 +203,10 @@ export default class NextNodeServer extends BaseServer< ...@@ -201,6 +203,10 @@ export default class NextNodeServer extends BaseServer<
installGlobalBehaviors(this.nextConfig) 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 const isDev = options.dev ?? false
this.isDev = isDev this.isDev = isDev
this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm) this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm)
...@@ -1906,6 +1912,28 @@ export default class NextNodeServer extends BaseServer< ...@@ -1906,6 +1912,28 @@ export default class NextNodeServer extends BaseServer<
return this._cachedPreviewManifest 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 { protected getRoutesManifest(): NormalizedRouteManifest | undefined {
return getTracer().trace( return getTracer().trace(
NextNodeServerSpan.getRoutesManifest, NextNodeServerSpan.getRoutesManifest,
......
import type { OutgoingHttpHeaders, ServerResponse } from 'http' import type { OutgoingHttpHeaders, ServerResponse } from 'http'
import type { CacheControl } from './lib/cache-control' import type { CacheControl } from './lib/cache-control'
import type { FetchMetrics } from './base-http' import type { FetchMetrics } from './base-http'
import type { PrefetchHints } from '../shared/lib/app-router-types'
import { import {
chainStreams, chainStreams,
...@@ -47,6 +48,13 @@ export type AppPageRenderResultMetadata = { ...@@ -47,6 +48,13 @@ export type AppPageRenderResultMetadata = {
segmentData?: Map<string, Buffer> 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 * 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 * is attached to the metadata so that it can be used during the render. When
......
...@@ -166,6 +166,18 @@ export const enum PrefetchHint { ...@@ -166,6 +166,18 @@ export const enum PrefetchHint {
SubtreeHasLoadingBoundary = 0b01000, SubtreeHasLoadingBoundary = 0b01000,
// This segment is the root layout of the application. // This segment is the root layout of the application.
IsRootLayout = 0b10000, 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 = ...@@ -239,6 +251,23 @@ export type FlightDataPath =
*/ */
export type FlightData = Array<FlightDataPath> | string 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 ActionResult = Promise<any>
export type InitialRSCPayload = { export type InitialRSCPayload = {
......
...@@ -95,6 +95,7 @@ export const NEXT_FONT_MANIFEST = 'next-font-manifest' ...@@ -95,6 +95,7 @@ export const NEXT_FONT_MANIFEST = 'next-font-manifest'
export const EXPORT_MARKER = 'export-marker.json' export const EXPORT_MARKER = 'export-marker.json'
export const EXPORT_DETAIL = 'export-detail.json' export const EXPORT_DETAIL = 'export-detail.json'
export const PRERENDER_MANIFEST = 'prerender-manifest.json' export const PRERENDER_MANIFEST = 'prerender-manifest.json'
export const PREFETCH_HINTS = 'prefetch-hints.json'
export const ROUTES_MANIFEST = 'routes-manifest.json' export const ROUTES_MANIFEST = 'routes-manifest.json'
export const IMAGES_MANIFEST = 'images-manifest.json' export const IMAGES_MANIFEST = 'images-manifest.json'
export const SERVER_FILES_MANIFEST = 'required-server-files' 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 Page() {
return <p>hello world</p>
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>
)
} }
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' ...@@ -6,11 +6,9 @@ import { useState } from 'react'
export function LinkAccordion({ export function LinkAccordion({
href, href,
children, children,
id,
}: { }: {
href: LinkProps['href'] href: LinkProps['href']
children: React.ReactNode children: React.ReactNode
id?: string
}) { }) {
const [isVisible, setIsVisible] = useState(false) const [isVisible, setIsVisible] = useState(false)
return ( return (
...@@ -19,7 +17,7 @@ export function LinkAccordion({ ...@@ -19,7 +17,7 @@ export function LinkAccordion({
type="checkbox" type="checkbox"
checked={isVisible} checked={isVisible}
onChange={() => setIsVisible(!isVisible)} onChange={() => setIsVisible(!isVisible)}
data-link-accordion={id ?? href} data-link-accordion={href}
/> />
{isVisible ? ( {isVisible ? (
<Link href={href}>{children}</Link> <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>
}
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