Fix client navigations rerendering fully static ISR pages in `next start`

Client navigations in self-hosted Cache Components applications rerendered
fully static pages generated on demand, even when fresh ISR entries held
their complete RSC payloads. After a server restart, this could produce
values that differed from the cached HTML.

This change serves the stored RSC payload for fresh, fully static entries
with resolved params. PR #100759 persisted these payloads in the filesystem
cache, and HTML document requests in `next start` already reused them.

Stale entries still render dynamically while revalidation runs in the
background. Metadata-only navigations that select a fresh, fully static
entry receive the full stored payload, including page content.
parent 94bd9d49
...@@ -68,6 +68,7 @@ import { ...@@ -68,6 +68,7 @@ import {
type ResponseCacheEntry, type ResponseCacheEntry,
type ResponseGenerator, type ResponseGenerator,
} from '../../server/response-cache' with { 'turbopack-transition': 'next-server-utility' } } from '../../server/response-cache' with { 'turbopack-transition': 'next-server-utility' }
import { toResponseCacheEntry } from '../../server/response-cache/utils' with { 'turbopack-transition': 'next-server-utility' }
import { import {
FallbackMode, FallbackMode,
parseFallbackField, parseFallbackField,
...@@ -1204,6 +1205,8 @@ export function createAppPageEntrypoint({ ...@@ -1204,6 +1205,8 @@ export function createAppPageEntrypoint({
} satisfies ResponseCacheEntry } satisfies ResponseCacheEntry
} }
let isDynamicRSCResponse = isDynamicRSCRequest
const responseGenerator: ResponseGenerator = async ({ const responseGenerator: ResponseGenerator = async ({
hasResolved, hasResolved,
previousCacheEntry: previousIncrementalCacheEntry, previousCacheEntry: previousIncrementalCacheEntry,
...@@ -1526,6 +1529,29 @@ export function createAppPageEntrypoint({ ...@@ -1526,6 +1529,29 @@ export function createAppPageEntrypoint({
postponed = incrementalCacheEntry.value.postponed postponed = incrementalCacheEntry.value.postponed
hasFullyStaticCacheEntry = postponed === undefined hasFullyStaticCacheEntry = postponed === undefined
// Serve the stored RSC payload of a fresh, fully static entry to
// navigations.
if (
hasFullyStaticCacheEntry &&
incrementalCacheEntry.value.rscData !== undefined &&
!incrementalCacheEntry.isStale &&
isSSG &&
!routeModule.isDev &&
method === 'GET' &&
// Runtime prefetches still require a runtime prerender.
req.headers[NEXT_ROUTER_PREFETCH_HEADER] === undefined &&
!isOnDemandRevalidate &&
!isDebugPrerender &&
// A shared shell entry can be fully static and still contain
// placeholder values for its unresolved params in the router
// tree.
(shellCacheKey === null ||
remainingFallbackRouteParams.length === 0)
) {
isDynamicRSCResponse = false
return toResponseCacheEntry(incrementalCacheEntry)
}
// If the cache entry is stale, we should trigger a background // If the cache entry is stale, we should trigger a background
// revalidation so that subsequent requests will get a fresh response. // revalidation so that subsequent requests will get a fresh response.
if ( if (
...@@ -2045,10 +2071,9 @@ export function createAppPageEntrypoint({ ...@@ -2045,10 +2071,9 @@ export function createAppPageEntrypoint({
if ( if (
isSSG && isSSG &&
// We don't want to send a cache header for requests that contain dynamic // Static cache headers describe the response's content, even when the
// data. If this is a Dynamic RSC request or wasn't a Prefetch RSC // request is a dynamic RSC navigation.
// request, then we should set the cache header. !isDynamicRSCResponse &&
!isDynamicRSCRequest &&
(!didPostpone || isPrefetchRSCRequest) (!didPostpone || isPrefetchRSCRequest)
) { ) {
if (!isMinimalMode) { if (!isMinimalMode) {
...@@ -2080,10 +2105,8 @@ export function createAppPageEntrypoint({ ...@@ -2080,10 +2105,8 @@ export function createAppPageEntrypoint({
cacheControl = { revalidate: 0, expire: undefined } cacheControl = { revalidate: 0, expire: undefined }
} }
// If this is in minimal mode and this is a flight request that isn't a // Dynamic RSC responses contain request-time content.
// prefetch request while PPR is enabled, it cannot be cached as it contains else if (isDynamicRSCResponse) {
// dynamic content.
else if (isDynamicRSCRequest) {
cacheControl = { revalidate: 0, expire: undefined } cacheControl = { revalidate: 0, expire: undefined }
} else if (!routeModule.isDev) { } else if (!routeModule.isDev) {
// If this is a preview mode request, we shouldn't cache it // If this is a preview mode request, we shouldn't cache it
...@@ -2241,7 +2264,7 @@ export function createAppPageEntrypoint({ ...@@ -2241,7 +2264,7 @@ export function createAppPageEntrypoint({
} }
// Mark that the request did postpone. // Mark that the request did postpone.
if (didPostpone && !isDynamicRSCRequest) { if (didPostpone && !isDynamicRSCResponse) {
res.setHeader(NEXT_DID_POSTPONE_HEADER, '1') res.setHeader(NEXT_DID_POSTPONE_HEADER, '1')
} }
......
'use client'
import { useActionState } from 'react'
import { runAction } from './actions'
export function ActionButton() {
const [result, action] = useActionState(runAction, '')
return (
<form action={action}>
<button id="run-action">Run action</button>
<p id="action-result">{result}</p>
</form>
)
}
'use server'
export async function runAction() {
return 'Action executed'
}
import { randomUUID } from 'node:crypto'
import { Suspense } from 'react'
import { connection } from 'next/server'
import { ActionButton } from '../../../action-button'
import { getValue } from '../../../value'
type Params = { kind: string; slug: string }
export function generateStaticParams(): Params[] {
return [
{ kind: 'static', slug: 'built' },
{ kind: 'partial', slug: 'built' },
]
}
export async function generateMetadata({
params,
}: {
params: Promise<Params>
}) {
const { kind, slug } = await params
return { title: kind + ':' + slug }
}
async function DynamicValue() {
await connection()
return <p id="dynamic">{randomUUID()}</p>
}
export default async function Page({ params }: { params: Promise<Params> }) {
const { kind, slug } = await params
return (
<>
<p id="value">{await getValue(kind, slug)}</p>
{kind === 'partial' ? (
<Suspense fallback="Loading dynamic content...">
<DynamicValue />
</Suspense>
) : null}
<ActionButton />
</>
)
}
import { revalidateTag } from 'next/cache'
export async function POST(request: Request) {
const { tag, state } = await request.json()
revalidateTag(tag, state === 'stale' ? 'max' : { expire: 0 })
return new Response(null, { status: 204 })
}
'use client'
import { useParams } from 'next/navigation'
export default function Page() {
const params = useParams<{ prefix: string; slug: string }>()
return <p id="slug">{params?.slug}</p>
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ prefix: 'built' }]
}
export default async function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<{ prefix: string }>
}) {
const { prefix } = await params
return <section data-prefix={prefix}>{children}</section>
}
import { Suspense } from 'react'
import { LinkAccordion } from '../link-accordion'
type Props = {
searchParams: Promise<{ target?: string | string[] }>
}
async function Target({ searchParams }: Props) {
const { target } = await searchParams
if (typeof target !== 'string') {
throw new Error('Expected a single navigation target')
}
return <LinkAccordion href={target} />
}
export default function Page(props: Props) {
return (
<Suspense fallback="Loading link...">
<Target {...props} />
</Suspense>
)
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({ href }: { href: string }) {
const [visible, setVisible] = useState(false)
return (
<>
<input
id="show-target"
type="checkbox"
checked={visible}
onChange={() => setVisible(!visible)}
/>
{visible ? (
<Link id="target" href={href} prefetch={false}>
Navigate
</Link>
) : null}
</>
)
}
export default function Page() {
return <p>Cache Components static navigation</p>
}
import { randomUUID } from 'node:crypto'
import { cacheLife, cacheTag } from 'next/cache'
export async function getValue(kind: string, slug: string) {
'use cache'
cacheLife({ stale: 300, revalidate: 3600, expire: 86400 })
cacheTag('cache-components-static-navigation:' + kind + ':' + slug)
return kind + ':' + slug + ':' + randomUUID()
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { createRouterAct } from 'router-act'
import type * as Playwright from 'playwright'
import { randomUUID } from 'node:crypto'
import { load } from 'cheerio'
describe('Cache Components static navigation', () => {
const { next } = nextTestSetup({ files: __dirname })
function pathname(kind: string, slug: string) {
return '/cache-components-static-navigation/' + kind + '/' + slug
}
async function read(path: string) {
const response = await next.fetch(path)
expect(response.status).toBe(200)
const $ = load(await response.text())
return {
value: $('#value').text(),
dynamic: $('#dynamic').text(),
cache: response.headers.get('x-nextjs-cache'),
postponed: response.headers.get('x-nextjs-postponed'),
}
}
async function warm(path: string) {
return retry(async () => {
const response = await read(path)
expect(response.cache).toBe('HIT')
expect(response.postponed).toBeNull()
return response
})
}
async function navigate(path: string) {
let act: ReturnType<typeof createRouterAct>
const responses: Playwright.Response[] = []
const browser = await next.browser(
'/hub?target=' + encodeURIComponent(path),
{
beforePageLoad(page: Playwright.Page) {
act = createRouterAct(page)
page.on('response', (response) => {
const request = response.request()
const headers = request.headers()
if (
new URL(request.url()).pathname === path &&
headers.rsc === '1' &&
headers['next-router-prefetch'] === undefined &&
headers['next-action'] === undefined
) {
responses.push(response)
}
})
},
}
)
try {
await act(async () => {
await browser.elementById('show-target').click()
await browser.elementById('target').click()
})
expect(responses.length).toBeGreaterThan(0)
const received = responses.map((response) => {
expect(response.status()).toBe(200)
return { headers: response.headers() }
})
return { browser, act, responses: received }
} catch (error) {
await browser.close()
throw error
}
}
async function expectCachedNavigation(path: string, value: string) {
const navigation = await navigate(path)
try {
expect(await navigation.browser.elementById('value').text()).toBe(value)
for (const response of navigation.responses) {
expect(response.headers['x-nextjs-cache']).toBe('HIT')
expect(response.headers['x-nextjs-prerender']).toBe('1')
}
} finally {
await navigation.browser.close()
}
}
it('serves a fresh prerender generated by a document request after a restart', async () => {
const path = pathname('static', 'runtime-' + randomUUID())
const { value } = await warm(path)
expect(value).toStartWith('static:runtime-')
await next.stop()
await next.start({ skipBuild: true })
await expectCachedNavigation(path, value)
})
it('serves complete cached RSC when a metadata-only request selects a fresh fully static entry', async () => {
const path = pathname('static', 'metadata-' + randomUUID())
const { value } = await warm(path)
const response = await next.fetch(path, {
headers: {
rsc: '1',
'next-router-state-tree': encodeURIComponent(
JSON.stringify(['', {}, null, 'metadata-only'])
),
},
})
expect(response.status).toBe(200)
expect(response.headers.get('x-nextjs-cache')).toBe('HIT')
expect(await response.text()).toContain(value)
})
it("reuses a partial prerender's cached value and renders its dynamic content for each navigation", async () => {
const path = pathname('partial', 'built')
const initial = await read(path)
expect(initial.dynamic).not.toBe('')
const navigation = await navigate(path)
try {
expect(await navigation.browser.elementById('value').text()).toBe(
initial.value
)
expect(await navigation.browser.elementById('dynamic').text()).not.toBe(
initial.dynamic
)
for (const response of navigation.responses) {
expect(response.headers['x-nextjs-prerender']).toBeUndefined()
}
} finally {
await navigation.browser.close()
}
})
it('renders concrete router tree params for a shared shell with no server-side dynamic holes', async () => {
const prefix = 'shared-' + randomUUID()
const path = '/cache-components-static-navigation/shared/' + prefix
await warm(path + '/first')
// A different slug hits the same shell without a server resume.
const sibling = await read(path + '/second')
expect(sibling.cache).toBe('HIT')
expect(sibling.postponed).toBeNull()
const navigation = await navigate(path + '/third')
try {
expect(await navigation.browser.elementById('slug').text()).toBe('third')
} finally {
await navigation.browser.close()
}
})
it('executes a Server Action when a fresh fully static entry is available', async () => {
const path = pathname('static', 'action-' + randomUUID())
await warm(path)
const navigation = await navigate(path)
try {
await navigation.act(() =>
navigation.browser.elementById('run-action').click()
)
await retry(async () => {
expect(
await navigation.browser.elementById('action-result').text()
).toBe('Action executed')
})
} finally {
await navigation.browser.close()
}
})
it('runtime-prerenders a runtime prefetch instead of serving a fresh cached RSC response', async () => {
const path = pathname('static', 'prefetch-' + randomUUID())
await warm(path)
const response = await next.fetch(path, {
headers: { rsc: '1', 'next-router-prefetch': '2' },
})
expect(response.status).toBe(200)
expect(response.headers.get('x-nextjs-prerender')).toBeNull()
expect(response.headers.get('x-nextjs-cache')).toBeNull()
await response.text()
})
for (const state of ['stale', 'expired'] as const) {
it(
'renders dynamic RSC after tag revalidation marks the cached value ' +
state,
async () => {
const slug = state + '-' + randomUUID()
const path = pathname('static', slug)
await warm(path)
const response = await next.fetch(
'/cache-components-static-navigation/revalidate',
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
tag: 'cache-components-static-navigation:static:' + slug,
state,
}),
}
)
expect(response.status).toBe(204)
const navigation = await navigate(path)
try {
for (const response of navigation.responses) {
expect(response.headers['x-nextjs-prerender']).toBeUndefined()
expect(response.headers['x-nextjs-cache']).toBeUndefined()
}
} finally {
await navigation.browser.close()
}
}
)
}
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching: process.env.__NEXT_TEST_AXIS !== 'A',
}
export default nextConfig
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