Unverified Commit 7d42c9dc authored by Josh Story's avatar Josh Story Committed by GitHub

Keep metadata rendering stable across streaming modes (#97440)

## Motivation

Streaming and blocking metadata previously used different rendering
paths. Metadata placement should depend on when Next.js starts consuming
the response, rather than requiring the metadata component itself to
render outside Suspense.

## What this does

Selected metadata now always renders through the same hidden Suspense
boundary. For blocking responses, an always-present `MetadataBlocker`
waits for the same cached resolution before Next.js pulls the response,
ensuring metadata remains in the document head.

`MetadataOutlet` remains a single promise. It renders inside Suspense
for streaming responses and outside Suspense for blocking responses so
navigation and regular errors retain their existing behavior.

HTML-limited bot requests continue to bypass PPR shells. A prerendered
shell has already closed its head before dynamic metadata resolves, so
resuming that shell cannot provide blocking metadata in the raw head.

## Review notes

- Metadata resolution still starts from a rendered component so the
active `workUnitStore` and React cache scope are available.
- Fizz may begin rendering before metadata settles; blocking is enforced
before Next.js starts pulling the response.
- The hidden wrapper keeps top-level suspenseful metadata out of the
document preamble. Metadata tags hoist out, so the wrapper remains
empty.
- The Cache Components blocking and hydration coverage runs with
parallel metadata both disabled and enabled.

## Verification

- `pnpm build-all`
- `pnpm test-start-turbo
test/e2e/app-dir/metadata-streaming-cache-components/metadata-streaming-cache-components-custom-bots.test.ts`
- `pnpm test-start-webpack
test/e2e/app-dir/metadata-streaming-cache-components/metadata-streaming-cache-components-custom-bots.test.ts`

<!-- NEXT_JS_LLM -->
parent cb469ded
...@@ -529,9 +529,10 @@ export function createAppPageEntrypoint({ ...@@ -529,9 +529,10 @@ export function createAppPageEntrypoint({
? true ? true
: shouldServeStreamingMetadata(userAgent, nextConfig.htmlLimitedBots) : shouldServeStreamingMetadata(userAgent, nextConfig.htmlLimitedBots)
// PPR shells are generated for streaming metadata. Requests that require // A PPR shell has already closed its head before the dynamic render resumes.
// blocking metadata must bypass the shell so the prerender and dynamic // Blocking metadata resolved during the resume would therefore be emitted
// render use the same metadata tree. // after the head, where HTML-limited bots cannot observe it. Bypass the
// shell so blocking metadata is included in the initial document head.
const shouldForceDynamicPPRRender = const shouldForceDynamicPPRRender =
isRoutePPREnabled && !serveStreamingMetadata isRoutePPREnabled && !serveStreamingMetadata
......
...@@ -98,8 +98,10 @@ export function createMetadataComponents({ ...@@ -98,8 +98,10 @@ export function createMetadataComponents({
) )
} }
async function Metadata() { // Metadata resolution must start while rendering so it observes the current
const tags = await getResolvedParallelMetadata( // work unit store.
function getSelectedMetadata() {
return getResolvedParallelMetadata(
tree, tree,
pathnameForMetadata, pathnameForMetadata,
searchParams, searchParams,
...@@ -110,30 +112,35 @@ export function createMetadataComponents({ ...@@ -110,30 +112,35 @@ export function createMetadataComponents({
// We're going to throw the error from the metadata outlet so we just render null here instead // We're going to throw the error from the metadata outlet so we just render null here instead
return null return null
}) })
}
return tags async function Metadata() {
return await getSelectedMetadata()
} }
Metadata.displayName = 'Next.Metadata' Metadata.displayName = 'Next.Metadata'
function MetadataBlocker() {
return serveStreamingMetadata
? null
: getSelectedMetadata().then(() => null)
}
function MetadataWrapper() { function MetadataWrapper() {
// TODO: We shouldn't change what we render based on whether we are streaming or not. // Keep the same component structure in streaming and blocking renders.
// If we aren't streaming we should just block the response until we have resolved the // The blocker only holds the shell open when metadata must not stream.
// metadata. // React requires top-level suspenseful metadata to be nested under a host
if (!serveStreamingMetadata) { // element. Otherwise it becomes part of the document preamble and blocks
return ( // shell flushing instead of streaming. Metadata tags are hoisted out, so
<MetadataBoundary> // this hidden wrapper remains empty.
<Metadata />
</MetadataBoundary>
)
}
return ( return (
<div hidden> <MetadataBoundary>
<MetadataBoundary> <div hidden>
<Suspense name="Next.Metadata"> <Suspense name="Next.Metadata">
<Metadata /> <Metadata />
</Suspense> </Suspense>
</MetadataBoundary> </div>
</div> <MetadataBlocker />
</MetadataBoundary>
) )
} }
...@@ -150,12 +157,10 @@ export function createMetadataComponents({ ...@@ -150,12 +157,10 @@ export function createMetadataComponents({
(resolution) => resolution.outlets.get(outletTree) ?? null (resolution) => resolution.outlets.get(outletTree) ?? null
) )
// TODO: We shouldn't change what we render based on whether we are streaming or not.
// If we aren't streaming we should just block the response until we have resolved the
// metadata.
if (!serveStreamingMetadata) { if (!serveStreamingMetadata) {
return <OutletBoundary>{pendingOutlet}</OutletBoundary> return <OutletBoundary>{pendingOutlet}</OutletBoundary>
} }
return ( return (
<OutletBoundary> <OutletBoundary>
<Suspense name="Next.MetadataOutlet">{pendingOutlet}</Suspense> <Suspense name="Next.MetadataOutlet">{pendingOutlet}</Suspense>
......
...@@ -84,8 +84,10 @@ export function createMetadataComponents({ ...@@ -84,8 +84,10 @@ export function createMetadataComponents({
) )
} }
async function Metadata() { // Metadata resolution must start while rendering so it observes the current
const tags = await getResolvedMetadata( // work unit store.
function getSelectedMetadata() {
return getResolvedMetadata(
tree, tree,
pathnameForMetadata, pathnameForMetadata,
searchParams, searchParams,
...@@ -105,30 +107,35 @@ export function createMetadataComponents({ ...@@ -105,30 +107,35 @@ export function createMetadataComponents({
// We're going to throw the error from the metadata outlet so we just render null here instead // We're going to throw the error from the metadata outlet so we just render null here instead
return null return null
}) })
}
return tags async function Metadata() {
return await getSelectedMetadata()
} }
Metadata.displayName = 'Next.Metadata' Metadata.displayName = 'Next.Metadata'
function MetadataBlocker() {
return serveStreamingMetadata
? null
: getSelectedMetadata().then(() => null)
}
function MetadataWrapper() { function MetadataWrapper() {
// TODO: We shouldn't change what we render based on whether we are streaming or not. // Keep the same component structure in streaming and blocking renders.
// If we aren't streaming we should just block the response until we have resolved the // The blocker only holds the shell open when metadata must not stream.
// metadata. // React requires top-level suspenseful metadata to be nested under a host
if (!serveStreamingMetadata) { // element. Otherwise it becomes part of the document preamble and blocks
return ( // shell flushing instead of streaming. Metadata tags are hoisted out, so
<MetadataBoundary> // this hidden wrapper remains empty.
<Metadata />
</MetadataBoundary>
)
}
return ( return (
<div hidden> <MetadataBoundary>
<MetadataBoundary> <div hidden>
<Suspense name="Next.Metadata"> <Suspense name="Next.Metadata">
<Metadata /> <Metadata />
</Suspense> </Suspense>
</MetadataBoundary> </div>
</div> <MetadataBlocker />
</MetadataBoundary>
) )
} }
...@@ -145,12 +152,10 @@ export function createMetadataComponents({ ...@@ -145,12 +152,10 @@ export function createMetadataComponents({
getResolvedViewport(tree, searchParams, interpolatedParams, errorType), getResolvedViewport(tree, searchParams, interpolatedParams, errorType),
]).then(() => null) ]).then(() => null)
// TODO: We shouldn't change what we render based on whether we are streaming or not.
// If we aren't streaming we should just block the response until we have resolved the
// metadata.
if (!serveStreamingMetadata) { if (!serveStreamingMetadata) {
return <OutletBoundary>{pendingOutlet}</OutletBoundary> return <OutletBoundary>{pendingOutlet}</OutletBoundary>
} }
return ( return (
<OutletBoundary> <OutletBoundary>
<Suspense name="Next.MetadataOutlet">{pendingOutlet}</Suspense> <Suspense name="Next.MetadataOutlet">{pendingOutlet}</Suspense>
......
import { isNextDev, nextTestSetup } from 'e2e-utils' import { isNextDev, nextTestSetup } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { assertNoConsoleErrors } from 'next-test-utils'
const describeCacheComponents = isNextDev ? describe.skip : describe const describeCacheComponents = isNextDev ? describe.skip : describe
describeCacheComponents('metadata streaming with a custom bot list', () => { function runCustomBotTests(parallelRouteMetadata: boolean) {
const { next, isNextDeploy } = nextTestSetup({ const { next, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
overrideFiles: {
'next.config.js': `
module.exports = {
cacheComponents: true,
htmlLimitedBots: /MyBot/i,
experimental: {
parallelRouteMetadata: ${parallelRouteMetadata},
},
}
`,
},
}) })
it('should serve a fully dynamic render with blocking metadata to a configured HTML-limited bot', async () => { it('should serve a fully dynamic render with blocking metadata to a configured HTML-limited bot', async () => {
...@@ -56,6 +68,20 @@ describeCacheComponents('metadata streaming with a custom bot list', () => { ...@@ -56,6 +68,20 @@ describeCacheComponents('metadata streaming with a custom bot list', () => {
expect($('#dynamic-content').text()).toBe('dynamic content') expect($('#dynamic-content').text()).toBe('dynamic content')
}) })
it('should hydrate blocking metadata without errors', async () => {
const browser = await next.browser('/partial', {
userAgent: 'MyBot',
pushErrorAsConsoleLog: true,
})
expect(
await browser
.waitForElementByCss('head title', { state: 'attached' })
.text()
).toBe('dynamic title')
await assertNoConsoleErrors(browser)
})
it('should continue streaming the body after blocking metadata for a configured HTML-limited bot', async () => { it('should continue streaming the body after blocking metadata for a configured HTML-limited bot', async () => {
const abortController = new AbortController() const abortController = new AbortController()
let body: let body:
...@@ -135,7 +161,14 @@ describeCacheComponents('metadata streaming with a custom bot list', () => { ...@@ -135,7 +161,14 @@ describeCacheComponents('metadata streaming with a custom bot list', () => {
expect($('body title').text()).toBe('dynamic title') expect($('body title').text()).toBe('dynamic title')
expect($('#dynamic-content').text()).toBe('dynamic content') expect($('#dynamic-content').text()).toBe('dynamic content')
}) })
}) }
describeCacheComponents.each([false, true])(
'metadata streaming with a custom bot list (parallelRouteMetadata: %s)',
(parallelRouteMetadata) => {
runCustomBotTests(parallelRouteMetadata)
}
)
;(isNextDev ? describe.skip : describe)( ;(isNextDev ? describe.skip : describe)(
'metadata streaming with Cache Components and a built-in bot in the custom pattern', 'metadata streaming with Cache Components and a built-in bot in the custom pattern',
() => { () => {
......
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