Unverified Commit cc4879d1 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Move metadata error under error boundaries (#53551)

### What & Why

Using `notFound()` in `generateMetadata()` or in page will lead to unacught global not found error when you do navigation, this is because `head` cache is actually not inside the error boundary as designed to stay in the beginning of the content. But in this way we won't be able to catch the notFound error thrown from metadata API. So we created a new approach that can separate the error itself from metadata result, and throw as error under the error boundaries, and metadata itself will always be safe to render.

### How

We use a new promise that resolve the `error` thrown from metadata resolving, and let the render result always return successfully and always has a value, using default metadata when there's error thrown. Create two components, one rendering the metadata tags, and another `MetadataOutlet` to throw the error when the resolving is failed but rendered under error boundaries.



```jsx
const [MetadataTree, MetadataOutlet] = createMetadataComponents(/*...*/)
const ComponentTree = createComponentTree({ metadataOutlet: <MetadataOutlet /> })

renderRSC(
  <AppRourer head={<MetadataTree />}>
    <ComponentTree />
  </AppRourer>
)
```

`metadataOutlet` will stay next to page component in the layout hierarchy

discuessed with @gnoff 

Minor changes: 

* When there's rendering root layout layer, not found boundary should be `DefaultNotFound` if the custom one doesn't exisit


Fixes #53371
Fixes #53149
parent f04dc5ad
...@@ -21,8 +21,13 @@ import { MetaFilter } from './generate/meta' ...@@ -21,8 +21,13 @@ import { MetaFilter } from './generate/meta'
import { ResolvedMetadata } from './types/metadata-interface' import { ResolvedMetadata } from './types/metadata-interface'
import { createDefaultMetadata } from './default-metadata' import { createDefaultMetadata } from './default-metadata'
// Generate the actual React elements from the resolved metadata. // Use a promise to share the status of the metadata resolving,
export async function MetadataTree({ // returning two components `MetadataTree` and `MetadataOutlet`
// `MetadataTree` is the one that will be rendered at first in the content sequence for metadata tags.
// `MetadataOutlet` is the one that will be rendered under error boundaries for metadata resolving errors.
// In this way we can let the metadata tags always render successfully,
// and the error will be caught by the error boundary and trigger fallbacks.
export function createMetadataComponents({
tree, tree,
pathname, pathname,
searchParams, searchParams,
...@@ -36,11 +41,21 @@ export async function MetadataTree({ ...@@ -36,11 +41,21 @@ export async function MetadataTree({
getDynamicParamFromSegment: GetDynamicParamFromSegment getDynamicParamFromSegment: GetDynamicParamFromSegment
appUsingSizeAdjust: boolean appUsingSizeAdjust: boolean
errorType?: 'not-found' | 'redirect' errorType?: 'not-found' | 'redirect'
}) { }): [React.ComponentType, React.ComponentType] {
const metadataContext = { const metadataContext = {
pathname, pathname,
} }
let resolve: (value: Error | undefined) => void | undefined
// Only use promise.resolve here to avoid unhandled rejections
const metadataErrorResolving = new Promise<Error | undefined>((res) => {
resolve = res
})
async function MetadataTree() {
const defaultMetadata = createDefaultMetadata()
let metadata: ResolvedMetadata | undefined = defaultMetadata
try {
const resolvedMetadata = await resolveMetadata({ const resolvedMetadata = await resolveMetadata({
tree, tree,
parentParams: {}, parentParams: {},
...@@ -49,15 +64,17 @@ export async function MetadataTree({ ...@@ -49,15 +64,17 @@ export async function MetadataTree({
getDynamicParamFromSegment, getDynamicParamFromSegment,
errorConvention: errorType === 'redirect' ? undefined : errorType, errorConvention: errorType === 'redirect' ? undefined : errorType,
}) })
let metadata: ResolvedMetadata | undefined = undefined
const defaultMetadata = createDefaultMetadata()
// Skip for redirect case as for the temporary redirect case we don't need the metadata on client // Skip for redirect case as for the temporary redirect case we don't need the metadata on client
if (errorType === 'redirect') { if (errorType === 'redirect') {
metadata = defaultMetadata metadata = defaultMetadata
} else { } else {
metadata = await accumulateMetadata(resolvedMetadata, metadataContext) metadata = await accumulateMetadata(resolvedMetadata, metadataContext)
} }
resolve(undefined)
} catch (error: any) {
resolve(error)
}
const elements = MetaFilter([ const elements = MetaFilter([
BasicMetadata({ metadata }), BasicMetadata({ metadata }),
...@@ -81,4 +98,16 @@ export async function MetadataTree({ ...@@ -81,4 +98,16 @@ export async function MetadataTree({
})} })}
</> </>
) )
}
async function MetadataOutlet() {
const error = await metadataErrorResolving
if (error) {
throw error
}
return null
}
// @ts-expect-error async server components
return [MetadataTree, MetadataOutlet]
} }
...@@ -39,7 +39,7 @@ import { ...@@ -39,7 +39,7 @@ import {
NEXT_ROUTER_STATE_TREE, NEXT_ROUTER_STATE_TREE,
RSC, RSC,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { MetadataTree } from '../../lib/metadata/metadata' import { createMetadataComponents } from '../../lib/metadata/metadata'
import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper' import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper'
import { StaticGenerationAsyncStorageWrapper } from '../async-storage/static-generation-async-storage-wrapper' import { StaticGenerationAsyncStorageWrapper } from '../async-storage/static-generation-async-storage-wrapper'
import { isClientReference } from '../../lib/client-reference' import { isClientReference } from '../../lib/client-reference'
...@@ -617,6 +617,7 @@ export async function renderToHTMLOrFlight( ...@@ -617,6 +617,7 @@ export async function renderToHTMLOrFlight(
injectedCSS, injectedCSS,
injectedFontPreloadTags, injectedFontPreloadTags,
asNotFound, asNotFound,
metadataOutlet,
}: { }: {
createSegmentPath: CreateSegmentPath createSegmentPath: CreateSegmentPath
loaderTree: LoaderTree loaderTree: LoaderTree
...@@ -626,6 +627,7 @@ export async function renderToHTMLOrFlight( ...@@ -626,6 +627,7 @@ export async function renderToHTMLOrFlight(
injectedCSS: Set<string> injectedCSS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
asNotFound?: boolean asNotFound?: boolean
metadataOutlet?: React.ReactNode
}): Promise<{ }): Promise<{
Component: React.ComponentType Component: React.ComponentType
styles: React.ReactNode styles: React.ReactNode
...@@ -697,7 +699,7 @@ export async function renderToHTMLOrFlight( ...@@ -697,7 +699,7 @@ export async function renderToHTMLOrFlight(
getComponent: notFound[0], getComponent: notFound[0],
injectedCSS: injectedCSSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
}) })
: [] : [rootLayoutIncluded ? undefined : DefaultNotFound]
let dynamic = layoutOrPageMod?.dynamic let dynamic = layoutOrPageMod?.dynamic
...@@ -892,6 +894,7 @@ export async function renderToHTMLOrFlight( ...@@ -892,6 +894,7 @@ export async function renderToHTMLOrFlight(
injectedFontPreloadTags: injectedFontPreloadTags:
injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTagsWithCurrentLayout,
asNotFound, asNotFound,
metadataOutlet,
}) })
const childProp: ChildProp = { const childProp: ChildProp = {
...@@ -1009,6 +1012,7 @@ export async function renderToHTMLOrFlight( ...@@ -1009,6 +1012,7 @@ export async function renderToHTMLOrFlight(
Component: () => { Component: () => {
return ( return (
<> <>
{isPage ? metadataOutlet : null}
{/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */} {/* <Component /> needs to be the first element because we use `findDOMNode` in layout router to locate it. */}
{isPage && isClientComponent && isStaticGeneration ? ( {isPage && isClientComponent && isStaticGeneration ? (
<StaticGenerationSearchParamsBailoutProvider <StaticGenerationSearchParamsBailoutProvider
...@@ -1056,6 +1060,7 @@ export async function renderToHTMLOrFlight( ...@@ -1056,6 +1060,7 @@ export async function renderToHTMLOrFlight(
injectedFontPreloadTags, injectedFontPreloadTags,
rootLayoutIncluded, rootLayoutIncluded,
asNotFound, asNotFound,
metadataOutlet,
}: { }: {
createSegmentPath: CreateSegmentPath createSegmentPath: CreateSegmentPath
loaderTreeToFilter: LoaderTree loaderTreeToFilter: LoaderTree
...@@ -1068,6 +1073,7 @@ export async function renderToHTMLOrFlight( ...@@ -1068,6 +1073,7 @@ export async function renderToHTMLOrFlight(
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
asNotFound?: boolean asNotFound?: boolean
metadataOutlet: React.ReactNode
}): Promise<FlightDataPath[]> => { }): Promise<FlightDataPath[]> => {
const [segment, parallelRoutes, components] = loaderTreeToFilter const [segment, parallelRoutes, components] = loaderTreeToFilter
...@@ -1147,6 +1153,7 @@ export async function renderToHTMLOrFlight( ...@@ -1147,6 +1153,7 @@ export async function renderToHTMLOrFlight(
// This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too. // This is intentionally not "rootLayoutIncludedAtThisLevelOrAbove" as createComponentTree starts at the current level and does a check for "rootLayoutAtThisLevel" too.
rootLayoutIncluded, rootLayoutIncluded,
asNotFound, asNotFound,
metadataOutlet,
} }
) )
...@@ -1224,6 +1231,7 @@ export async function renderToHTMLOrFlight( ...@@ -1224,6 +1231,7 @@ export async function renderToHTMLOrFlight(
injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTagsWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
asNotFound, asNotFound,
metadataOutlet,
}) })
return path return path
...@@ -1250,9 +1258,17 @@ export async function renderToHTMLOrFlight( ...@@ -1250,9 +1258,17 @@ export async function renderToHTMLOrFlight(
// Flight data that is going to be passed to the browser. // Flight data that is going to be passed to the browser.
// Currently a single item array but in the future multiple patches might be combined in a single request. // Currently a single item array but in the future multiple patches might be combined in a single request.
const flightData: FlightData | null = options?.skipFlight
? null let flightData: FlightData | null = null
: ( if (!options?.skipFlight) {
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree: loaderTree,
pathname,
searchParams: providedSearchParams,
getDynamicParamFromSegment,
appUsingSizeAdjust,
})
flightData = (
await walkTreeWithFlightRouterState({ await walkTreeWithFlightRouterState({
createSegmentPath: (child) => child, createSegmentPath: (child) => child,
loaderTreeToFilter: loaderTree, loaderTreeToFilter: loaderTree,
...@@ -1261,25 +1277,17 @@ export async function renderToHTMLOrFlight( ...@@ -1261,25 +1277,17 @@ export async function renderToHTMLOrFlight(
isFirst: true, isFirst: true,
// For flight, render metadata inside leaf page // For flight, render metadata inside leaf page
rscPayloadHead: ( rscPayloadHead: (
<> // Adding requestId as react key to make metadata remount for each render
{/* Adding key={requestId} to make metadata remount for each render */} <MetadataTree key={requestId} />
{/* @ts-expect-error allow to use async server component */}
<MetadataTree
key={requestId}
tree={loaderTree}
pathname={pathname}
searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment}
appUsingSizeAdjust={appUsingSizeAdjust}
/>
</>
), ),
injectedCSS: new Set(), injectedCSS: new Set(),
injectedFontPreloadTags: new Set(), injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false, rootLayoutIncluded: false,
asNotFound: pagePath === '/404' || options?.asNotFound, asNotFound: pagePath === '/404' || options?.asNotFound,
metadataOutlet: <MetadataOutlet />,
}) })
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
}
const buildIdFlightDataPair = [renderOpts.buildId, flightData] const buildIdFlightDataPair = [renderOpts.buildId, flightData]
...@@ -1398,6 +1406,20 @@ export async function renderToHTMLOrFlight( ...@@ -1398,6 +1406,20 @@ export async function renderToHTMLOrFlight(
// Create full component tree from root to leaf. // Create full component tree from root to leaf.
const injectedCSS = new Set<string>() const injectedCSS = new Set<string>()
const injectedFontPreloadTags = new Set<string>() const injectedFontPreloadTags = new Set<string>()
const initialTree = createFlightRouterStateFromLoaderTree(
loaderTreeToRender,
getDynamicParamFromSegment,
query
)
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree: loaderTreeToRender,
errorType: props.asNotFound ? 'not-found' : undefined,
pathname: pathname,
searchParams: providedSearchParams,
getDynamicParamFromSegment: getDynamicParamFromSegment,
appUsingSizeAdjust: appUsingSizeAdjust,
})
const { Component: ComponentTree, styles } = const { Component: ComponentTree, styles } =
await createComponentTree({ await createComponentTree({
...@@ -1409,28 +1431,9 @@ export async function renderToHTMLOrFlight( ...@@ -1409,28 +1431,9 @@ export async function renderToHTMLOrFlight(
injectedFontPreloadTags, injectedFontPreloadTags,
rootLayoutIncluded: false, rootLayoutIncluded: false,
asNotFound: props.asNotFound, asNotFound: props.asNotFound,
metadataOutlet: <MetadataOutlet />,
}) })
const createMetadata = (errorType?: 'not-found') => (
// Adding key={requestId} to make metadata remount for each render
// @ts-expect-error allow to use async server component
<MetadataTree
key={requestId}
tree={loaderTreeToRender}
errorType={errorType}
pathname={pathname}
searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment}
appUsingSizeAdjust={appUsingSizeAdjust}
/>
)
const initialTree = createFlightRouterStateFromLoaderTree(
loaderTreeToRender,
getDynamicParamFromSegment,
query
)
return ( return (
<> <>
{styles} {styles}
...@@ -1439,9 +1442,10 @@ export async function renderToHTMLOrFlight( ...@@ -1439,9 +1442,10 @@ export async function renderToHTMLOrFlight(
assetPrefix={assetPrefix} assetPrefix={assetPrefix}
initialCanonicalUrl={pathname} initialCanonicalUrl={pathname}
initialTree={initialTree} initialTree={initialTree}
initialHead={createMetadata( initialHead={
props.asNotFound ? 'not-found' : undefined // Adding requestId as react key to make metadata remount for each render
)} <MetadataTree key={requestId} />
}
globalErrorComponent={GlobalError} globalErrorComponent={GlobalError}
> >
<ComponentTree /> <ComponentTree />
...@@ -1702,18 +1706,19 @@ export async function renderToHTMLOrFlight( ...@@ -1702,18 +1706,19 @@ export async function renderToHTMLOrFlight(
) )
const ErrorPage = createServerComponentRenderer( const ErrorPage = createServerComponentRenderer(
async () => { async () => {
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree, // still use original tree with not-found boundaries to extract metadata
pathname,
errorType,
searchParams: providedSearchParams,
getDynamicParamFromSegment,
appUsingSizeAdjust,
})
const head = ( const head = (
<> <>
{/* @ts-expect-error allow to use async server component */} {/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree <MetadataTree key={requestId} />
key={requestId}
tree={tree}
pathname={pathname}
errorType={errorType}
searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment}
appUsingSizeAdjust={appUsingSizeAdjust}
/>
{errorMeta} {errorMeta}
</> </>
) )
...@@ -1721,7 +1726,6 @@ export async function renderToHTMLOrFlight( ...@@ -1721,7 +1726,6 @@ export async function renderToHTMLOrFlight(
const notFoundLoaderTree: LoaderTree = is404 const notFoundLoaderTree: LoaderTree = is404
? createNotFoundLoaderTree(tree) ? createNotFoundLoaderTree(tree)
: tree : tree
const initialTree = createFlightRouterStateFromLoaderTree( const initialTree = createFlightRouterStateFromLoaderTree(
notFoundLoaderTree, notFoundLoaderTree,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -1733,6 +1737,7 @@ export async function renderToHTMLOrFlight( ...@@ -1733,6 +1737,7 @@ export async function renderToHTMLOrFlight(
const notFoundElement = ( const notFoundElement = (
<ErrorLayout params={{}}> <ErrorLayout params={{}}>
<MetadataOutlet />
{rootStyles} {rootStyles}
{notFoundStyles} {notFoundStyles}
<GlobalNotFound /> <GlobalNotFound />
......
...@@ -33,7 +33,11 @@ createNextDescribe( ...@@ -33,7 +33,11 @@ createNextDescribe(
} else { } else {
// If expected is undefined, then it should not exist. // If expected is undefined, then it should not exist.
// Otherwise, it should exist in the matched values. // Otherwise, it should exist in the matched values.
expect(values.includes(expected)).toBe(expected !== undefined) if (expected === undefined) {
expect(values).not.toContain(undefined)
} else {
expect(values).toContain(expected)
}
} }
} }
} }
......
...@@ -12,7 +12,7 @@ export default function Root({ children }) { ...@@ -12,7 +12,7 @@ export default function Root({ children }) {
} }
return ( return (
<html> <html className="root-layout-html">
<body> <body>
<NotFoundTrigger /> <NotFoundTrigger />
<button id="trigger-not-found" onClick={() => setClicked(true)}> <button id="trigger-not-found" onClick={() => setClicked(true)}>
......
import { notFound } from 'next/navigation'
export async function generateMetadata() {
notFound()
}
export default function layout({ children }) {
return children
}
export default function page() {
return 'not found metadata page'
}
import { notFound } from 'next/navigation'
export default function page() {
notFound()
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<p>hello world</p>
<div>
<Link id="navigate-not-found" href="/navigate-not-found">
navigate to page calling notfound()
</Link>
</div>
<div>
<Link id="metadata-layout-not-found" href="/metadata-layout-not-found">
navigate to layout with metadata API calling notfound()
</Link>
</div>
</div>
)
}
...@@ -2,7 +2,7 @@ import { createNextDescribe } from 'e2e-utils' ...@@ -2,7 +2,7 @@ import { createNextDescribe } from 'e2e-utils'
import { check, getRedboxDescription, hasRedbox } from 'next-test-utils' import { check, getRedboxDescription, hasRedbox } from 'next-test-utils'
createNextDescribe( createNextDescribe(
'app dir - root layout not found', 'app dir - not found with default 404 page',
{ {
files: __dirname, files: __dirname,
skipDeployment: true, skipDeployment: true,
...@@ -48,5 +48,29 @@ createNextDescribe( ...@@ -48,5 +48,29 @@ createNextDescribe(
) )
} }
}) })
it('should be able to navigate to page calling not-found', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#navigate-not-found').click()
await browser.waitForElementByCss('.next-error-h1')
expect(await browser.elementByCss('h1').text()).toBe('404')
expect(await browser.elementByCss('h2').text()).toBe(
'This page could not be found.'
)
})
it('should be able to navigate to page with calling not-found in metadata', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#metadata-layout-not-found').click()
await browser.waitForElementByCss('.next-error-h1')
expect(await browser.elementByCss('h1').text()).toBe('404')
expect(await browser.elementByCss('h2').text()).toBe(
'This page could not be found.'
)
})
} }
) )
export default function Page() {
return <p>hello world</p>
}
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