Unverified Commit 1d14e93c authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Cached Navigations: Cache visited fully static pages in the segment cache (#90306)

When a fully static page is loaded (via initial HTML or client-side
navigation), the segments are now written into the segment cache so
subsequent navigations can be served entirely from cache without server
requests.

Initial HTML: The RSC payload inlined in the HTML is written during
hydration via `getStaleAt` + `writeStaticStageResponseIntoCache` with
`isResponsePartial: false`, using `FetchStrategy.Full` since all
segments are present. A `StaleTimeIterable` (`s` field) is included in
the `InitialRSCPayload` during the Cache Components prerender path to
provide the stale time.

Navigation: The `isResponsePartial` flag from the prepended byte
(stripped by `processFetch`) is now also used to determine how segments
from `writeStaticStageResponseIntoCache` are cached. For fully static
routes (`isResponsePartial: false`), segments are written as non-partial
so no dynamic follow-up is needed.

The route tree used for cache writes is now always derived from the
Flight data itself (via `convertServerPatchToFullTree`), rather than
from a pre-existing route cache entry. This guarantees the tree stays in
sync with the response and avoids key mismatches between the static
stage tree and the per-segment prefetch tree for parallel route slots.

When writing the head into the cache, `isHeadPartial` from the server is
overridden to `false` for non-partial responses, but only when Cache
Components is enabled. This corrects the server's conservative
`isPossiblyPartialHead` marking during static generation. Without Cache
Components, the server already sends the correct value. Responses
without a recognized marker byte (e.g. regular navigations that don't go
through the prerender path) are conservatively treated as partial.

Partially static pages (where the static stage needs to be extracted via
byte-level truncation of the initial HTML Flight stream) will be handled
in a follow-up.

---------
Co-authored-by: 's avatarAndrew Clark <git@andrewclark.io>
parent e4cae370
......@@ -1085,5 +1085,6 @@
"1084": "Route \"%s\": Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route",
"1085": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata",
"1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport",
"1087": "Failed to parse \"%s\":\\n%s%s"
"1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body"
}
......@@ -326,6 +326,8 @@ export async function hydrate(
initialRenderedSearch: initialRSCPayload.q,
initialCouldBeIntercepted: initialRSCPayload.i,
initialSupportsPerSegmentPrefetching: initialRSCPayload.S,
initialStaleTime: initialRSCPayload.s,
initialHeadVaryParams: initialRSCPayload.h,
location: window.location,
}),
instrumentationHooks
......
import type { FlightDataPath } from '../../../shared/lib/app-router-types'
import type { VaryParamsThenable } from '../../../shared/lib/segment-cache/vary-params-decoding'
import { createHrefFromUrl } from './create-href-from-url'
import { extractPathFromFlightRouterState } from './compute-changed-path'
......@@ -6,7 +7,11 @@ import { extractPathFromFlightRouterState } from './compute-changed-path'
import type { AppRouterState } from './router-reducer-types'
import { getFlightDataPartsFromPath } from '../../flight-data-helpers'
import { createInitialCacheNodeForHydration } from './ppr-navigations'
import { convertRootFlightRouterStateToRouteTree } from '../segment-cache/cache'
import {
convertRootFlightRouterStateToRouteTree,
getStaleAt,
writeStaticStageResponseIntoCache,
} from '../segment-cache/cache'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import type { NormalizedSearch } from '../segment-cache/cache-key'
......@@ -17,6 +22,8 @@ export interface InitialRouterStateParameters {
initialFlightData: FlightDataPath[]
initialCouldBeIntercepted: boolean
initialSupportsPerSegmentPrefetching: boolean
initialStaleTime: AsyncIterable<number> | undefined
initialHeadVaryParams: VaryParamsThenable | null
location: Location | null
}
......@@ -27,6 +34,8 @@ export function createInitialRouterState({
initialRenderedSearch,
initialCouldBeIntercepted,
initialSupportsPerSegmentPrefetching,
initialStaleTime,
initialHeadVaryParams,
location,
}: InitialRouterStateParameters): AppRouterState {
// When initialized on the server, the canonical URL is provided as an array of parts.
......@@ -51,7 +60,7 @@ export function createInitialRouterState({
createHrefFromUrl(location)
: initialCanonicalUrl
// Conver the initial FlightRouterState into the RouteTree type.
// Convert the initial FlightRouterState into the RouteTree type.
// NOTE: The metadataVaryPath isn't used for anything currently because the
// head is embedded into the CacheNode tree, but eventually we'll lift it out
// and store it on the top-level state object.
......@@ -69,10 +78,10 @@ export function createInitialRouterState({
initialHead
)
// Learn the route pattern so we can predict it for future navigations.
// Only do this in the browser (location !== null) since route learning
// state doesn't persist from SSR to client.
// The following only applies in the browser (location !== null) since neither
// route learning nor segment cache state persists from SSR to client.
if (location !== null && metadataVaryPath !== null) {
// Learn the route pattern so we can predict it for future navigations.
discoverKnownRoute(
Date.now(),
location.pathname,
......@@ -85,6 +94,31 @@ export function createInitialRouterState({
initialSupportsPerSegmentPrefetching,
false // hasDynamicRewrite
)
// Write the initial seed data into the segment cache so subsequent
// navigations to the initial page can serve cached segments instantly.
if (initialSeedData !== null && initialStaleTime !== undefined) {
// Currently only fully static pages include initialStaleTime.
const now = Date.now()
getStaleAt(now, initialStaleTime)
.then((staleAt) => {
writeStaticStageResponseIntoCache(
now,
initialFlightData,
undefined, // buildId — not applicable for initial HTML
initialHeadVaryParams,
staleAt,
initialTree,
initialRenderedSearch,
false // isResponsePartial
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the page
// rendered normally, we just won't write into the cache.
})
}
}
// NOTE: We intentionally don't check if any data needs to be fetched from the
......
......@@ -41,6 +41,7 @@ import type { NormalizedSearch } from '../segment-cache/cache-key'
import { getDeploymentId } from '../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { stripIsPartialByte } from '../segment-cache/cache'
const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
......@@ -63,6 +64,11 @@ export interface FetchServerResponseOptions {
readonly isHmrRefresh?: boolean
}
export type StaticStageData = {
readonly response: NavigationFlightResponse
readonly isResponsePartial: boolean
}
type SpaFetchServerResponseResult = {
flightData: NormalizedFlightData[]
canonicalUrl: URL
......@@ -71,7 +77,7 @@ type SpaFetchServerResponseResult = {
supportsPerSegmentPrefetching: boolean
postponed: boolean
staleTime: number
staticStageResponse: Promise<NavigationFlightResponse> | null
staticStageData: StaticStageData | null
responseHeaders: Headers
debugInfo: Array<any> | null
}
......@@ -236,7 +242,10 @@ export async function fetchServerResponse(
)
}
const flightResponse = await flightResponsePromise
const [flightResponse, cacheData] = await Promise.all([
flightResponsePromise,
res.cacheData,
])
if (
(res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==
......@@ -251,19 +260,10 @@ export async function fetchServerResponse(
return doMpaNavigation(normalizedFlightData)
}
// If the server included a static stage byte count, decode the static
// stage from the cloned response body to seed the segment cache.
let staticStageResponse: Promise<NavigationFlightResponse> | null = null
if (flightResponse.l !== undefined && res.staticStageBodyPromise !== null) {
staticStageResponse = decodeStaticStageResponse(
flightResponse.l,
res.staticStageBodyPromise,
headers
)
} else if (res.staticStageBodyPromise !== null) {
// No static stage byte count — cancel the unused clone.
res.staticStageBodyPromise.then((body) => body?.cancel())
}
const staticStageData =
cacheData !== null
? await resolveStaticStageData(cacheData, flightResponse, headers)
: null
return {
flightData: normalizedFlightData,
......@@ -280,7 +280,7 @@ export async function fetchServerResponse(
supportsPerSegmentPrefetching: flightResponse.S,
postponed,
staleTime,
staticStageResponse,
staticStageData,
responseHeaders: res.headers,
debugInfo: flightResponsePromise._debugInfo ?? null,
}
......@@ -312,7 +312,109 @@ export type RSCResponse<T> = {
status: number
url: string
flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null
staticStageBodyPromise: Promise<ReadableStream<Uint8Array> | null> | null
cacheData: Promise<FetchResponseCacheData | null>
}
type FetchResponseCacheData = {
isResponsePartial: boolean
responseBodyClone: ReadableStream<Uint8Array>
}
/**
* Strips the leading isPartial byte from an RSC navigation response and
* clones the body for segment cache extraction.
*
* When cache components is enabled, the server prepends a single byte:
* '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped
* before Flight decoding because it's not valid RSC data. The body is
* cloned before Flight can consume it so the clone is available for later use.
*
* When cache components is disabled, returns the original response with
* cacheData: null.
*/
export async function processFetch(response: Response): Promise<{
response: Response
cacheData: FetchResponseCacheData | null
}> {
if (process.env.__NEXT_CACHE_COMPONENTS) {
if (!response.body) {
throw new InvariantError(
'Expected RSC navigation response to have a body'
)
}
const { stream, isPartial } = await stripIsPartialByte(response.body)
const [stream1, stream2] = stream.tee()
const strippedResponse = new Response(stream1, {
headers: response.headers,
status: response.status,
statusText: response.statusText,
})
// The Response constructor doesn't preserve `url` or `redirected` from
// the original. We need both: `url` for React DevTools and `redirected`
// for the redirect replay logic below.
Object.defineProperty(strippedResponse, 'url', { value: response.url })
Object.defineProperty(strippedResponse, 'redirected', {
value: response.redirected,
})
return {
response: strippedResponse,
cacheData: { isResponsePartial: isPartial, responseBodyClone: stream2 },
}
}
return { response, cacheData: null }
}
/**
* Resolves the static stage response from the raw `processFetch` outputs and
* the decoded flight response, for writing into the segment cache.
*
* - Fully static: use the decoded flight response as-is, no truncation needed.
* - Not fully static + `l` field: truncate the body clone at the static stage
* byte boundary and decode.
* - Otherwise: no cache-worthy data.
*/
async function resolveStaticStageData(
cacheData: FetchResponseCacheData,
flightResponse: NavigationFlightResponse,
headers: RequestHeaders
): Promise<StaticStageData | null> {
const { isResponsePartial, responseBodyClone } = cacheData
if (!isResponsePartial) {
// Fully static — cache the entire decoded response as-is.
responseBodyClone.cancel()
return { response: flightResponse, isResponsePartial: false }
}
if (flightResponse.l !== undefined) {
// Partially static — truncate the body clone at the byte boundary.
const staticStageByteLength = await flightResponse.l
const truncatedStream = truncateStream(
responseBodyClone,
staticStageByteLength
)
const response =
await createFromNextReadableStream<NavigationFlightResponse>(
truncatedStream,
headers,
{ allowPartialStream: true }
)
return { response, isResponsePartial: true }
}
// No caching — cancel the unused clone.
responseBodyClone.cancel()
return null
}
export async function createFetch<T>(
......@@ -360,15 +462,8 @@ export async function createFetch<T>(
// track them separately.
let fetchUrl = new URL(url)
setCacheBustingSearchParam(fetchUrl, headers)
let fetchPromise = fetch(fetchUrl, fetchOptions)
// When cache components is enabled, clone the response before Flight
// consumes the body, so we can later truncate the clone to extract the
// static stage for caching.
let staticStageBodyPromise: Promise<ReadableStream<Uint8Array> | null> | null =
process.env.__NEXT_CACHE_COMPONENTS
? fetchPromise.then((response) => response.clone().body)
: null
let processed = fetch(fetchUrl, fetchOptions).then(processFetch)
let fetchPromise = processed.then(({ response }) => response)
// Immediately pass the fetch promise to the Flight client so that the debug
// info includes the latency from the client to the server. The internal timer
......@@ -437,10 +532,8 @@ export async function createFetch<T>(
// TODO: We should abort the previous request.
fetchUrl = new URL(responseUrl)
setCacheBustingSearchParam(fetchUrl, headers)
fetchPromise = fetch(fetchUrl, fetchOptions)
if (process.env.__NEXT_CACHE_COMPONENTS) {
staticStageBodyPromise = fetchPromise.then((r) => r.clone().body)
}
processed = fetch(fetchUrl, fetchOptions).then(processFetch)
fetchPromise = processed.then(({ response }) => response)
flightResponsePromise = shouldImmediatelyDecode
? createFromNextFetch<T>(fetchPromise, headers)
: null
......@@ -477,7 +570,7 @@ export async function createFetch<T>(
// are later rendered by React.
flightResponsePromise: flightResponsePromise,
staticStageBodyPromise: staticStageBodyPromise,
cacheData: processed.then(({ cacheData }) => cacheData),
}
return rscResponse
......@@ -507,26 +600,6 @@ function createFromNextFetch<T>(
})
}
async function decodeStaticStageResponse(
staticStageByteLengthPromise: Promise<number>,
staticStageBodyPromise: Promise<ReadableStream<Uint8Array> | null>,
requestHeaders: RequestHeaders
): Promise<NavigationFlightResponse> {
const [byteLength, staticBody] = await Promise.all([
staticStageByteLengthPromise,
staticStageBodyPromise,
])
if (staticBody === null) {
throw new InvariantError('Expected static stage body to be available')
}
const truncatedStream = truncateStream(staticBody, byteLength)
return createFromNextReadableStream<NavigationFlightResponse>(
truncatedStream,
requestHeaders,
{ allowPartialStream: true }
)
}
function truncateStream(
stream: ReadableStream<Uint8Array>,
byteLength: number
......
......@@ -35,11 +35,12 @@ import {
waitForSegmentCacheEntry,
markRouteEntryAsDynamicRewrite,
invalidateRouteCacheEntries,
processStaticStageResponse,
getStaleAt,
writeStaticStageResponseIntoCache,
EntryStatus,
} from '../segment-cache/cache'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import type { NormalizedSearch } from '../segment-cache/cache-key'
import {
getRenderedSearchFromVaryPath,
......@@ -1581,23 +1582,33 @@ async function fetchMissingDynamicData(
await waitForNavigationLock()
}
if (routeCacheEntry !== null && result.staticStageResponse !== null) {
if (routeCacheEntry !== null && result.staticStageData !== null) {
const { response: staticStageResponse, isResponsePartial } =
result.staticStageData
const now = Date.now()
processStaticStageResponse(now, result.staticStageResponse).then(
({ serverData, headVaryParams, staleAt }) =>
getStaleAt(now, staticStageResponse.s)
.then((staleAt) => {
const buildId =
result.responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
staticStageResponse.b
writeStaticStageResponseIntoCache(
now,
serverData,
result.responseHeaders,
headVaryParams,
staticStageResponse.f,
buildId,
staticStageResponse.h,
staleAt,
routeCacheEntry
),
() => {
dynamicRequestTree,
result.renderedSearch,
isResponsePartial
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache.
}
)
})
}
const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(
......
......@@ -64,6 +64,7 @@ import {
} from '../../../../shared/lib/action-revalidation-kind'
import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy } from '../ppr-navigations'
import { processFetch } from '../fetch-server-response'
import { invalidateBfCache } from '../../segment-cache/bfcache'
const createFromFetch =
......@@ -205,8 +206,15 @@ async function fetchServerAction(
let couldBeIntercepted: boolean = false
if (isRscResponse) {
// Server action redirect responses carry the Flight data of the redirect
// target, which may be prerendered with a completeness marker byte
// prepended. Strip it before passing to Flight.
const responsePromise = redirectLocation
? processFetch(res).then(({ response: r }) => r)
: Promise.resolve(res)
const response: ActionFlightResponse = await createFromFetch(
Promise.resolve(res),
responsePromise,
{
callServer,
findSourceMapURL,
......
......@@ -14,12 +14,13 @@ import {
type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import {
EntryStatus,
readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry,
convertRootFlightRouterStateToRouteTree,
processStaticStageResponse,
getStaleAt,
writeStaticStageResponseIntoCache,
type RouteTree,
type FulfilledRouteCacheEntry,
......@@ -371,7 +372,7 @@ async function navigateToUnknownRoute(
renderedSearch,
couldBeIntercepted,
supportsPerSegmentPrefetching,
staticStageResponse,
staticStageData,
responseHeaders,
debugInfo,
} = result
......@@ -392,7 +393,7 @@ async function navigateToUnknownRoute(
// retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).
const metadataVaryPath = navigationSeed.metadataVaryPath
if (metadataVaryPath !== null) {
const fulfilledRoute = discoverKnownRoute(
discoverKnownRoute(
now,
url.pathname,
nextUrl,
......@@ -405,24 +406,33 @@ async function navigateToUnknownRoute(
false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal
)
// Write the static stage of the response into the segment cache so
// that subsequent navigations can serve cached static segments instantly.
if (staticStageResponse !== null) {
processStaticStageResponse(now, staticStageResponse).then(
({ serverData, headVaryParams, staleAt }) =>
if (staticStageData !== null) {
const { response: staticStageResponse, isResponsePartial } =
staticStageData
// Write the static stage of the response into the segment cache so that
// subsequent navigations can serve cached static segments instantly.
getStaleAt(now, staticStageResponse.s)
.then((staleAt) => {
const buildId =
responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
staticStageResponse.b
writeStaticStageResponseIntoCache(
now,
serverData,
responseHeaders,
headVaryParams,
staticStageResponse.f,
buildId,
staticStageResponse.h,
staleAt,
fulfilledRoute
),
() => {
currentFlightRouterState,
renderedSearch,
isResponsePartial
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache.
}
)
})
}
}
......
......@@ -1456,7 +1456,6 @@ async function finalRuntimeServerPrerender(
}
)
// Prepend a byte indicating whether the response contains dynamic holes.
result.prelude = prependIsPartialByte(result.prelude, serverIsDynamic)
return {
......@@ -1828,6 +1827,8 @@ function App<T>({
initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i,
initialSupportsPerSegmentPrefetching: response.S,
initialStaleTime: undefined,
initialHeadVaryParams: null,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
......@@ -1893,6 +1894,8 @@ function ErrorApp<T>({
initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i,
initialSupportsPerSegmentPrefetching: response.S,
initialStaleTime: undefined,
initialHeadVaryParams: null,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
......@@ -5139,6 +5142,9 @@ async function prerenderToStream(
res.statusCode === 404
)
const staleTimeIterable = new StaleTimeIterable()
finalAttemptRSCPayload.s = staleTimeIterable
const serverDynamicTracking = createDynamicTrackingState(
isDebugDynamicAccesses
)
......@@ -5166,6 +5172,12 @@ async function prerenderToStream(
varyParamsAccumulator,
})
trackStaleTime(
finalServerPrerenderStore,
staleTimeIterable,
selectStaleTime
)
let prerenderIsPending = true
const finalRSCPrerenderOptions = {
filterStackFrame,
......@@ -5175,18 +5187,20 @@ async function prerenderToStream(
signal: finalServerReactController.signal,
}
const finalRSCAbortCallback = async () => {
// Now that the prerendering is complete, we know which vary
// params were used to compute the response. Resolve the vary
// params thenable so it can be sent to the client. The timing
// here is important: the thenable was included in the Flight
// payload, but it can only be serialized at the very end, after
// all the components have finished.
// Now that the prerendering is complete, we know the final stale
// time and vary params. Close the stale time iterable and resolve
// the vary params thenable so Flight can serialize their values
// into the stream. The timing here is important: both were
// included in the Flight payload, but they can only be serialized
// at the very end, after all the components have finished.
//
// We resolve the accumulator directly here instead of reading from
// the work unit store because this callback runs in a separate
// task (via setTimeout) and may not have access to the async
// storage context.
await finishAccumulatingVaryParams(varyParamsAccumulator)
// We resolve these directly here instead of reading from the work
// unit store because this callback runs in a separate task (via
// setTimeout) and may not have access to the async storage context.
await Promise.all([
finishStaleTimeTracking(staleTimeIterable),
finishAccumulatingVaryParams(varyParamsAccumulator),
])
if (finalServerReactController.signal.aborted) {
// If the server controller is already aborted we must have called something
......@@ -5356,8 +5370,12 @@ async function prerenderToStream(
tracingMetadata: tracingMetadata,
})
const flightData = await streamToBuffer(reactServerResult.asStream())
metadata.flightData = flightData
metadata.flightData = await streamToBuffer(
prependIsPartialByte(reactServerResult.asStream(), serverIsDynamic)
)
// collectSegmentData needs the raw flight data without the marker byte.
const flightData = metadata.flightData.subarray(1)
metadata.segmentData = await collectSegmentData(
flightData,
finalServerPrerenderStore,
......
......@@ -14,6 +14,7 @@ import { INFINITE_CACHE } from '../../lib/constants'
export class StaleTimeIterable {
private _resolve: ((result: IteratorResult<number>) => void) | null = null
private _done = false
private _buffer: number[] = []
/** The last value passed to `update()`. */
public currentValue: number = 0
......@@ -24,6 +25,8 @@ export class StaleTimeIterable {
if (this._resolve) {
this._resolve({ value, done: false })
this._resolve = null
} else {
this._buffer.push(value)
}
}
......@@ -39,6 +42,9 @@ export class StaleTimeIterable {
[Symbol.asyncIterator](): AsyncIterator<number> {
return {
next: () => {
if (this._buffer.length > 0) {
return Promise.resolve({ value: this._buffer.shift()!, done: false })
}
if (this._done) {
return Promise.resolve({ value: undefined, done: true })
}
......
......@@ -262,6 +262,8 @@ export type InitialRSCPayload = {
* headVaryParams - vary params for the head (metadata) of the response.
*/
h: VaryParamsThenable | null
/** staleTime in seconds - Only present when Cache Components is enabled. */
s?: AsyncIterable<number>
}
// Response from `createFromFetch` for normal rendering
......
......@@ -6,7 +6,9 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<html>
<body>
<nav>
<Link href="/">Home</Link>
<Link href="/" prefetch={false}>
Home
</Link>
</nav>
{children}
</body>
......
......@@ -15,12 +15,12 @@ describe('cached navigations', () => {
it('serves cached static segments instantly on the second navigation', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
await page.clock.install()
// First navigation — full dynamic request, no prefetch
await act(
......@@ -147,52 +147,48 @@ describe('cached navigations', () => {
)
})
// TODO: To be implemented.
it.failing(
'serves a fully static page without any requests on the second navigation',
async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
it('serves a fully static page without any requests on the second navigation', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// First navigation — full request, no prefetch
await act(
async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
},
{ includes: 'Cached content' }
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// First navigation — full request, no prefetch
await act(
async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
},
{ includes: 'Cached content' }
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Navigate back to home
await browser.back()
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Navigate back to home
await browser.back()
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Second navigation — fully cached, should not issue any requests
await act(async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
}, 'no-requests')
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
}
)
// Second navigation — fully cached, should not issue any requests
await act(async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
}, 'no-requests')
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
})
it('caches static segments when navigating to a known route without a prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
await page.clock.install()
// First navigation — seeds the route cache (stale after 5 min) and
// segment cache (stale after 120s, from cacheLife({ stale: 120 })).
......@@ -280,12 +276,12 @@ describe('cached navigations', () => {
it('includes static params in the cached static stage', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
await page.clock.install()
// First navigation
await act(
......@@ -340,12 +336,12 @@ describe('cached navigations', () => {
it('defers fallback params to the runtime stage', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
await page.clock.install()
// First navigation — "foo" is not in generateStaticParams, so it's a
// fallback param
......@@ -405,4 +401,65 @@ describe('cached navigations', () => {
'Dynamic content'
)
})
it('caches a fully static page from the initial HTML for subsequent navigations', async () => {
let page: Playwright.Page
// Start directly at /fully-static — full HTML load, not a client-side
// navigation. The RSC payload is inlined in the HTML and contains only
// static (cached) content.
const browser = await next.browser('/fully-static', {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
// Verify the page rendered fully via HTML
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Navigate to home
await act(
async () => {
await browser.elementByCss('a[href="/"]').click()
},
{ includes: 'Home' }
)
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Navigate back to /fully-static. Since it was fully static and cached
// during the initial HTML load, no server requests should be needed.
await act(async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
}, 'no-requests')
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Navigate back to home again
await act(async () => {
await browser.elementByCss('a[href="/"]').click()
}, 'no-requests')
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Fast-forward past the stale time (120s from cacheLife({ stale: 120 })).
// Using 180s to stay well under the 300s default — if we accidentally
// used the default instead of the collected stale time, this would
// not expire and the test would fail.
await page.clock.fastForward(180_000)
// Navigate to /fully-static again — cache is stale, so a server
// request should be required.
await act(
async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
},
{ includes: 'Cached content' }
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
})
})
......@@ -138,4 +138,54 @@ describe('segment cache (refresh)', () => {
expect(await docsPage.textContent()).toBe('Static docs page')
}, 'no-requests')
})
it('re-navigation to a fully static page does not overwrite dynamic slots with default content', async () => {
// Load the main Dashboard page. The @navbar slot renders dynamic content
// (connection() + randomUUID()), but the @main slot is static.
let page: Playwright.Page
const browser = await next.browser('/dashboard', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// Navigate to the Analytics page. This is a fully static page (both the
// @main/analytics slot and the @navbar/default slot are static), so the
// server responds with a Static completeness marker. The client writes
// all segments into the segment cache.
await act(async () => {
const toggleAnalyticsLink = await browser.elementByCss(
'input[data-link-accordion="/dashboard/analytics"]'
)
await toggleAnalyticsLink.click()
const link = await browser.elementByCss('a[href="/dashboard/analytics"]')
await link.click()
})
// Navigate back to the Dashboard page.
await act(async () => {
const toggleDashboardLink = await browser.elementByCss(
'input[data-link-accordion="/dashboard"]'
)
await toggleDashboardLink.click()
const link = await browser.elementByCss('a[href="/dashboard"]')
await link.click()
})
// Navigate to the Analytics page again. Since it's fully static and was
// already visited, this should be served entirely from the segment cache
// without any server requests.
await act(async () => {
const link = await browser.elementByCss('a[href="/dashboard/analytics"]')
await link.click()
}, 'no-requests')
// Verify the navbar still shows the dynamic content from the original
// /dashboard render, not the static @navbar/default.tsx content.
const navbarDynamicRenderCounter = await browser.elementById(
'navbar-dynamic-render-counter'
)
expect(await navbarDynamicRenderCounter.textContent()).toBe('0')
})
})
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