Skip to content

Commit 27e225f

Browse files
authored
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 -->
1 parent 2850659 commit 27e225f

10 files changed

Lines changed: 255 additions & 48 deletions

File tree

‎packages/next/src/client/components/segment-cache/cache.ts‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2989,18 +2989,21 @@ export function writeDynamicRenderResponseIntoCache(
29892989

29902990
const head = flightDataEntry.head
29912991
if (head !== null && metadataTree !== null) {
2992-
// When Cache Components is enabled, the server conservatively marks
2993-
// the head as partial during static generation (isPossiblyPartialHead
2994-
// in app-render.tsx), even for fully static pages where the head is
2995-
// actually complete. When the response is non-partial, we override
2996-
// this since the server confirmed no dynamic content exists.
2992+
// When Cache Components is enabled, the server's `isHeadPartial` flag
2993+
// (isPossiblyPartialHead in app-render.tsx) is unreliable: it's computed
2994+
// before the head is serialized, so it's conservatively `true` for every
2995+
// statically-generated PPR page — even pages whose head is actually
2996+
// complete — and it's `false` for runtime/dynamic responses whose head is
2997+
// actually partial (e.g. a route with an async `generateMetadata`). So we
2998+
// ignore it and derive the head's partiality from whether the response
2999+
// itself was partial, exactly as we do for segments (see
3000+
// `writeSeedDataIntoCache`). A non-partial response carries a complete
3001+
// head; a partial (postponed) one does not.
29973002
//
2998-
// Without Cache Components, the server always sends the correct
2999-
// isHeadPartial value, so no override is needed.
3000-
const isHeadPartial =
3001-
!isResponsePartial && process.env.__NEXT_CACHE_COMPONENTS
3002-
? false
3003-
: flightDataEntry.isHeadPartial
3003+
// Without Cache Components, the server sends the correct isHeadPartial.
3004+
const isHeadPartial = process.env.__NEXT_CACHE_COMPONENTS
3005+
? isResponsePartial
3006+
: flightDataEntry.isHeadPartial
30043007

30053008
fulfillEntrySpawnedByRuntimePrefetch(
30063009
now,

‎packages/next/src/client/components/segment-cache/scheduler.ts‎

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ import {
2727
canNewFetchStrategyProvideMoreContent,
2828
attemptToFulfillDynamicSegmentFromBFCache,
2929
attemptToUpgradeSegmentFromBFCache,
30-
MetadataOnlyRequestTree,
3130
} from './cache'
3231
import type { RouteCacheKey } from './cache-key'
3332
import { createCacheKey } from './cache-key'
@@ -851,18 +850,22 @@ function pingRootRouteTree(
851850
? FetchStrategy.RuntimeShell
852851
: FetchStrategy.PPRRuntime
853852

854-
// Always ping the runtime head — it may need to be fetched
855-
// independently even if all runtime segments are already
856-
// cached (e.g. navigating between siblings under a shared
857-
// runtime layout).
858-
const spawnedEntries = new Map<
859-
SegmentRequestKey,
860-
PendingSegmentCacheEntry
861-
>()
862-
pingRuntimeHead(now, task, route, spawnedEntries, runtimeStrategy)
863-
853+
// spawnedRuntimePrefetches was populated during the traversal
854+
// above: every segment in the new part of the tree that is a
855+
// candidate for runtime prefetching. It's derived purely from
856+
// server hints, not cache state — it tells us whether a runtime
857+
// request would be needed even if the cache were completely empty.
858+
//
859+
// If it's null, nothing in the new part of the tree is a candidate
860+
// for runtime prefetching, and we don't fetch the head, either —
861+
// the head is runtime prefetched only if one of the segments is.
864862
const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches
865863
if (spawnedRuntimePrefetches !== null) {
864+
const spawnedEntries = new Map<
865+
SegmentRequestKey,
866+
PendingSegmentCacheEntry
867+
>()
868+
pingRuntimeHead(now, task, route, spawnedEntries, runtimeStrategy)
866869
const requestTree = pingRuntimePrefetches(
867870
now,
868871
task,
@@ -883,25 +886,6 @@ function pingRootRouteTree(
883886
)
884887
)
885888
}
886-
} else {
887-
// No segments spawned a runtime prefetch; however, the head might
888-
// have. If there are any spawned entries, it must have come from
889-
// the head. Request the metadata only.
890-
// TODO: Refactor the "request tree" format so that the metadata
891-
// is less of a special case. Right now the logic for this is
892-
// spread across both here
893-
// and fetchSegmentPrefetchesUsingDynamicRequest.
894-
if (spawnedEntries.size > 0) {
895-
spawnPrefetchSubtask(
896-
fetchSegmentPrefetchesUsingDynamicRequest(
897-
task,
898-
route,
899-
runtimeStrategy,
900-
MetadataOnlyRequestTree,
901-
spawnedEntries
902-
)
903-
)
904-
}
905889
}
906890
}
907891

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { ReactNode } from 'react'
2+
3+
export const metadata = {
4+
// The root layout provides a default title and a template. While a child
5+
// route's dynamic metadata is still streaming in, the title should fall back
6+
// to this default (or retain the previous route's title) — it must never be
7+
// dropped to an empty string (which makes the browser tab show the URL).
8+
title: { default: 'Home Default', template: '%s | Site' },
9+
}
10+
11+
export default function RootLayout({ children }: { children: ReactNode }) {
12+
return (
13+
<html lang="en">
14+
<body>{children}</body>
15+
</html>
16+
)
17+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use client'
2+
3+
import Link, { type LinkProps } from 'next/link'
4+
import { useState } from 'react'
5+
6+
export function LinkAccordion({
7+
href,
8+
children,
9+
prefetch,
10+
}: {
11+
href: string
12+
children: React.ReactNode
13+
prefetch?: LinkProps['prefetch']
14+
}) {
15+
const [isVisible, setIsVisible] = useState(false)
16+
return (
17+
<>
18+
<input
19+
type="checkbox"
20+
checked={isVisible}
21+
onChange={() => setIsVisible(!isVisible)}
22+
data-link-accordion={href}
23+
/>
24+
{isVisible ? (
25+
<Link href={href} prefetch={prefetch}>
26+
{children}
27+
</Link>
28+
) : (
29+
`${children} (link is hidden)`
30+
)}
31+
</>
32+
)
33+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { LinkAccordion } from './link-accordion'
2+
3+
export default function Home() {
4+
return (
5+
<main>
6+
<h1 id="home">Home</h1>
7+
<ul>
8+
<li>
9+
<LinkAccordion href="/slow">slow (dynamic metadata)</LinkAccordion>
10+
</li>
11+
<li>
12+
<LinkAccordion href="/static-meta">
13+
static-meta (static metadata, dynamic body)
14+
</LinkAccordion>
15+
</li>
16+
</ul>
17+
</main>
18+
)
19+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import type { Metadata } from 'next'
2+
import { connection } from 'next/server'
3+
import { Suspense } from 'react'
4+
5+
// Dynamic metadata: it reads request-time data (`connection()`), so it is not
6+
// part of the prefetchable App Shell and must be fetched on navigation.
7+
export async function generateMetadata(): Promise<Metadata> {
8+
await connection()
9+
return { title: 'Slow Page' }
10+
}
11+
12+
async function DynamicContent() {
13+
await connection()
14+
return <p id="slow-content">Slow content</p>
15+
}
16+
17+
export default function SlowPage() {
18+
return (
19+
<main>
20+
<Suspense fallback={<p id="slow-fallback">loading…</p>}>
21+
<DynamicContent />
22+
</Suspense>
23+
</main>
24+
)
25+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { Suspense } from 'react'
2+
import { connection } from 'next/server'
3+
4+
// STATIC metadata, but a dynamic body. The head is complete at prefetch time,
5+
// but the page segment is still fetched dynamically on navigation.
6+
export const metadata = {
7+
title: 'Static Meta',
8+
}
9+
10+
async function DynamicContent() {
11+
await connection()
12+
return <p id="static-meta-content">Static meta content</p>
13+
}
14+
15+
export default function StaticMetaPage() {
16+
return (
17+
<main>
18+
<Suspense fallback={<p id="static-meta-fallback">loading…</p>}>
19+
<DynamicContent />
20+
</Suspense>
21+
</main>
22+
)
23+
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { nextTestSetup } from 'e2e-utils'
2+
import { retry } from 'next-test-utils'
3+
import type * as Playwright from 'playwright'
4+
import { createRouterAct } from 'router-act'
5+
6+
// Regression test for GitHub #95268: with Cache Components + `partialPrefetching`,
7+
// the metadata `<title>` is permanently dropped after a client-side navigation
8+
// to a route with dynamic `generateMetadata` whose prefetch has already settled.
9+
// The prefetch caches the route's App Shell, whose head does not include the
10+
// dynamic title; the subsequent navigation must replace that prefetched head
11+
// with the full head from the dynamic response. Previously it did not, so the
12+
// title never appeared (only a hard reload fixed it).
13+
describe('metadata-soft-nav-cache-components', () => {
14+
const { next, isNextDev } = nextTestSetup({
15+
files: __dirname,
16+
})
17+
18+
if (isNextDev) {
19+
test('disabled in development', () => {})
20+
return
21+
}
22+
23+
it('applies dynamic metadata after navigating to an already-prefetched route', async () => {
24+
let page: Playwright.Page = null as any
25+
const browser = await next.browser('/', {
26+
beforePageLoad(p: Playwright.Page) {
27+
page = p
28+
},
29+
})
30+
const act = createRouterAct(page, { includeAppShellRequests: true })
31+
32+
expect(await browser.eval(() => document.title)).toBe('Home Default')
33+
34+
// Reveal the link and let its prefetch fully settle (act waits for the
35+
// prefetch requests to complete). This caches the route's App Shell, whose
36+
// head does NOT include the dynamic metadata title.
37+
await act(async () => {
38+
await browser.elementByCss('input[data-link-accordion="/slow"]').click()
39+
})
40+
41+
// Navigate to the now-prefetched route.
42+
await act(
43+
async () => {
44+
await browser.elementByCss('a[href="/slow"]').click()
45+
},
46+
{ includes: 'Slow content' }
47+
)
48+
49+
await browser.waitForElementByCss('#slow-content')
50+
51+
// The title must resolve to the route's own metadata, merged with the
52+
// layout's template — not be permanently dropped to an empty string.
53+
await retry(async () => {
54+
expect(await browser.eval(() => document.title)).toBe('Slow Page | Site')
55+
})
56+
})
57+
58+
it('does not blank a complete static title when navigating to a prefetched route with a dynamic body', async () => {
59+
let page: Playwright.Page = null as any
60+
const browser = await next.browser('/', {
61+
beforePageLoad(p: Playwright.Page) {
62+
page = p
63+
},
64+
})
65+
const act = createRouterAct(page, { includeAppShellRequests: true })
66+
67+
expect(await browser.eval(() => document.title)).toBe('Home Default')
68+
69+
await act(async () => {
70+
await browser
71+
.elementByCss('input[data-link-accordion="/static-meta"]')
72+
.click()
73+
})
74+
75+
await act(
76+
async () => {
77+
await browser.elementByCss('a[href="/static-meta"]').click()
78+
},
79+
{ includes: 'Static meta content' }
80+
)
81+
82+
await browser.waitForElementByCss('#static-meta-content')
83+
84+
await retry(async () => {
85+
expect(await browser.eval(() => document.title)).toBe(
86+
'Static Meta | Site'
87+
)
88+
})
89+
})
90+
})
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
/**
2+
* @type {import('next').NextConfig}
3+
*/
4+
const nextConfig = {
5+
cacheComponents: true,
6+
partialPrefetching: true,
7+
}
8+
9+
module.exports = nextConfig

‎test/e2e/app-dir/segment-cache/prefetch-inlining/prefetch-inlining.test.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -736,19 +736,23 @@ describe('prefetch inlining', () => {
736736
)
737737
})
738738

739-
it('independent head: metadata is prefetched even when no runtime segment request is needed', async () => {
739+
it('independent head: param-dependent head is deferred to navigation, not speculatively prefetched', async () => {
740740
// The layout at /test-independent-head/[item] uses runtime prefetching
741741
// (reads cookies). The pages underneath it are static. The metadata
742742
// (head) accesses both the [item] param and searchParams, making it
743743
// depend on runtime data.
744744
//
745745
// When we prefetch route A, the runtime layout and head are fetched
746-
// together. When we then prefetch sibling route B, the layout is
747-
// already cached — no runtime segment request is needed. But the
748-
// head is different (it includes the [item] param in the title) and
749-
// must still be fetched via a runtime prefetch. This test verifies
750-
// that the head is fetched independently even when no runtime segment
751-
// request is spawned for the sibling.
746+
// together (the layout is a runtime segment in the new part of the
747+
// tree, so a runtime request happens and the head rides along). When
748+
// we then prefetch sibling route B, the runtime layout is already
749+
// shared and cached, so the new part of the tree (the [item] page) is
750+
// fully static and needs no runtime request. Because the head is
751+
// param-dependent it is NOT part of the reusable App Shell, and we do
752+
// not spawn a standalone runtime request just to prefetch it — it is
753+
// deferred to navigation. This test verifies that a speculative
754+
// per-link prefetch fetches the static page but not the param-dependent
755+
// head.
752756
const data = await fetchRouteTreePrefetch(next, '/test-independent-head/a')
753757
expect(renderInliningTree(data.tree)).toMatchInlineSnapshot(`
754758
"

0 commit comments

Comments
 (0)