Unverified Commit 2ba73b7a authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix per-segment prefetching for initial loads with Cache Components (#90610)

The `S` field in the RSC payload was only set to `true` during static
generation, but the client used it to determine whether a route supports
per-segment prefetching (`isPPREnabled` on the route cache entry). For
partially static pages with Cache Components enabled, the initial HTML
is served via PPR resume, which generates the RSC payload at request
time with `isStaticGeneration` set to `false`. This caused `S` to be
`false` even though the route fully supports per-segment prefetching.

This caused the prefetch scheduler to fall back to the `LoadingBoundary`
fetch strategy instead of `PPR`, which skipped fetching
`_head.segment.rsc` and instead sent a `metadata-only` dynamic request.
That request returned a 404 locally (harmless) but a 200 with an empty
body on Vercel, which interfered with same-page navigation refreshes
introduced in #76223 and exposed by the route cache keying fix in
#90400.

To fix this, `S` is now also set to `true` when `cacheComponents` is
enabled, since all Cache Components routes support per-segment
prefetching. When Cache Components is disabled, `S` continues to rely
solely on `isStaticGeneration`, which is correct because fully static
pages always have both their RSC payload and per-segment prefetch
responses generated at build time.

This PR also renames `isPPREnabled` to `supportsPerSegmentPrefetching`
on the client and updates the `S` field comments in the RSC payload
types to better reflect the field's actual meaning.
parent 10725f84
......@@ -325,7 +325,7 @@ export async function hydrate(
initialCanonicalUrlParts: initialRSCPayload.c,
initialRenderedSearch: initialRSCPayload.q,
initialCouldBeIntercepted: initialRSCPayload.i,
initialPrerendered: initialRSCPayload.S,
initialSupportsPerSegmentPrefetching: initialRSCPayload.S,
location: window.location,
}),
instrumentationHooks
......
......@@ -16,7 +16,7 @@ export interface InitialRouterStateParameters {
initialRenderedSearch: string
initialFlightData: FlightDataPath[]
initialCouldBeIntercepted: boolean
initialPrerendered: boolean
initialSupportsPerSegmentPrefetching: boolean
location: Location | null
}
......@@ -26,7 +26,7 @@ export function createInitialRouterState({
initialCanonicalUrlParts,
initialRenderedSearch,
initialCouldBeIntercepted,
initialPrerendered,
initialSupportsPerSegmentPrefetching,
location,
}: InitialRouterStateParameters): AppRouterState {
// When initialized on the server, the canonical URL is provided as an array of parts.
......@@ -82,7 +82,7 @@ export function createInitialRouterState({
metadataVaryPath,
initialCouldBeIntercepted,
canonicalUrl,
initialPrerendered,
initialSupportsPerSegmentPrefetching,
false // hasDynamicRewrite
)
}
......
......@@ -68,7 +68,7 @@ type SpaFetchServerResponseResult = {
canonicalUrl: URL
renderedSearch: NormalizedSearch
couldBeIntercepted: boolean
prerendered: boolean
supportsPerSegmentPrefetching: boolean
postponed: boolean
staleTime: number
staticStageResponse: Promise<NavigationFlightResponse> | null
......@@ -281,7 +281,7 @@ export async function fetchServerResponse(
// wrong for interception routes.
renderedSearch: flightResponse.q as NormalizedSearch,
couldBeIntercepted: interception,
prerendered: flightResponse.S,
supportsPerSegmentPrefetching: flightResponse.S,
postponed,
staleTime,
staticStageResponse,
......
......@@ -1491,7 +1491,7 @@ function dispatchRetryDueToTreeMismatch(
metadataVaryPath,
false, // couldBeIntercepted - doesn't matter, we're just marking hasDynamicRewrite
createHrefFromUrl(retryUrl),
false, // isPPREnabled - doesn't matter, we're just marking hasDynamicRewrite
false, // supportsPerSegmentPrefetching - doesn't matter, we're just marking hasDynamicRewrite
true // hasDynamicRewrite
)
}
......
......@@ -200,7 +200,7 @@ export type PendingRouteCacheEntry = RouteCacheEntryShared & {
renderedSearch: null
tree: null
metadata: null
isPPREnabled: false
supportsPerSegmentPrefetching: false
}
type RejectedRouteCacheEntry = RouteCacheEntryShared & {
......@@ -210,7 +210,7 @@ type RejectedRouteCacheEntry = RouteCacheEntryShared & {
renderedSearch: null
tree: null
metadata: null
isPPREnabled: boolean
supportsPerSegmentPrefetching: boolean
}
export type FulfilledRouteCacheEntry = RouteCacheEntryShared & {
......@@ -220,7 +220,7 @@ export type FulfilledRouteCacheEntry = RouteCacheEntryShared & {
renderedSearch: NormalizedSearch
tree: RouteTree
metadata: RouteTree
isPPREnabled: boolean
supportsPerSegmentPrefetching: boolean
// When true, this entry should not be used as a template for route
// prediction. Set when we discover that the URL was rewritten by middleware
// to a different route structure (e.g., /foo was rewritten to /bar). Since
......@@ -510,7 +510,7 @@ function createDetachedRouteCacheEntry(): PendingRouteCacheEntry {
// from the server.
couldBeIntercepted: true,
// Similarly, we don't yet know if the route supports PPR.
isPPREnabled: false,
supportsPerSegmentPrefetching: false,
renderedSearch: null,
// Map-related fields
......@@ -660,7 +660,8 @@ export function deprecated_requestOptimisticRouteCacheEntry(
tree: optimisticRouteTree,
metadata: optimisticMetadataTree,
couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,
isPPREnabled: routeWithNoSearchParams.isPPREnabled,
supportsPerSegmentPrefetching:
routeWithNoSearchParams.supportsPerSegmentPrefetching,
hasDynamicRewrite: routeWithNoSearchParams.hasDynamicRewrite,
// Override the rendered search with the optimistic value.
......@@ -1057,7 +1058,7 @@ export function fulfillRouteCacheEntry(
metadataVaryPath: PageVaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
isPPREnabled: boolean
supportsPerSegmentPrefetching: boolean
): FulfilledRouteCacheEntry {
// Get the rendered search from the vary path
const renderedSearch =
......@@ -1074,7 +1075,7 @@ export function fulfillRouteCacheEntry(
fulfilledEntry.couldBeIntercepted = couldBeIntercepted
fulfilledEntry.canonicalUrl = canonicalUrl
fulfilledEntry.renderedSearch = renderedSearch
fulfilledEntry.isPPREnabled = isPPREnabled
fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching
fulfilledEntry.hasDynamicRewrite = false
pingBlockedTasks(entry)
return fulfilledEntry
......@@ -1088,7 +1089,7 @@ export function writeRouteIntoCache(
metadataVaryPath: PageVaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
isPPREnabled: boolean
supportsPerSegmentPrefetching: boolean
): FulfilledRouteCacheEntry {
const pendingEntry = createDetachedRouteCacheEntry()
const fulfilledEntry = fulfillRouteCacheEntry(
......@@ -1098,7 +1099,7 @@ export function writeRouteIntoCache(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled
supportsPerSegmentPrefetching
)
const renderedSearch = fulfilledEntry.renderedSearch
const varyPath = getFulfilledRouteVaryPath(
......
......@@ -370,7 +370,7 @@ async function navigateToUnknownRoute(
canonicalUrl,
renderedSearch,
couldBeIntercepted,
prerendered,
supportsPerSegmentPrefetching,
staticStageResponse,
responseHeaders,
debugInfo,
......@@ -401,7 +401,7 @@ async function navigateToUnknownRoute(
metadataVaryPath,
couldBeIntercepted,
createHrefFromUrl(canonicalUrl),
prerendered,
supportsPerSegmentPrefetching,
false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal
)
......
......@@ -177,7 +177,7 @@ export function discoverKnownRoute(
metadataVaryPath: PageVaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
isPPREnabled: boolean,
supportsPerSegmentPrefetching: boolean,
hasDynamicRewrite: boolean
): FulfilledRouteCacheEntry {
const tree = routeTree
......@@ -195,7 +195,7 @@ export function discoverKnownRoute(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled
supportsPerSegmentPrefetching
)
if (hasDynamicRewrite) {
fulfilledEntry.hasDynamicRewrite = true
......@@ -216,7 +216,7 @@ export function discoverKnownRoute(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled,
supportsPerSegmentPrefetching,
hasDynamicRewrite
)
return fulfilledEntry
......@@ -237,7 +237,7 @@ export function discoverKnownRoute(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled,
supportsPerSegmentPrefetching,
hasDynamicRewrite
)
}
......@@ -293,7 +293,7 @@ function discoverKnownRoutePart(
metadataVaryPath: PageVaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
isPPREnabled: boolean,
supportsPerSegmentPrefetching: boolean,
hasDynamicRewrite: boolean
): FulfilledRouteCacheEntry {
const segment = routeTree.segment
......@@ -334,7 +334,7 @@ function discoverKnownRoutePart(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled
supportsPerSegmentPrefetching
)
}
......@@ -413,7 +413,7 @@ function discoverKnownRoutePart(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled,
supportsPerSegmentPrefetching,
hasDynamicRewrite
)
// All parallel route branches share the same URL, so they should all
......@@ -436,7 +436,7 @@ function discoverKnownRoutePart(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled
supportsPerSegmentPrefetching
)
}
......@@ -466,7 +466,7 @@ function discoverKnownRoutePart(
metadataVaryPath,
couldBeIntercepted,
canonicalUrl,
isPPREnabled
supportsPerSegmentPrefetching
)
}
......@@ -557,7 +557,7 @@ export function matchKnownRoute(
tree: reifiedTree,
metadata: reifiedMetadata,
couldBeIntercepted: pattern.couldBeIntercepted,
isPPREnabled: pattern.isPPREnabled,
supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,
hasDynamicRewrite: false,
renderedSearch: search,
ref: null,
......
......@@ -727,7 +727,7 @@ function pingRootRouteTree(
// continue to work until you opt into `instant`.
fetchStrategy = FetchStrategy.PPR
} else if (task.fetchStrategy === FetchStrategy.PPR) {
fetchStrategy = route.isPPREnabled
fetchStrategy = route.supportsPerSegmentPrefetching
? FetchStrategy.PPR
: FetchStrategy.LoadingBoundary
} else {
......
......@@ -1645,7 +1645,11 @@ async function getRSCPayload(
],
m: missingSlots,
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
// Tells the client whether this route supports per-segment prefetching.
// With Cache Components, all routes support it. Without it, only fully
// static pages do, because their per-segment prefetch responses are
// generated during static generation (build or ISR).
S: workStore.isStaticGeneration || ctx.renderOpts.cacheComponents,
h: getMetadataVaryParamsThenable(),
})
}
......@@ -1771,7 +1775,11 @@ async function getErrorRSCPayload(
] as FlightDataPath,
],
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
// Tells the client whether this route supports per-segment prefetching.
// With Cache Components, all routes support it. Without it, only fully
// static pages do, because their per-segment prefetch responses are
// generated during static generation (build or ISR).
S: workStore.isStaticGeneration || ctx.renderOpts.cacheComponents,
h: getMetadataVaryParamsThenable(),
} satisfies InitialRSCPayload)
}
......@@ -1815,7 +1823,7 @@ function App<T>({
initialCanonicalUrlParts: response.c,
initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i,
initialPrerendered: response.S,
initialSupportsPerSegmentPrefetching: response.S,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
......@@ -1880,7 +1888,7 @@ function ErrorApp<T>({
initialCanonicalUrlParts: response.c,
initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i,
initialPrerendered: response.S,
initialSupportsPerSegmentPrefetching: response.S,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
......
......@@ -256,7 +256,7 @@ export type InitialRSCPayload = {
m: Set<string> | undefined
/** GlobalError */
G: [React.ComponentType<any>, React.ReactNode | undefined]
/** prerendered */
/** supportsPerSegmentPrefetching */
S: boolean
/**
* headVaryParams - vary params for the head (metadata) of the response.
......@@ -270,7 +270,7 @@ export type NavigationFlightResponse = {
b?: string
/** flightData */
f: FlightData
/** prerendered */
/** supportsPerSegmentPrefetching */
S: boolean
/** renderedSearch */
q: string
......
......@@ -3,7 +3,7 @@ import { createRouterAct } from 'router-act'
import { waitFor } from 'next-test-utils'
describe('segment cache (basic tests)', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
......@@ -277,75 +277,71 @@ describe('segment cache (basic tests)', () => {
expect(await dynamicDiv.innerHTML()).toBe('Dynamic page')
})
// TODO: Fix same-page navigation refresh behavior in deploy mode
;(isNextDeploy ? it.skip : it)(
'refreshes page segments when navigating to the exact same URL as the current location',
async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/same-page-nav', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
const linkWithNoHash = await browser.elementByCss(
'a[href="/same-page-nav"]'
)
const linkWithHashA = await browser.elementByCss(
'a[href="/same-page-nav#hash-a"]'
)
const linkWithHashB = await browser.elementByCss(
'a[href="/same-page-nav#hash-b"]'
)
async function readRandomNumberFromPage() {
const randomNumber = await browser.elementById('random-number')
return await randomNumber.textContent()
}
it('refreshes page segments when navigating to the exact same URL as the current location', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/same-page-nav', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
// Navigating to the same URL should refresh the page
const randomNumber = await readRandomNumberFromPage()
await act(async () => {
await linkWithNoHash.click()
}, [
{
includes: 'random-number',
},
{
// Only the page segments should be refreshed, not the layouts.
// TODO: We plan to change this in the future.
block: 'reject',
includes: 'same-page-nav-layout',
},
])
const randomNumber2 = await readRandomNumberFromPage()
expect(randomNumber2).not.toBe(randomNumber)
// Navigating to a different hash should *not* refresh the page
await act(async () => {
await linkWithHashA.click()
}, 'no-requests')
expect(await readRandomNumberFromPage()).toBe(randomNumber2)
// Navigating to the same hash again should refresh the page
await act(
async () => {
await linkWithHashA.click()
},
{
includes: 'random-number',
}
)
const randomNumber3 = await readRandomNumberFromPage()
expect(randomNumber3).not.toBe(randomNumber2)
// Navigating to a different hash should *not* refresh the page
await act(async () => {
await linkWithHashB.click()
}, 'no-requests')
expect(await readRandomNumberFromPage()).toBe(randomNumber3)
const linkWithNoHash = await browser.elementByCss(
'a[href="/same-page-nav"]'
)
const linkWithHashA = await browser.elementByCss(
'a[href="/same-page-nav#hash-a"]'
)
const linkWithHashB = await browser.elementByCss(
'a[href="/same-page-nav#hash-b"]'
)
async function readRandomNumberFromPage() {
const randomNumber = await browser.elementById('random-number')
return await randomNumber.textContent()
}
)
// Navigating to the same URL should refresh the page
const randomNumber = await readRandomNumberFromPage()
await act(async () => {
await linkWithNoHash.click()
}, [
{
includes: 'random-number',
},
{
// Only the page segments should be refreshed, not the layouts.
// TODO: We plan to change this in the future.
block: 'reject',
includes: 'same-page-nav-layout',
},
])
const randomNumber2 = await readRandomNumberFromPage()
expect(randomNumber2).not.toBe(randomNumber)
// Navigating to a different hash should *not* refresh the page
await act(async () => {
await linkWithHashA.click()
}, 'no-requests')
expect(await readRandomNumberFromPage()).toBe(randomNumber2)
// Navigating to the same hash again should refresh the page
await act(
async () => {
await linkWithHashA.click()
},
{
includes: 'random-number',
}
)
const randomNumber3 = await readRandomNumberFromPage()
expect(randomNumber3).not.toBe(randomNumber2)
// Navigating to a different hash should *not* refresh the page
await act(async () => {
await linkWithHashB.click()
}, 'no-requests')
expect(await readRandomNumberFromPage()).toBe(randomNumber3)
})
it('does not throw an error when navigating to a page with a server action', async () => {
let act: ReturnType<typeof createRouterAct>
......
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