Unverified Commit 5a18a71b authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Cached Navigations: Cache static stage of partially static initial HTML (#90539)

When a partially static page is loaded via initial HTML (PPR resume), the RSC payload now includes the `l` (static stage byte length) field, enabling the client router to extract and cache the static stage during hydration. Subsequent navigations to the same page serve the cached static content instantly while streaming in dynamic content.

On the server, the resume path in `renderToStream` now uses staged rendering (mirroring `generateStagedDynamicFlightRenderResult`) when Cache Components is enabled. A `StagedRenderingController` separates the static and dynamic stages, and `countStaticStageBytes` resolves the byte length promise that Flight serializes into the stream as `l`. `getRSCPayload` accepts `staleTimeIterable` and `staticStageByteLengthPromise` options to wire `s` and `l` into the `InitialRSCPayload`.

On the client, `app-index.tsx` tees the inlined Flight stream when Cache Components is enabled. One copy goes to React for decoding, the other is passed to `createInitialRouterState`. When `l` is present (partially static), the clone is truncated at the byte boundary via `decodeStaticStage` and written into the segment cache via `writeStaticStageResponseIntoCache` with `isResponsePartial: true`. When `l` is absent but `s` is present (fully static), the same function is used with `isResponsePartial: false`.

`createInitialRouterState` now accepts a single `initialRSCPayload: InitialRSCPayload` prop instead of individual destructured fields.
parent cb44b43c
...@@ -165,7 +165,7 @@ nextServerDataLoadingGlobal.length = 0 ...@@ -165,7 +165,7 @@ nextServerDataLoadingGlobal.length = 0
// Patch its push method so subsequent chunks are handled (but not actually pushed to the array). // Patch its push method so subsequent chunks are handled (but not actually pushed to the array).
nextServerDataLoadingGlobal.push = nextServerDataCallback nextServerDataLoadingGlobal.push = nextServerDataCallback
const readable = new ReadableStream({ let readable: ReadableStream<Uint8Array> = new ReadableStream({
start(controller) { start(controller) {
nextServerDataRegisterWriter(controller) nextServerDataRegisterWriter(controller)
}, },
...@@ -175,6 +175,17 @@ if (process.env.NODE_ENV !== 'production') { ...@@ -175,6 +175,17 @@ if (process.env.NODE_ENV !== 'production') {
readable.name = 'hydration' readable.name = 'hydration'
} }
// When Cache Components is enabled, tee the inlined Flight stream so we can
// truncate a clone at the static stage byte boundary and cache it. We don't
// know if `l` is present until React decodes the payload, so always tee and
// cancel the clone if not needed.
let initialFlightStreamForCache: ReadableStream<Uint8Array> | null = null
if (process.env.__NEXT_CACHE_COMPONENTS) {
const [forReact, forCache] = readable.tee()
readable = forReact
initialFlightStreamForCache = forCache
}
let debugChannel: let debugChannel:
| { readable?: ReadableStream; writable?: WritableStream } | { readable?: ReadableStream; writable?: WritableStream }
| undefined | undefined
...@@ -321,13 +332,8 @@ export async function hydrate( ...@@ -321,13 +332,8 @@ export async function hydrate(
const actionQueue: AppRouterActionQueue = createMutableActionQueue( const actionQueue: AppRouterActionQueue = createMutableActionQueue(
createInitialRouterState({ createInitialRouterState({
navigatedAt: initialTimestamp, navigatedAt: initialTimestamp,
initialFlightData: initialRSCPayload.f, initialRSCPayload,
initialCanonicalUrlParts: initialRSCPayload.c, initialFlightStreamForCache,
initialRenderedSearch: initialRSCPayload.q,
initialCouldBeIntercepted: initialRSCPayload.i,
initialSupportsPerSegmentPrefetching: initialRSCPayload.S,
initialStaleTime: initialRSCPayload.s,
initialHeadVaryParams: initialRSCPayload.h,
location: window.location, location: window.location,
}), }),
instrumentationHooks instrumentationHooks
......
import type { FlightDataPath } from '../../../shared/lib/app-router-types' import type { InitialRSCPayload } 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 { createHrefFromUrl } from './create-href-from-url'
import { extractPathFromFlightRouterState } from './compute-changed-path' import { extractPathFromFlightRouterState } from './compute-changed-path'
...@@ -12,32 +11,34 @@ import { ...@@ -12,32 +11,34 @@ import {
getStaleAt, getStaleAt,
writeStaticStageResponseIntoCache, writeStaticStageResponseIntoCache,
} from '../segment-cache/cache' } from '../segment-cache/cache'
import { decodeStaticStage } from './fetch-server-response'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes' import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from '../segment-cache/cache-key'
export interface InitialRouterStateParameters { export interface InitialRouterStateParameters {
navigatedAt: number navigatedAt: number
initialCanonicalUrlParts: string[] initialRSCPayload: InitialRSCPayload
initialRenderedSearch: string initialFlightStreamForCache?: ReadableStream<Uint8Array> | null
initialFlightData: FlightDataPath[]
initialCouldBeIntercepted: boolean
initialSupportsPerSegmentPrefetching: boolean
initialStaleTime: AsyncIterable<number> | undefined
initialHeadVaryParams: VaryParamsThenable | null
location: Location | null location: Location | null
} }
export function createInitialRouterState({ export function createInitialRouterState({
navigatedAt, navigatedAt,
initialFlightData, initialRSCPayload,
initialCanonicalUrlParts, initialFlightStreamForCache,
initialRenderedSearch,
initialCouldBeIntercepted,
initialSupportsPerSegmentPrefetching,
initialStaleTime,
initialHeadVaryParams,
location, location,
}: InitialRouterStateParameters): AppRouterState { }: InitialRouterStateParameters): AppRouterState {
const {
c: initialCanonicalUrlParts,
f: initialFlightData,
q: initialRenderedSearch,
i: initialCouldBeIntercepted,
S: initialSupportsPerSegmentPrefetching,
s: initialStaleTime,
l: initialStaticStageByteLength,
h: initialHeadVaryParams,
} = initialRSCPayload
// When initialized on the server, the canonical URL is provided as an array of parts. // When initialized on the server, the canonical URL is provided as an array of parts.
// This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it
// as a URL that should be crawled. // as a URL that should be crawled.
...@@ -98,26 +99,68 @@ export function createInitialRouterState({ ...@@ -98,26 +99,68 @@ export function createInitialRouterState({
// Write the initial seed data into the segment cache so subsequent // Write the initial seed data into the segment cache so subsequent
// navigations to the initial page can serve cached segments instantly. // navigations to the initial page can serve cached segments instantly.
if (initialSeedData !== null && initialStaleTime !== undefined) { if (initialSeedData !== null && initialStaleTime !== undefined) {
// Currently only fully static pages include initialStaleTime. if (
const now = Date.now() initialStaticStageByteLength !== undefined &&
initialFlightStreamForCache != null
getStaleAt(now, initialStaleTime) ) {
.then((staleAt) => { // Partially static page — truncate the cloned Flight stream at the
writeStaticStageResponseIntoCache( // static stage byte boundary, decode, and cache the static subset.
now, decodeStaticStage<InitialRSCPayload>(
initialFlightData, initialFlightStreamForCache,
undefined, // buildId — not applicable for initial HTML initialStaticStageByteLength,
initialHeadVaryParams, undefined
staleAt, )
initialTree, .then(async (staticStageResponse) => {
initialRenderedSearch, const now = Date.now()
false // isResponsePartial const staleAt = await getStaleAt(now, staticStageResponse.s)
)
}) writeStaticStageResponseIntoCache(
.catch(() => { now,
// The static stage processing failed. Not fatal — the page staticStageResponse.f,
// rendered normally, we just won't write into the cache. undefined, // no build ID mismatch check for initial HTML
}) staticStageResponse.h,
staleAt,
initialTree,
initialRenderedSearch,
true // isResponsePartial
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the page
// rendered normally, we just won't write into the cache.
})
} else {
// Fully static page — cache the entire decoded seed data as-is. We're
// not using the initial response here (which would allow us to combine
// the two branches) to avoid unnecessary decoding of the Flight data,
// since we can just take the seed data that we already decoded during
// hydration and write it into the cache directly.
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.
})
// Cancel the stream clone — fully static path doesn't need it.
initialFlightStreamForCache?.cancel()
}
} else {
// No caching — cancel the unused stream clone.
initialFlightStreamForCache?.cancel()
} }
} }
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
import { InvariantError } from '../../../shared/lib/invariant-error' import { InvariantError } from '../../../shared/lib/invariant-error'
import type { import type {
FlightRouterState, FlightRouterState,
InitialRSCPayload,
NavigationFlightResponse, NavigationFlightResponse,
} from '../../../shared/lib/app-router-types' } from '../../../shared/lib/app-router-types'
...@@ -64,8 +65,12 @@ export interface FetchServerResponseOptions { ...@@ -64,8 +65,12 @@ export interface FetchServerResponseOptions {
readonly isHmrRefresh?: boolean readonly isHmrRefresh?: boolean
} }
export type StaticStageData = { export type StaticStageData<
readonly response: NavigationFlightResponse T extends
| NavigationFlightResponse
| InitialRSCPayload = NavigationFlightResponse,
> = {
readonly response: T
readonly isResponsePartial: boolean readonly isResponsePartial: boolean
} }
...@@ -378,11 +383,13 @@ export async function processFetch(response: Response): Promise<{ ...@@ -378,11 +383,13 @@ export async function processFetch(response: Response): Promise<{
* byte boundary and decode. * byte boundary and decode.
* - Otherwise: no cache-worthy data. * - Otherwise: no cache-worthy data.
*/ */
async function resolveStaticStageData( export async function resolveStaticStageData<
T extends NavigationFlightResponse | InitialRSCPayload,
>(
cacheData: FetchResponseCacheData, cacheData: FetchResponseCacheData,
flightResponse: NavigationFlightResponse, flightResponse: T,
headers: RequestHeaders headers: RequestHeaders | undefined
): Promise<StaticStageData | null> { ): Promise<StaticStageData<T> | null> {
const { isResponsePartial, responseBodyClone } = cacheData const { isResponsePartial, responseBodyClone } = cacheData
if (!isResponsePartial) { if (!isResponsePartial) {
...@@ -393,21 +400,14 @@ async function resolveStaticStageData( ...@@ -393,21 +400,14 @@ async function resolveStaticStageData(
} }
if (flightResponse.l !== undefined) { if (flightResponse.l !== undefined) {
// Partially static — truncate the body clone at the byte boundary. // Partially static — truncate the body clone at the byte boundary and
const staticStageByteLength = await flightResponse.l // decode it.
const response = await decodeStaticStage<T>(
const truncatedStream = truncateStream(
responseBodyClone, responseBodyClone,
staticStageByteLength flightResponse.l,
headers
) )
const response =
await createFromNextReadableStream<NavigationFlightResponse>(
truncatedStream,
headers,
{ allowPartialStream: true }
)
return { response, isResponsePartial: true } return { response, isResponsePartial: true }
} }
...@@ -417,6 +417,28 @@ async function resolveStaticStageData( ...@@ -417,6 +417,28 @@ async function resolveStaticStageData(
return null return null
} }
/**
* Truncates a Flight stream clone at the given byte boundary and decodes the
* static stage prefix. Used by both the navigation path and the initial HTML
* hydration path.
*/
export async function decodeStaticStage<T>(
responseBodyClone: ReadableStream<Uint8Array>,
staticStageByteLengthPromise: Promise<number>,
headers: RequestHeaders | undefined
): Promise<T> {
const staticStageByteLength = await staticStageByteLengthPromise
const truncatedStream = truncateStream(
responseBodyClone,
staticStageByteLength
)
return createFromNextReadableStream<T>(truncatedStream, headers, {
allowPartialStream: true,
})
}
export async function createFetch<T>( export async function createFetch<T>(
url: URL, url: URL,
headers: RequestHeaders, headers: RequestHeaders,
...@@ -578,7 +600,7 @@ export async function createFetch<T>( ...@@ -578,7 +600,7 @@ export async function createFetch<T>(
export function createFromNextReadableStream<T>( export function createFromNextReadableStream<T>(
flightStream: ReadableStream<Uint8Array>, flightStream: ReadableStream<Uint8Array>,
requestHeaders: RequestHeaders, requestHeaders: RequestHeaders | undefined,
options?: { allowPartialStream?: boolean } options?: { allowPartialStream?: boolean }
): Promise<T> { ): Promise<T> {
return createFromReadableStream(flightStream, { return createFromReadableStream(flightStream, {
......
...@@ -1518,8 +1518,13 @@ function getRenderedSearch(query: NextParsedUrlQuery): string { ...@@ -1518,8 +1518,13 @@ function getRenderedSearch(query: NextParsedUrlQuery): string {
async function getRSCPayload( async function getRSCPayload(
tree: LoaderTree, tree: LoaderTree,
ctx: AppRenderContext, ctx: AppRenderContext,
is404: boolean options: {
is404: boolean
staleTimeIterable?: AsyncIterable<number>
staticStageByteLengthPromise?: Promise<number>
}
): Promise<InitialRSCPayload & { P: ReactNode }> { ): Promise<InitialRSCPayload & { P: ReactNode }> {
const { is404, staleTimeIterable, staticStageByteLengthPromise } = options
const injectedCSS = new Set<string>() const injectedCSS = new Set<string>()
const injectedJS = new Set<string>() const injectedJS = new Set<string>()
const injectedFontPreloadTags = new Set<string>() const injectedFontPreloadTags = new Set<string>()
...@@ -1653,6 +1658,8 @@ async function getRSCPayload( ...@@ -1653,6 +1658,8 @@ async function getRSCPayload(
// generated during static generation (build or ISR). // generated during static generation (build or ISR).
S: workStore.isStaticGeneration || ctx.renderOpts.cacheComponents, S: workStore.isStaticGeneration || ctx.renderOpts.cacheComponents,
h: getMetadataVaryParamsThenable(), h: getMetadataVaryParamsThenable(),
s: staleTimeIterable,
l: staticStageByteLengthPromise,
}) })
} }
...@@ -1820,13 +1827,7 @@ function App<T>({ ...@@ -1820,13 +1827,7 @@ function App<T>({
// This is not used during hydration, so we don't have to pass a // This is not used during hydration, so we don't have to pass a
// real timestamp. // real timestamp.
navigatedAt: -1, navigatedAt: -1,
initialFlightData: response.f, initialRSCPayload: response,
initialCanonicalUrlParts: response.c,
initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i,
initialSupportsPerSegmentPrefetching: response.S,
initialStaleTime: undefined,
initialHeadVaryParams: null,
// location is not initialized in the SSR render // location is not initialized in the SSR render
// it's set to window.location during hydration // it's set to window.location during hydration
location: null, location: null,
...@@ -1887,13 +1888,7 @@ function ErrorApp<T>({ ...@@ -1887,13 +1888,7 @@ function ErrorApp<T>({
// This is not used during hydration, so we don't have to pass a // This is not used during hydration, so we don't have to pass a
// real timestamp. // real timestamp.
navigatedAt: -1, navigatedAt: -1,
initialFlightData: response.f, initialRSCPayload: response,
initialCanonicalUrlParts: response.c,
initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i,
initialSupportsPerSegmentPrefetching: response.S,
initialStaleTime: undefined,
initialHeadVaryParams: null,
// location is not initialized in the SSR render // location is not initialized in the SSR render
// it's set to window.location during hydration // it's set to window.location during hydration
location: null, location: null,
...@@ -2780,7 +2775,7 @@ async function renderToStream( ...@@ -2780,7 +2775,7 @@ async function renderToStream(
getRSCPayload, getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 { is404: res.statusCode === 404 }
) )
if (isBypassingCachesInDev(requestStore)) { if (isBypassingCachesInDev(requestStore)) {
...@@ -2884,6 +2879,78 @@ async function renderToStream( ...@@ -2884,6 +2879,78 @@ async function renderToStream(
requestId requestId
) )
} }
} else if (cacheComponents) {
// Production Cache Components: use staged rendering so the RSC payload
// includes the static stage byte length (`l` field), enabling the
// client to cache the static subset during hydration.
const { renderToReadableStream } = ctx.componentMod
const selectStaleTime = createSelectStaleTime(experimental)
const staleTimeIterable = new StaleTimeIterable()
const stageController = new StagedRenderingController()
requestStore.stale = INFINITE_CACHE
requestStore.stagedRendering = stageController
trackStaleTime(
requestStore as { stale: number },
staleTimeIterable,
selectStaleTime
)
let resolveStaticStageByteLength: (count: number) => void
const staticStageByteLengthPromise = new Promise<number>((resolve) => {
resolveStaticStageByteLength = resolve
})
const RSCPayload = await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
{
is404: res.statusCode === 404,
staleTimeIterable,
staticStageByteLengthPromise,
}
)
const flightStream = await runInSequentialTasks(
() => {
stageController.advanceStage(RenderStage.Static)
const stream = workUnitAsyncStorage.run(
requestStore,
renderToReadableStream,
RSCPayload,
clientModules,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
}
)
const [dynamicStream, staticStream] = stream.tee()
countStaticStageBytes(staticStream, stageController).then(
resolveStaticStageByteLength!
)
return dynamicStream
},
() => {
// This is a separate task that doesn't advance a stage. It forces
// draining the microtask queue so that the stale time iterable is
// closed before we advance to the dynamic stage.
void finishStaleTimeTracking(staleTimeIterable)
},
() => {
stageController.advanceStage(RenderStage.Dynamic)
}
)
reactServerResult = new ReactServerResult(flightStream)
} else { } else {
// This is a dynamic render. We don't do dynamic tracking because we're not prerendering // This is a dynamic render. We don't do dynamic tracking because we're not prerendering
const RSCPayload: RSCPayload & RSCPayloadDevProperties = const RSCPayload: RSCPayload & RSCPayloadDevProperties =
...@@ -2892,7 +2959,7 @@ async function renderToStream( ...@@ -2892,7 +2959,7 @@ async function renderToStream(
getRSCPayload, getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 { is404: res.statusCode === 404 }
) )
const debugChannel = setReactDebugChannel && createDebugChannel() const debugChannel = setReactDebugChannel && createDebugChannel()
...@@ -4857,7 +4924,7 @@ async function prerenderToStream( ...@@ -4857,7 +4924,7 @@ async function prerenderToStream(
getRSCPayload, getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 { is404: res.statusCode === 404 }
) )
const initialServerPrerenderStore: PrerenderStore = (prerenderStore = { const initialServerPrerenderStore: PrerenderStore = (prerenderStore = {
...@@ -5137,7 +5204,7 @@ async function prerenderToStream( ...@@ -5137,7 +5204,7 @@ async function prerenderToStream(
getRSCPayload, getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 { is404: res.statusCode === 404 }
) )
const staleTimeIterable = new StaleTimeIterable() const staleTimeIterable = new StaleTimeIterable()
...@@ -5555,7 +5622,7 @@ async function prerenderToStream( ...@@ -5555,7 +5622,7 @@ async function prerenderToStream(
getRSCPayload, getRSCPayload,
tree, tree,
ctx, ctx,
res.statusCode === 404 { is404: res.statusCode === 404 }
) )
let reactServerResult: ReactServerPrerenderResult let reactServerResult: ReactServerPrerenderResult
......
...@@ -264,6 +264,8 @@ export type InitialRSCPayload = { ...@@ -264,6 +264,8 @@ export type InitialRSCPayload = {
h: VaryParamsThenable | null h: VaryParamsThenable | null
/** staleTime in seconds - Only present when Cache Components is enabled. */ /** staleTime in seconds - Only present when Cache Components is enabled. */
s?: AsyncIterable<number> s?: AsyncIterable<number>
/** staticStageByteLength - Resolves when the static stage ends. */
l?: Promise<number>
} }
// Response from `createFromFetch` for normal rendering // Response from `createFromFetch` for normal rendering
......
...@@ -11,5 +11,5 @@ export default async function Page() { ...@@ -11,5 +11,5 @@ export default async function Page() {
async function CachedContent() { async function CachedContent() {
'use cache' 'use cache'
cacheLife({ stale: 120 }) cacheLife({ stale: 120 })
return <p id="cached-content">Cached content</p> return <p id="cached-content">Cached content ({new Date().toISOString()})</p>
} }
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
import { Suspense } from 'react' import { Suspense } from 'react'
export default async function Page({ export default async function Page({
...@@ -38,7 +39,7 @@ export default async function Page({ ...@@ -38,7 +39,7 @@ export default async function Page({
async function CachedContent() { async function CachedContent() {
'use cache' 'use cache'
cacheLife({ stale: 120 }) cacheLife({ stale: 120 })
return <p id="cached-content">Cached content</p> return <p id="cached-content">Cached content ({new Date().toISOString()})</p>
} }
async function SearchParamsContent({ async function SearchParamsContent({
...@@ -47,33 +48,45 @@ async function SearchParamsContent({ ...@@ -47,33 +48,45 @@ async function SearchParamsContent({
searchParams: Promise<{ q?: string }> searchParams: Promise<{ q?: string }>
}) { }) {
const { q } = await searchParams const { q } = await searchParams
return <p>Search params: {q ?? 'none'}</p> await setTimeout(300)
return (
<p>
Search params: {q ?? 'none'} ({new Date().toISOString()})
</p>
)
} }
async function CookiesContent() { async function CookiesContent() {
const cookieStore = await cookies() const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none' const value = cookieStore.get('testCookie')?.value ?? 'none'
const timestamp = await getShortLivedCachedTimestamp() const date = await getShortLivedCachedDate()
await setTimeout(300)
return ( return (
<p> <p>
Cookie: {value}, Cached at: {timestamp} Cookie: {value}, Cached at: {date}
</p> </p>
) )
} }
async function getShortLivedCachedTimestamp() { async function getShortLivedCachedDate() {
'use cache' 'use cache'
cacheLife({ stale: 30 }) cacheLife({ stale: 30 })
return Date.now() return new Date().toISOString()
} }
async function HeadersContent() { async function HeadersContent() {
const headerStore = await headers() const headerStore = await headers()
const value = headerStore.get('x-test-header') ?? 'none' const value = headerStore.get('x-test-header') ?? 'none'
return <p>Header: {value}</p> await setTimeout(300)
return (
<p>
Header: {value} ({new Date().toISOString()})
</p>
)
} }
async function ConnectionContent() { async function ConnectionContent() {
await connection() await connection()
return <p>Dynamic content</p> await setTimeout(600)
return <p>Dynamic content ({new Date().toISOString()})</p>
} }
import { cacheLife } from 'next/cache' import { cacheLife } from 'next/cache'
import { connection } from 'next/server' import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
import { Suspense } from 'react' import { Suspense } from 'react'
export default function Page({ export default function Page({
...@@ -27,7 +28,7 @@ export default function Page({ ...@@ -27,7 +28,7 @@ export default function Page({
async function CachedContent() { async function CachedContent() {
'use cache' 'use cache'
cacheLife({ stale: 120 }) cacheLife({ stale: 120 })
return <p id="cached-content">Cached content</p> return <p id="cached-content">Cached content ({new Date().toISOString()})</p>
} }
async function ParamsContent({ async function ParamsContent({
...@@ -39,10 +40,12 @@ async function ParamsContent({ ...@@ -39,10 +40,12 @@ async function ParamsContent({
// await is deferred to the runtime stage, so this content won't appear // await is deferred to the runtime stage, so this content won't appear
// in the static stage. // in the static stage.
const { slug } = await params const { slug } = await params
await setTimeout(300)
return <p>Param: {slug}</p> return <p>Param: {slug}</p>
} }
async function ConnectionContent() { async function ConnectionContent() {
await connection() await connection()
return <p>Dynamic content</p> await setTimeout(600)
return <p>Dynamic content ({new Date().toISOString()})</p>
} }
import { connection } from 'next/server' import { connection } from 'next/server'
import { setTimeout } from 'timers/promises'
import { Suspense } from 'react' import { Suspense } from 'react'
export async function generateStaticParams() { export async function generateStaticParams() {
...@@ -28,10 +29,11 @@ export default async function Page({ ...@@ -28,10 +29,11 @@ export default async function Page({
async function CachedContent() { async function CachedContent() {
'use cache' 'use cache'
return <p id="cached-content">Cached content</p> return <p id="cached-content">Cached content ({new Date().toISOString()})</p>
} }
async function ConnectionContent() { async function ConnectionContent() {
await connection() await connection()
return <p>Dynamic content</p> await setTimeout(600)
return <p>Dynamic content ({new Date().toISOString()})</p>
} }
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
...@@ -462,4 +463,70 @@ describe('cached navigations', () => { ...@@ -462,4 +463,70 @@ describe('cached navigations', () => {
'Cached content' 'Cached content'
) )
}) })
it('caches a partially static page from the initial HTML for subsequent navigations', async () => {
let page: Playwright.Page
// Start directly at /partially-static — full HTML load. The RSC payload
// inlined in the HTML contains both cached and dynamic content.
const browser = await next.browser('/partially-static', {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
// Verify the page rendered fully via HTML. Dynamic content streams in
// with a delay, so use retry to wait for it.
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
await retry(async () => {
expect(await browser.elementById('connection-boundary').text()).toContain(
'Dynamic 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 /partially-static. The static stage was cached during
// the initial HTML load, so cached content should be available instantly
// while the dynamic content streams in.
await act(async () => {
await act(
async () => {
await browser.elementByCss('a[href="/partially-static"]').click()
},
{
includes: 'Dynamic content',
block: true,
}
)
// Cached content should be visible while the dynamic request is blocked
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Dynamic content should show Suspense fallbacks
expect(await browser.elementById('connection-boundary').text()).toBe(
'Loading connection...'
)
})
// After unblocking, all content should be visible
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
expect(await browser.elementById('connection-boundary').text()).toContain(
'Dynamic content'
)
})
}) })
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