Unverified Commit 129368cf authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

[metadata]: ensure metadata boundary is only rendered once on client nav (#76692)

On client navigations, rendering does not start at the root, it starts
at the common layout down. As a result the existing heuristic to only
render the `<StreamingMetadata />` component once won't work, as
`children` will likely appear for parallel routes within the subtree.
(In other words: `children` is only useful as a heuristic for root
renders).

As a result, metadata will get duplicated on client navigation if
parallel routes match that page (this is because we iterate over all
parallel routes, and conditionally render `<StreamingMetadata />` based
on the flawed heuristic above)

Since the metadata tree is accumulated and only rendered once, ideally
it should never be rendered in `createComponentTree`. Or if it is, we
need to ensure it’s never rendered more than once, as it would contain
the same contents twice.

This PR:
- On client navs, ensures that we only render `<StreamingMetadata />`
once as part of the `rscHead`, rather than per parallel route segment:
[5e3686a](https://github.com/vercel/next.js/pull/76692/commits/5e3686ac55c0020ab843e8a2648f180ad9f33ca6)
- On the client, we make sure to prioritize the `head` node
corresponding with the root page slot ("children"). Otherwise we might
not render `<StreamingMetadata />` at all, since the current heuristic
would have early-returned for a parallel route that _didn't_ change as
part of the navigation (eg the case where a slot doesn't match, and
keeps rendering the previous node):
[7364e6e](https://github.com/vercel/next.js/pull/76692/commits/7364e6e008dfb99b454267ff6a7b4a080a9f3d08)
parent 4bf1ee11
...@@ -19,7 +19,30 @@ function findHeadInCacheImpl( ...@@ -19,7 +19,30 @@ function findHeadInCacheImpl(
// Returns the entire Cache Node of the segment whose head we will render. // Returns the entire Cache Node of the segment whose head we will render.
return [cache, keyPrefix] return [cache, keyPrefix]
} }
// First try the 'children' parallel route if it exists
// when starting from the "root", this corresponds with the main page component
if (parallelRoutes.children) {
const [segment, childParallelRoutes] = parallelRoutes.children
const childSegmentMap = cache.parallelRoutes.get('children')
if (childSegmentMap) {
const cacheKey = createRouterCacheKey(segment)
const cacheNode = childSegmentMap.get(cacheKey)
if (cacheNode) {
const item = findHeadInCacheImpl(
cacheNode,
childParallelRoutes,
keyPrefix + '/' + cacheKey
)
if (item) return item
}
}
}
// if we didn't find metadata in the page slot, check the other parallel routes
for (const key in parallelRoutes) { for (const key in parallelRoutes) {
if (key === 'children') continue // already checked above
const [segment, childParallelRoutes] = parallelRoutes[key] const [segment, childParallelRoutes] = parallelRoutes[key]
const childSegmentMap = cache.parallelRoutes.get(key) const childSegmentMap = cache.parallelRoutes.get(key)
if (!childSegmentMap) { if (!childSegmentMap) {
......
...@@ -522,6 +522,7 @@ async function generateDynamicRSCPayload( ...@@ -522,6 +522,7 @@ async function generateDynamicRSCPayload(
<NonIndex ctx={ctx} /> <NonIndex ctx={ctx} />
{/* Adding requestId as react key to make metadata remount for each render */} {/* Adding requestId as react key to make metadata remount for each render */}
<ViewportTree key={requestId} /> <ViewportTree key={requestId} />
{StreamingMetadata ? <StreamingMetadata /> : null}
<StaticMetadata /> <StaticMetadata />
</React.Fragment> </React.Fragment>
), ),
...@@ -532,7 +533,6 @@ async function generateDynamicRSCPayload( ...@@ -532,7 +533,6 @@ async function generateDynamicRSCPayload(
getViewportReady, getViewportReady,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
StreamingMetadata,
StreamingMetadataOutlet, StreamingMetadataOutlet,
}) })
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
......
...@@ -40,7 +40,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -40,7 +40,6 @@ export async function walkTreeWithFlightRouterState({
getMetadataReady, getMetadataReady,
ctx, ctx,
preloadCallbacks, preloadCallbacks,
StreamingMetadata,
StreamingMetadataOutlet, StreamingMetadataOutlet,
}: { }: {
loaderTreeToFilter: LoaderTree loaderTreeToFilter: LoaderTree
...@@ -56,8 +55,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -56,8 +55,7 @@ export async function walkTreeWithFlightRouterState({
getViewportReady: () => Promise<void> getViewportReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
StreamingMetadata: React.ComponentType<{}> | null StreamingMetadataOutlet: React.ComponentType
StreamingMetadataOutlet: React.ComponentType<{}>
}): Promise<FlightDataPath[]> { }): Promise<FlightDataPath[]> {
const { const {
renderOpts: { nextFontManifest, experimental }, renderOpts: { nextFontManifest, experimental },
...@@ -206,7 +204,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -206,7 +204,7 @@ export async function walkTreeWithFlightRouterState({
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
authInterrupts: experimental.authInterrupts, authInterrupts: experimental.authInterrupts,
StreamingMetadata, StreamingMetadata: null,
StreamingMetadataOutlet, StreamingMetadataOutlet,
} }
) )
...@@ -267,7 +265,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -267,7 +265,6 @@ export async function walkTreeWithFlightRouterState({
getViewportReady, getViewportReady,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
StreamingMetadata,
StreamingMetadataOutlet, StreamingMetadataOutlet,
}) })
......
export default function Page() {
return 'test-page @bar'
}
export default function Page() {
return 'no-bar @foo'
}
export default function Page() {
return 'test-page @foo'
}
import { connection } from 'next/server'
export default function TestPage() {
return 'test page'
}
export async function generateMetadata() {
await connection()
await new Promise((resolve) => setTimeout(resolve, 3000))
return {
title: `Dynamic api ${Math.random()}`,
}
}
import Link from 'next/link'
export default function Page() { export default function Page() {
return <div>Hello from Nested</div> return (
<div>
Hello from Nested{' '}
<Link href="/parallel-routes/test-page">
To /parallel-routes/test-page
</Link>
<Link href="/parallel-routes/no-bar">To /parallel-routes/no-bar</Link>
</div>
)
} }
export const metadata = { export const metadata = {
......
import { connection } from 'next/server'
export default function TestPage() {
return 'test page'
}
export async function generateMetadata() {
await connection()
await new Promise((resolve) => setTimeout(resolve, 3000))
return {
title: `Dynamic api ${Math.random()}`,
}
}
...@@ -88,7 +88,7 @@ describe('app-dir - metadata-streaming', () => { ...@@ -88,7 +88,7 @@ describe('app-dir - metadata-streaming', () => {
expect((await browser.elementsByCss('body meta')).length).toBe(9) expect((await browser.elementsByCss('body meta')).length).toBe(9)
}) })
it('should only insert metadata once for parallel routes', async () => { it('should only insert metadata once for parallel routes when slots match', async () => {
const browser = await next.browser('/parallel-routes') const browser = await next.browser('/parallel-routes')
expect((await browser.elementsByCss('head title')).length).toBe(1) expect((await browser.elementsByCss('head title')).length).toBe(1)
...@@ -96,6 +96,30 @@ describe('app-dir - metadata-streaming', () => { ...@@ -96,6 +96,30 @@ describe('app-dir - metadata-streaming', () => {
const $ = await next.render$('/parallel-routes') const $ = await next.render$('/parallel-routes')
expect($('title').length).toBe(1) expect($('title').length).toBe(1)
// validate behavior remains the same on client navigations
await browser.elementByCss('[href="/parallel-routes/test-page"]').click()
await retry(async () => {
expect(await browser.elementByCss('title').text()).toContain(
'Dynamic api'
)
})
expect((await browser.elementsByCss('title')).length).toBe(1)
})
it('should only insert metadata once for parallel routes when there is a missing slot', async () => {
const browser = await next.browser('/parallel-routes')
await browser.elementByCss('[href="/parallel-routes/no-bar"]').click()
await retry(async () => {
expect(await browser.elementByCss('title').text()).toContain(
'Dynamic api'
)
})
expect((await browser.elementsByCss('title')).length).toBe(1)
}) })
describe('dynamic api', () => { describe('dynamic api', () => {
......
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