Unverified Commit 27e225f4 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Fix metadata title dropped on soft navigation with Cache Components (#95315)

With `cacheComponents` + `partialPrefetching`, navigating to an
already-prefetched route with a dynamic `generateMetadata` left
`document.title` permanently empty until a hard reload.

The prefetch cached the head as complete using the server's
`isHeadPartial` flag, which is unreliable under Cache Components. Derive
the head's partiality from `isResponsePartial` instead, as segment data
already does, so a dynamic head is fetched and applied on navigation
while a fully static head stays complete.

Fixing the flag exposed a latent issue in the prefetch scheduler: during
a speculative prefetch, the head was unconditionally runtime-prefetched,
which previously went unnoticed because the head was mismarked as
complete. The head is now runtime-prefetched only when a segment in the
new part of the tree is a candidate for runtime prefetching — it rides
along with that request rather than spawning a standalone one. If
nothing in the new part of the tree is a runtime prefetch candidate, the
head is fetched during the navigation instead. This makes the
scheduler's metadata-only request path dead code, so it's removed.

Fixes #95268.

<!-- NEXT_JS_LLM_PR -->
parent 2850659b
......@@ -2989,18 +2989,21 @@ export function writeDynamicRenderResponseIntoCache(
const head = flightDataEntry.head
if (head !== null && metadataTree !== null) {
// When Cache Components is enabled, the server conservatively marks
// the head as partial during static generation (isPossiblyPartialHead
// in app-render.tsx), even for fully static pages where the head is
// actually complete. When the response is non-partial, we override
// this since the server confirmed no dynamic content exists.
// When Cache Components is enabled, the server's `isHeadPartial` flag
// (isPossiblyPartialHead in app-render.tsx) is unreliable: it's computed
// before the head is serialized, so it's conservatively `true` for every
// statically-generated PPR page — even pages whose head is actually
// complete — and it's `false` for runtime/dynamic responses whose head is
// actually partial (e.g. a route with an async `generateMetadata`). So we
// ignore it and derive the head's partiality from whether the response
// itself was partial, exactly as we do for segments (see
// `writeSeedDataIntoCache`). A non-partial response carries a complete
// head; a partial (postponed) one does not.
//
// Without Cache Components, the server always sends the correct
// isHeadPartial value, so no override is needed.
const isHeadPartial =
!isResponsePartial && process.env.__NEXT_CACHE_COMPONENTS
? false
: flightDataEntry.isHeadPartial
// Without Cache Components, the server sends the correct isHeadPartial.
const isHeadPartial = process.env.__NEXT_CACHE_COMPONENTS
? isResponsePartial
: flightDataEntry.isHeadPartial
fulfillEntrySpawnedByRuntimePrefetch(
now,
......
......@@ -27,7 +27,6 @@ import {
canNewFetchStrategyProvideMoreContent,
attemptToFulfillDynamicSegmentFromBFCache,
attemptToUpgradeSegmentFromBFCache,
MetadataOnlyRequestTree,
} from './cache'
import type { RouteCacheKey } from './cache-key'
import { createCacheKey } from './cache-key'
......@@ -851,18 +850,22 @@ function pingRootRouteTree(
? FetchStrategy.RuntimeShell
: FetchStrategy.PPRRuntime
// Always ping the runtime head — it may need to be fetched
// independently even if all runtime segments are already
// cached (e.g. navigating between siblings under a shared
// runtime layout).
const spawnedEntries = new Map<
SegmentRequestKey,
PendingSegmentCacheEntry
>()
pingRuntimeHead(now, task, route, spawnedEntries, runtimeStrategy)
// spawnedRuntimePrefetches was populated during the traversal
// above: every segment in the new part of the tree that is a
// candidate for runtime prefetching. It's derived purely from
// server hints, not cache state — it tells us whether a runtime
// request would be needed even if the cache were completely empty.
//
// If it's null, nothing in the new part of the tree is a candidate
// for runtime prefetching, and we don't fetch the head, either —
// the head is runtime prefetched only if one of the segments is.
const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches
if (spawnedRuntimePrefetches !== null) {
const spawnedEntries = new Map<
SegmentRequestKey,
PendingSegmentCacheEntry
>()
pingRuntimeHead(now, task, route, spawnedEntries, runtimeStrategy)
const requestTree = pingRuntimePrefetches(
now,
task,
......@@ -883,25 +886,6 @@ function pingRootRouteTree(
)
)
}
} else {
// No segments spawned a runtime prefetch; however, the head might
// have. If there are any spawned entries, it must have come from
// the head. Request the metadata only.
// TODO: Refactor the "request tree" format so that the metadata
// is less of a special case. Right now the logic for this is
// spread across both here
// and fetchSegmentPrefetchesUsingDynamicRequest.
if (spawnedEntries.size > 0) {
spawnPrefetchSubtask(
fetchSegmentPrefetchesUsingDynamicRequest(
task,
route,
runtimeStrategy,
MetadataOnlyRequestTree,
spawnedEntries
)
)
}
}
}
......
import { ReactNode } from 'react'
export const metadata = {
// The root layout provides a default title and a template. While a child
// route's dynamic metadata is still streaming in, the title should fall back
// to this default (or retain the previous route's title) — it must never be
// dropped to an empty string (which makes the browser tab show the URL).
title: { default: 'Home Default', template: '%s | Site' },
}
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
import { LinkAccordion } from './link-accordion'
export default function Home() {
return (
<main>
<h1 id="home">Home</h1>
<ul>
<li>
<LinkAccordion href="/slow">slow (dynamic metadata)</LinkAccordion>
</li>
<li>
<LinkAccordion href="/static-meta">
static-meta (static metadata, dynamic body)
</LinkAccordion>
</li>
</ul>
</main>
)
}
import type { Metadata } from 'next'
import { connection } from 'next/server'
import { Suspense } from 'react'
// Dynamic metadata: it reads request-time data (`connection()`), so it is not
// part of the prefetchable App Shell and must be fetched on navigation.
export async function generateMetadata(): Promise<Metadata> {
await connection()
return { title: 'Slow Page' }
}
async function DynamicContent() {
await connection()
return <p id="slow-content">Slow content</p>
}
export default function SlowPage() {
return (
<main>
<Suspense fallback={<p id="slow-fallback">loading…</p>}>
<DynamicContent />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
// STATIC metadata, but a dynamic body. The head is complete at prefetch time,
// but the page segment is still fetched dynamically on navigation.
export const metadata = {
title: 'Static Meta',
}
async function DynamicContent() {
await connection()
return <p id="static-meta-content">Static meta content</p>
}
export default function StaticMetaPage() {
return (
<main>
<Suspense fallback={<p id="static-meta-fallback">loading…</p>}>
<DynamicContent />
</Suspense>
</main>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
// Regression test for GitHub #95268: with Cache Components + `partialPrefetching`,
// the metadata `<title>` is permanently dropped after a client-side navigation
// to a route with dynamic `generateMetadata` whose prefetch has already settled.
// The prefetch caches the route's App Shell, whose head does not include the
// dynamic title; the subsequent navigation must replace that prefetched head
// with the full head from the dynamic response. Previously it did not, so the
// title never appeared (only a hard reload fixed it).
describe('metadata-soft-nav-cache-components', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('disabled in development', () => {})
return
}
it('applies dynamic metadata after navigating to an already-prefetched route', async () => {
let page: Playwright.Page = null as any
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
expect(await browser.eval(() => document.title)).toBe('Home Default')
// Reveal the link and let its prefetch fully settle (act waits for the
// prefetch requests to complete). This caches the route's App Shell, whose
// head does NOT include the dynamic metadata title.
await act(async () => {
await browser.elementByCss('input[data-link-accordion="/slow"]').click()
})
// Navigate to the now-prefetched route.
await act(
async () => {
await browser.elementByCss('a[href="/slow"]').click()
},
{ includes: 'Slow content' }
)
await browser.waitForElementByCss('#slow-content')
// The title must resolve to the route's own metadata, merged with the
// layout's template — not be permanently dropped to an empty string.
await retry(async () => {
expect(await browser.eval(() => document.title)).toBe('Slow Page | Site')
})
})
it('does not blank a complete static title when navigating to a prefetched route with a dynamic body', async () => {
let page: Playwright.Page = null as any
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
expect(await browser.eval(() => document.title)).toBe('Home Default')
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/static-meta"]')
.click()
})
await act(
async () => {
await browser.elementByCss('a[href="/static-meta"]').click()
},
{ includes: 'Static meta content' }
)
await browser.waitForElementByCss('#static-meta-content')
await retry(async () => {
expect(await browser.eval(() => document.title)).toBe(
'Static Meta | Site'
)
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
module.exports = nextConfig
......@@ -736,19 +736,23 @@ describe('prefetch inlining', () => {
)
})
it('independent head: metadata is prefetched even when no runtime segment request is needed', async () => {
it('independent head: param-dependent head is deferred to navigation, not speculatively prefetched', async () => {
// The layout at /test-independent-head/[item] uses runtime prefetching
// (reads cookies). The pages underneath it are static. The metadata
// (head) accesses both the [item] param and searchParams, making it
// depend on runtime data.
//
// When we prefetch route A, the runtime layout and head are fetched
// together. When we then prefetch sibling route B, the layout is
// already cached — no runtime segment request is needed. But the
// head is different (it includes the [item] param in the title) and
// must still be fetched via a runtime prefetch. This test verifies
// that the head is fetched independently even when no runtime segment
// request is spawned for the sibling.
// together (the layout is a runtime segment in the new part of the
// tree, so a runtime request happens and the head rides along). When
// we then prefetch sibling route B, the runtime layout is already
// shared and cached, so the new part of the tree (the [item] page) is
// fully static and needs no runtime request. Because the head is
// param-dependent it is NOT part of the reusable App Shell, and we do
// not spawn a standalone runtime request just to prefetch it — it is
// deferred to navigation. This test verifies that a speculative
// per-link prefetch fetches the static page but not the param-dependent
// head.
const data = await fetchRouteTreePrefetch(next, '/test-independent-head/a')
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
"
......
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