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

Track vary params for segments without server-side param access (#88998)

Based on:

- https://github.com/vercel/next.js/pull/88834
- https://github.com/vercel/next.js/pull/88989

---

This implements a partial "vary params" optimization for the segment
cache. When a segment doesn't access params on the server, its
prefetched data can be reused across different param values.

Two cases are handled:
1. Segments without a user-provided layout (only loading.tsx or nothing)
2. Segments with a 'use client' layout

The server now includes a varyParams field in segment prefetch
responses. When varyParams is an empty Set, the client re-keys the cache
entry with Fallback for all param values, making it reusable across
different params.

This is a stepping stone toward full vary params tracking where Server
Components would track which specific params they access during
rendering.
parent 6adedb5e
...@@ -36,6 +36,7 @@ import { ...@@ -36,6 +36,7 @@ import {
type PartialSegmentVaryPath, type PartialSegmentVaryPath,
getRouteVaryPath, getRouteVaryPath,
getFulfilledRouteVaryPath, getFulfilledRouteVaryPath,
getFulfilledSegmentVaryPath,
getSegmentVaryPathForRequest, getSegmentVaryPathForRequest,
appendLayoutVaryPath, appendLayoutVaryPath,
finalizeLayoutVaryPath, finalizeLayoutVaryPath,
...@@ -1140,7 +1141,8 @@ function convertTreePrefetchToRouteTree( ...@@ -1140,7 +1141,8 @@ function convertTreePrefetchToRouteTree(
childPartialVaryPath = appendLayoutVaryPath( childPartialVaryPath = appendLayoutVaryPath(
partialVaryPath, partialVaryPath,
childParamKey childParamKey,
childSegmentName
) )
childSegment = [ childSegment = [
childSegmentName, childSegmentName,
...@@ -1309,7 +1311,12 @@ function convertFlightRouterStateToRouteTree( ...@@ -1309,7 +1311,12 @@ function convertFlightRouterStateToRouteTree(
if (Array.isArray(originalSegment)) { if (Array.isArray(originalSegment)) {
isPage = false isPage = false
const paramCacheKey = originalSegment[1] const paramCacheKey = originalSegment[1]
partialVaryPath = appendLayoutVaryPath(parentPartialVaryPath, paramCacheKey) const paramName = originalSegment[0]
partialVaryPath = appendLayoutVaryPath(
parentPartialVaryPath,
paramCacheKey,
paramName
)
varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath) varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)
segment = originalSegment segment = originalSegment
} else { } else {
...@@ -1804,13 +1811,36 @@ export async function fetchSegmentOnCacheMiss( ...@@ -1804,13 +1811,36 @@ export async function fetchSegmentOnCacheMiss(
return null return null
} }
const staleAt = Date.now() + getStaleTimeMs(serverData.staleTime) const staleAt = Date.now() + getStaleTimeMs(serverData.staleTime)
const fulfilledEntry = fulfillSegmentCacheEntry(
segmentCacheEntry,
serverData.rsc,
staleAt,
serverData.isPartial
)
// If the server tells us which params the segment varies by, we can re-key
// the entry to a more generic vary path. This allows the entry to be reused
// across different param values for params that the segment doesn't
// actually depend on.
const varyParams = serverData.varyParams
if (varyParams !== null) {
// Re-key the entry by storing it at a more generic vary path where
// unused params are replaced with Fallback.
const fulfilledVaryPath = getFulfilledSegmentVaryPath(
tree.varyPath,
varyParams
)
const isRevalidation = false
setInCacheMap(
segmentCacheMap,
fulfilledVaryPath,
fulfilledEntry,
isRevalidation
)
}
return { return {
value: fulfillSegmentCacheEntry( value: fulfilledEntry,
segmentCacheEntry,
serverData.rsc,
staleAt,
serverData.isPartial
),
// Return a promise that resolves when the network connection closes, so // Return a promise that resolves when the network connection closes, so
// the scheduler can track the number of concurrent network connections. // the scheduler can track the number of concurrent network connections.
closed: closed.promise, closed: closed.promise,
......
...@@ -681,6 +681,7 @@ function convertServerPatchToFullTreeImpl( ...@@ -681,6 +681,7 @@ function convertServerPatchToFullTreeImpl(
null, null,
isEmptySeedDataPartial, isEmptySeedDataPartial,
false, false,
null,
] ]
return { return {
......
...@@ -26,6 +26,16 @@ type Opaque<T, K> = T & { __brand: K } ...@@ -26,6 +26,16 @@ type Opaque<T, K> = T & { __brand: K }
* string, and Next-URL header. * string, and Next-URL header.
*/ */
export type VaryPath = { export type VaryPath = {
/**
* Identifies which param this vary path node corresponds to. Used by
* getFulfilledSegmentVaryPath to determine which params to replace with
* Fallback based on the varyParams set from the server.
*
* - For path params: the param name (e.g., 'slug')
* - For search params: '?'
* - For non-param nodes (request keys, etc.): null
*/
id: string | null
value: string | null | FallbackType value: string | null | FallbackType
parent: VaryPath | null parent: VaryPath | null
} }
...@@ -37,10 +47,13 @@ export type VaryPath = { ...@@ -37,10 +47,13 @@ export type VaryPath = {
// requestKey -> searchParams -> nextUrl // requestKey -> searchParams -> nextUrl
export type RouteVaryPath = Opaque< export type RouteVaryPath = Opaque<
{ {
id: null
value: NormalizedPathname value: NormalizedPathname
parent: { parent: {
id: '?'
value: NormalizedSearch value: NormalizedSearch
parent: { parent: {
id: null
value: NormalizedNextUrl | null | FallbackType value: NormalizedNextUrl | null | FallbackType
parent: null parent: null
} }
...@@ -52,6 +65,7 @@ export type RouteVaryPath = Opaque< ...@@ -52,6 +65,7 @@ export type RouteVaryPath = Opaque<
// requestKey -> pathParams // requestKey -> pathParams
export type LayoutVaryPath = Opaque< export type LayoutVaryPath = Opaque<
{ {
id: null
value: string value: string
parent: PartialSegmentVaryPath | null parent: PartialSegmentVaryPath | null
}, },
...@@ -61,8 +75,10 @@ export type LayoutVaryPath = Opaque< ...@@ -61,8 +75,10 @@ export type LayoutVaryPath = Opaque<
// requestKey -> searchParams -> pathParams // requestKey -> searchParams -> pathParams
export type PageVaryPath = Opaque< export type PageVaryPath = Opaque<
{ {
id: null
value: string value: string
parent: { parent: {
id: '?'
value: NormalizedSearch | FallbackType value: NormalizedSearch | FallbackType
parent: PartialSegmentVaryPath | null parent: PartialSegmentVaryPath | null
} }
...@@ -83,10 +99,13 @@ export function getRouteVaryPath( ...@@ -83,10 +99,13 @@ export function getRouteVaryPath(
): RouteVaryPath { ): RouteVaryPath {
// requestKey -> searchParams -> nextUrl // requestKey -> searchParams -> nextUrl
const varyPath: VaryPath = { const varyPath: VaryPath = {
id: null,
value: pathname, value: pathname,
parent: { parent: {
id: '?',
value: search, value: search,
parent: { parent: {
id: null,
value: nextUrl, value: nextUrl,
parent: null, parent: null,
}, },
...@@ -105,10 +124,13 @@ export function getFulfilledRouteVaryPath( ...@@ -105,10 +124,13 @@ export function getFulfilledRouteVaryPath(
// re-keyed based on which inputs the response varies by. // re-keyed based on which inputs the response varies by.
// requestKey -> searchParams -> nextUrl // requestKey -> searchParams -> nextUrl
const varyPath: VaryPath = { const varyPath: VaryPath = {
id: null,
value: pathname, value: pathname,
parent: { parent: {
id: '?',
value: search, value: search,
parent: { parent: {
id: null,
value: couldBeIntercepted ? nextUrl : Fallback, value: couldBeIntercepted ? nextUrl : Fallback,
parent: null, parent: null,
}, },
...@@ -119,9 +141,11 @@ export function getFulfilledRouteVaryPath( ...@@ -119,9 +141,11 @@ export function getFulfilledRouteVaryPath(
export function appendLayoutVaryPath( export function appendLayoutVaryPath(
parentPath: PartialSegmentVaryPath | null, parentPath: PartialSegmentVaryPath | null,
cacheKey: string cacheKey: string,
paramName: string
): PartialSegmentVaryPath { ): PartialSegmentVaryPath {
const varyPathPart: VaryPath = { const varyPathPart: VaryPath = {
id: paramName,
value: cacheKey, value: cacheKey,
parent: parentPath, parent: parentPath,
} }
...@@ -133,6 +157,7 @@ export function finalizeLayoutVaryPath( ...@@ -133,6 +157,7 @@ export function finalizeLayoutVaryPath(
varyPath: PartialSegmentVaryPath | null varyPath: PartialSegmentVaryPath | null
): LayoutVaryPath { ): LayoutVaryPath {
const layoutVaryPath: VaryPath = { const layoutVaryPath: VaryPath = {
id: null,
value: requestKey, value: requestKey,
parent: varyPath, parent: varyPath,
} }
...@@ -154,8 +179,10 @@ export function finalizePageVaryPath( ...@@ -154,8 +179,10 @@ export function finalizePageVaryPath(
// Unlike layouts, a page segment's vary path also includes the search string. // Unlike layouts, a page segment's vary path also includes the search string.
// requestKey -> searchParams -> pathParams // requestKey -> searchParams -> pathParams
const pageVaryPath: VaryPath = { const pageVaryPath: VaryPath = {
id: null,
value: requestKey, value: requestKey,
parent: { parent: {
id: '?',
value: renderedSearch, value: renderedSearch,
parent: varyPath, parent: varyPath,
}, },
...@@ -201,11 +228,13 @@ export function finalizeMetadataVaryPath( ...@@ -201,11 +228,13 @@ export function finalizeMetadataVaryPath(
// different parallel pages are things like route groups and parallel // different parallel pages are things like route groups and parallel
// route slots. As long as it's always the same one, it doesn't matter. // route slots. As long as it's always the same one, it doesn't matter.
const pageVaryPath: VaryPath = { const pageVaryPath: VaryPath = {
id: null,
// Append the actual metadata request key to the page request key. Note // Append the actual metadata request key to the page request key. Note
// that we're not using a separate vary path part; it's unnecessary because // that we're not using a separate vary path part; it's unnecessary because
// these are not conceptually separate inputs. // these are not conceptually separate inputs.
value: pageRequestKey + HEAD_REQUEST_KEY, value: pageRequestKey + HEAD_REQUEST_KEY,
parent: { parent: {
id: '?',
value: renderedSearch, value: renderedSearch,
parent: varyPath, parent: varyPath,
}, },
...@@ -261,8 +290,10 @@ export function getSegmentVaryPathForRequest( ...@@ -261,8 +290,10 @@ export function getSegmentVaryPathForRequest(
const searchParamsVaryPath = (originalVaryPath as PageVaryPath).parent const searchParamsVaryPath = (originalVaryPath as PageVaryPath).parent
const pathParamsVaryPath = searchParamsVaryPath.parent const pathParamsVaryPath = searchParamsVaryPath.parent
const patchedVaryPath: VaryPath = { const patchedVaryPath: VaryPath = {
id: null,
value: originalVaryPath.value, value: originalVaryPath.value,
parent: { parent: {
id: '?',
value: Fallback, value: Fallback,
parent: pathParamsVaryPath, parent: pathParamsVaryPath,
}, },
...@@ -283,8 +314,10 @@ export function clonePageVaryPathWithNewSearchParams( ...@@ -283,8 +314,10 @@ export function clonePageVaryPathWithNewSearchParams(
// ^ This part gets replaced with newSearch // ^ This part gets replaced with newSearch
const searchParamsVaryPath = originalVaryPath.parent const searchParamsVaryPath = originalVaryPath.parent
const clonedVaryPath: VaryPath = { const clonedVaryPath: VaryPath = {
id: null,
value: originalVaryPath.value, value: originalVaryPath.value,
parent: { parent: {
id: '?',
value: newSearch, value: newSearch,
parent: searchParamsVaryPath.parent, parent: searchParamsVaryPath.parent,
}, },
...@@ -300,3 +333,32 @@ export function getRenderedSearchFromVaryPath( ...@@ -300,3 +333,32 @@ export function getRenderedSearchFromVaryPath(
? (searchParams as NormalizedSearch) ? (searchParams as NormalizedSearch)
: null : null
} }
export function getFulfilledSegmentVaryPath(
original: VaryPath,
varyParams: Set<string>
): SegmentVaryPath {
// Re-keys a segment's vary path based on which params the segment actually
// depends on. Params that are NOT in the varyParams set are replaced with
// Fallback, allowing the cache entry to be reused across different values of
// those params.
// This is called when a segment is fulfilled with data from the server. The
// varyParams set comes from the server and indicates which params were
// accessed during rendering.
const clone: VaryPath = {
id: original.id,
// If the id is null, this node is not a param (e.g., it's a request key).
// If the id is in the varyParams set, keep the original value.
// Otherwise, replace with Fallback to make it reusable.
value:
original.id === null || varyParams.has(original.id)
? original.value
: Fallback,
parent:
original.parent === null
? null
: getFulfilledSegmentVaryPath(original.parent, varyParams),
}
return clone as SegmentVaryPath
}
...@@ -1651,6 +1651,7 @@ async function getErrorRSCPayload( ...@@ -1651,6 +1651,7 @@ async function getErrorRSCPayload(
null, null,
false, false,
false, // We don't currently support runtime prefetching for error pages. false, // We don't currently support runtime prefetching for error pages.
null, // varyParams - not tracked for error pages
] ]
const { GlobalError, styles: globalErrorStyles } = await getGlobalErrorStyles( const { GlobalError, styles: globalErrorStyles } = await getGlobalErrorStyles(
......
...@@ -81,6 +81,16 @@ export type SegmentPrefetch = { ...@@ -81,6 +81,16 @@ export type SegmentPrefetch = {
rsc: React.ReactNode | null rsc: React.ReactNode | null
isPartial: boolean isPartial: boolean
staleTime: number staleTime: number
/**
* The set of params that this segment's output depends on. Used by the client
* cache to determine which entries can be reused across different param
* values.
* - `null` means vary params were not tracked (conservative: assume all
* params matter)
* - Empty set means no params were accessed (segment is reusable for any
* param values)
*/
varyParams: Set<string> | null
} }
const filterStackFrame = const filterStackFrame =
...@@ -260,6 +270,9 @@ async function PrefetchTreeData({ ...@@ -260,6 +270,9 @@ async function PrefetchTreeData({
staleTime, staleTime,
head, head,
HEAD_REQUEST_KEY, HEAD_REQUEST_KEY,
// TODO: Track vary params for metadata. For now, assume all
// params vary.
null,
clientModules clientModules
) )
) )
...@@ -323,6 +336,7 @@ function collectSegmentDataImpl( ...@@ -323,6 +336,7 @@ function collectSegmentDataImpl(
} }
const hasRuntimePrefetch = seedData !== null ? seedData[4] : false const hasRuntimePrefetch = seedData !== null ? seedData[4] : false
const varyParams = seedData !== null ? seedData[5] : null
if (seedData !== null) { if (seedData !== null) {
// Spawn a task to write the segment data to a new Flight stream. // Spawn a task to write the segment data to a new Flight stream.
...@@ -335,6 +349,7 @@ function collectSegmentDataImpl( ...@@ -335,6 +349,7 @@ function collectSegmentDataImpl(
staleTime, staleTime,
seedData[0], seedData[0],
requestKey, requestKey,
varyParams,
clientModules clientModules
) )
) )
...@@ -380,6 +395,7 @@ async function renderSegmentPrefetch( ...@@ -380,6 +395,7 @@ async function renderSegmentPrefetch(
staleTime: number, staleTime: number,
rsc: React.ReactNode, rsc: React.ReactNode,
requestKey: SegmentRequestKey, requestKey: SegmentRequestKey,
varyParams: Set<string> | null,
clientModules: ManifestNode clientModules: ManifestNode
): Promise<[SegmentRequestKey, Buffer]> { ): Promise<[SegmentRequestKey, Buffer]> {
// Render the segment data to a stream. // Render the segment data to a stream.
...@@ -388,6 +404,7 @@ async function renderSegmentPrefetch( ...@@ -388,6 +404,7 @@ async function renderSegmentPrefetch(
rsc, rsc,
isPartial: await isPartialRSCData(rsc, clientModules), isPartial: await isPartialRSCData(rsc, clientModules),
staleTime, staleTime,
varyParams,
} }
// Since all we're doing is decoding and re-encoding a cached prerender, if // Since all we're doing is decoding and re-encoding a cached prerender, if
// it takes longer than a microtask, it must because of hanging promises // it takes longer than a microtask, it must because of hanging promises
......
...@@ -672,6 +672,8 @@ async function createComponentTreeInternal( ...@@ -672,6 +672,8 @@ async function createComponentTreeInternal(
// When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component // When the segment does not have a layout or page we still have to add the layout router to ensure the path holds the loading component
if (!MaybeComponent) { if (!MaybeComponent) {
// No user-provided component at this level, so no params are accessed.
const emptyVaryParams = new Set<string>()
return createSeedData( return createSeedData(
ctx, ctx,
createElement( createElement(
...@@ -685,7 +687,8 @@ async function createComponentTreeInternal( ...@@ -685,7 +687,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch hasRuntimePrefetch,
emptyVaryParams
) )
} }
...@@ -706,6 +709,8 @@ async function createComponentTreeInternal( ...@@ -706,6 +709,8 @@ async function createComponentTreeInternal(
workStore.forceDynamic && workStore.forceDynamic &&
experimental.isRoutePPREnabled experimental.isRoutePPREnabled
) { ) {
// force-dynamic segments can't have their vary params tracked
const unknownVaryParams = null
return createSeedData( return createSeedData(
ctx, ctx,
createElement( createElement(
...@@ -722,12 +727,23 @@ async function createComponentTreeInternal( ...@@ -722,12 +727,23 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
true, true,
hasRuntimePrefetch hasRuntimePrefetch,
unknownVaryParams
) )
} }
const isClientComponent = isClientReference(layoutOrPageMod) const isClientComponent = isClientReference(layoutOrPageMod)
const varyParams =
isClientComponent && cacheComponents
? // Client components with Cache Components enabled don't receive params
// from the server, so they have an empty vary params set.
new Set<string>()
: // TODO: Server segments don't yet track which params are accessed.
// So for now we must assume that all params may vary (null represents
// unknown vary params, not an empty set).
null
if ( if (
process.env.NODE_ENV === 'development' && process.env.NODE_ENV === 'development' &&
'params' in parallelRouteProps 'params' in parallelRouteProps
...@@ -835,7 +851,8 @@ async function createComponentTreeInternal( ...@@ -835,7 +851,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch hasRuntimePrefetch,
varyParams
) )
} else { } else {
const SegmentComponent = Component const SegmentComponent = Component
...@@ -1048,7 +1065,8 @@ async function createComponentTreeInternal( ...@@ -1048,7 +1065,8 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData, parallelRouteCacheNodeSeedData,
loadingData, loadingData,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch hasRuntimePrefetch,
varyParams
) )
} }
} }
...@@ -1199,7 +1217,8 @@ function createSeedData( ...@@ -1199,7 +1217,8 @@ function createSeedData(
parallelRoutes: Record<string, CacheNodeSeedData | null>, parallelRoutes: Record<string, CacheNodeSeedData | null>,
loading: LoadingModuleData | null, loading: LoadingModuleData | null,
isPossiblyPartialResponse: boolean, isPossiblyPartialResponse: boolean,
hasRuntimePrefetch: boolean hasRuntimePrefetch: boolean,
varyParams: Set<string> | null
): CacheNodeSeedData { ): CacheNodeSeedData {
if (loading !== null) { if (loading !== null) {
// If a loading.tsx boundary is present, wrap the component data in an // If a loading.tsx boundary is present, wrap the component data in an
...@@ -1220,5 +1239,6 @@ function createSeedData( ...@@ -1220,5 +1239,6 @@ function createSeedData(
null, null,
isPossiblyPartialResponse, isPossiblyPartialResponse,
hasRuntimePrefetch, hasRuntimePrefetch,
varyParams,
] ]
} }
...@@ -193,6 +193,17 @@ export type CacheNodeSeedData = [ ...@@ -193,6 +193,17 @@ export type CacheNodeSeedData = [
isPartial: boolean, isPartial: boolean,
/** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */ /** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */
hasRuntimePrefetch: boolean, hasRuntimePrefetch: boolean,
/**
* The set of params that this segment's server-rendered output depends on.
* Used by the client cache to determine which entries can be reused across
* different param values.
*
* - `null` means vary params were not tracked (conservative: assume all
* params vary)
* - Empty set means no params were accessed (segment is reusable for any
* param values)
*/
varyParams: Set<string> | null,
] ]
export type FlightDataSegment = [ export type FlightDataSegment = [
......
'use client'
/**
* This is a client component layout. Even though it has access to params via
* the props, it doesn't access them on the server during rendering. This means
* the segment's varyParams should be an empty set, allowing the prefetched
* data to be reused across different param values.
*/
export default function ClientLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div data-client-layout="true">
<div>Client Layout (use client)</div>
{children}
</div>
)
}
export default function Loading() {
return <div data-loading="client-layout">Loading client layout...</div>
}
type Params = { param: string }
export async function generateStaticParams(): Promise<Params[]> {
return [{ param: 'aaa' }, { param: 'bbb' }]
}
export default async function Page({ params }: { params: Promise<Params> }) {
const { param } = await params
return (
<div id="client-layout-param-page">
<div data-param={param}>Param value: {param}</div>
</div>
)
}
import { LinkAccordion } from '../../components/link-accordion'
export default function ClientLayoutIndexPage() {
return (
<div id="client-layout-index">
<h1>Client Layout Index</h1>
<ul>
<li>
<LinkAccordion href="/client-layout/aaa">Link to aaa</LinkAccordion>
</li>
<li>
<LinkAccordion href="/client-layout/bbb">Link to bbb</LinkAccordion>
</li>
</ul>
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Loading() {
return <div data-loading="true">Loading [param]...</div>
}
type Params = { param: string }
export async function generateStaticParams(): Promise<Params[]> {
return [{ param: 'aaa' }, { param: 'bbb' }]
}
export default async function Page({ params }: { params: Promise<Params> }) {
const { param } = await params
return (
<div id="param-page">
<div data-param={param}>Param value: {param}</div>
</div>
)
}
import { LinkAccordion } from '../../components/link-accordion'
export default function StaticPage() {
return (
<div id="index-page">
<h1>Index Page</h1>
<ul>
<li>
<LinkAccordion href="/static/aaa">Link to aaa</LinkAccordion>
</li>
<li>
<LinkAccordion href="/static/bbb">Link to bbb</LinkAccordion>
</li>
</ul>
</div>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children?: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
const displayChildren = children !== undefined ? children : href
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{displayChildren}
</Link>
) : (
<>{displayChildren} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
/**
* Tests for the "vary params" optimization. Segments that don't access params
* on the server can have their prefetched data reused across different param
* values. This includes:
*
* 1. Segments without a user-provided layout (only loading.tsx or nothing)
* 2. Segments with a 'use client' layout (client components don't run on server)
*/
describe('segment cache - vary params', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('prefetching is disabled in dev mode', () => {})
return
}
it('reuses prefetched segment when there is no user-provided layout', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/static', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Prefetch the first link (/static/aaa). This will populate the segment
// cache with the [param] segment's loading boundary.
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/static/aaa"]'
)
await toggle.click()
})
// Now prefetch the second link (/static/bbb). Because the [param] segment
// has no user-provided layout (only loading.tsx), its varyParams is an
// empty set. This means the segment data from /static/aaa is re-keyed with
// Fallback and should be reused for /static/bbb.
//
// We should NOT see a new prefetch request for the [param] segment's
// loading boundary - only the page content should be fetched.
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/static/bbb"]'
)
await toggle.click()
},
// The loading boundary content should NOT be re-fetched because the
// segment shell is reused from the /static/aaa prefetch.
{ includes: 'Loading [param]', block: 'reject' }
)
// Navigate to /static/bbb and verify it works. Since all the data is
// prefetched, there should be no additional requests during navigation.
await act(async () => {
const link = await browser.elementByCss('a[href="/static/bbb"]')
await link.click()
}, 'no-requests')
// Verify the final page content
const paramPage = await browser.elementById('param-page')
expect(await paramPage.text()).toContain('Param value: bbb')
})
it("reuses prefetched segment when layout is marked with 'use client'", async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/client-layout', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Prefetch the first link (/client-layout/aaa). This will populate the
// segment cache with the [param] segment's client layout.
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/client-layout/aaa"]'
)
await toggle.click()
})
// Now prefetch the second link (/client-layout/bbb). Because the [param]
// segment has a 'use client' layout, it doesn't access params on the
// server, so its varyParams is an empty set. The segment data from
// /client-layout/aaa should be reused for /client-layout/bbb.
//
// We should NOT see a new prefetch request for the [param] segment's
// layout - only the page content should be fetched.
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/client-layout/bbb"]'
)
await toggle.click()
},
// The client layout content should NOT be re-fetched because the segment
// is reused from the /client-layout/aaa prefetch.
{ includes: 'Client Layout (use client)', block: 'reject' }
)
// Navigate to /client-layout/bbb and verify it works. Since all the data
// is prefetched, there should be no additional requests during navigation.
await act(async () => {
const link = await browser.elementByCss('a[href="/client-layout/bbb"]')
await link.click()
}, 'no-requests')
// Verify the final page content
const paramPage = await browser.elementById('client-layout-param-page')
expect(await paramPage.text()).toContain('Param value: bbb')
})
})
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