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,49 +41,73 @@ export async function MetadataTree({ ...@@ -36,49 +41,73 @@ 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,
} }
const resolvedMetadata = await resolveMetadata({ let resolve: (value: Error | undefined) => void | undefined
tree, // Only use promise.resolve here to avoid unhandled rejections
parentParams: {}, const metadataErrorResolving = new Promise<Error | undefined>((res) => {
metadataItems: [], resolve = res
searchParams,
getDynamicParamFromSegment,
errorConvention: errorType === 'redirect' ? undefined : errorType,
}) })
let metadata: ResolvedMetadata | undefined = undefined
const defaultMetadata = createDefaultMetadata() async function MetadataTree() {
// Skip for redirect case as for the temporary redirect case we don't need the metadata on client const defaultMetadata = createDefaultMetadata()
if (errorType === 'redirect') { let metadata: ResolvedMetadata | undefined = defaultMetadata
metadata = defaultMetadata try {
} else { const resolvedMetadata = await resolveMetadata({
metadata = await accumulateMetadata(resolvedMetadata, metadataContext) tree,
} parentParams: {},
metadataItems: [],
searchParams,
getDynamicParamFromSegment,
errorConvention: errorType === 'redirect' ? undefined : errorType,
})
// Skip for redirect case as for the temporary redirect case we don't need the metadata on client
if (errorType === 'redirect') {
metadata = defaultMetadata
} else {
metadata = await accumulateMetadata(resolvedMetadata, metadataContext)
}
resolve(undefined)
} catch (error: any) {
resolve(error)
}
const elements = MetaFilter([
BasicMetadata({ metadata }),
AlternatesMetadata({ alternates: metadata.alternates }),
ItunesMeta({ itunes: metadata.itunes }),
FormatDetectionMeta({ formatDetection: metadata.formatDetection }),
VerificationMeta({ verification: metadata.verification }),
AppleWebAppMeta({ appleWebApp: metadata.appleWebApp }),
OpenGraphMetadata({ openGraph: metadata.openGraph }),
TwitterMetadata({ twitter: metadata.twitter }),
AppLinksMeta({ appLinks: metadata.appLinks }),
IconsMetadata({ icons: metadata.icons }),
])
const elements = MetaFilter([ if (appUsingSizeAdjust) elements.push(<meta name="next-size-adjust" />)
BasicMetadata({ metadata }),
AlternatesMetadata({ alternates: metadata.alternates }),
ItunesMeta({ itunes: metadata.itunes }),
FormatDetectionMeta({ formatDetection: metadata.formatDetection }),
VerificationMeta({ verification: metadata.verification }),
AppleWebAppMeta({ appleWebApp: metadata.appleWebApp }),
OpenGraphMetadata({ openGraph: metadata.openGraph }),
TwitterMetadata({ twitter: metadata.twitter }),
AppLinksMeta({ appLinks: metadata.appLinks }),
IconsMetadata({ icons: metadata.icons }),
])
if (appUsingSizeAdjust) elements.push(<meta name="next-size-adjust" />) return (
<>
{elements.map((el, index) => {
return React.cloneElement(el as React.ReactElement, { key: index })
})}
</>
)
}
async function MetadataOutlet() {
const error = await metadataErrorResolving
if (error) {
throw error
}
return null
}
return ( // @ts-expect-error async server components
<> return [MetadataTree, MetadataOutlet]
{elements.map((el, index) => {
return React.cloneElement(el as React.ReactElement, { key: index })
})}
</>
)
} }
...@@ -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