Unverified Commit 594f3d1f authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix root not-found page tree loader structure (#54080)

### What & Why

Previously when rendering the root `/_not-found` in production, we'll always override the parallel routes component children with not-found component, this will break the navigation in build mode from root 404 `/_not-found` path.

### How

The new solution is to change the root `/_not-found` rendering strategy. Previously the loader tree of `/_not-found` look like this

```js
['',
  {
    children: ['not-found', {}, {}]
  },
  { layout: ..., 'not-found': ...}
]
```

it's not a pretty valid tree, which could lead to problems during rendering.

New solution is to change the children to render a page, but the page content is `not-found.js` component. The new tree of root not-found will look like

```js
['',
  {
    children: ['__PAGE__', {}, {
      page: ... // same as root 'not-found'
    }]
  },
  { layout: ..., 'not-found': ...}
]
```

This change could fix the navigation on the root not-found page.

Fixes #52264
parent b676fce0
......@@ -149,6 +149,7 @@ const isDirectory = async (pathname: string) => {
async function createTreeCodeFromPath(
pagePath: string,
{
page,
resolveDir,
resolver,
resolveParallelSegments,
......@@ -156,6 +157,7 @@ async function createTreeCodeFromPath(
pageExtensions,
basePath,
}: {
page: string
resolveDir: DirResolver
resolver: PathResolver
metadataResolver: MetadataResolver
......@@ -175,6 +177,7 @@ async function createTreeCodeFromPath(
const splittedPath = pagePath.split(/[\\/]/)
const appDirPrefix = splittedPath[0]
const pages: string[] = []
const isNotFoundRoute = page === '/_not-found'
let rootLayout: string | undefined
let globalError: string | undefined
......@@ -282,9 +285,8 @@ async function createTreeCodeFromPath(
)
)
const { treeCode: subtreeCode } = await createSubtreePropsFromSegmentPath(
subSegmentPath
)
const { treeCode: pageSubtreeCode } =
await createSubtreePropsFromSegmentPath(subSegmentPath)
const parallelSegmentPath = subSegmentPath.join('/')
......@@ -342,19 +344,40 @@ async function createTreeCodeFromPath(
? 'children'
: parallelSegmentKey
props[normalizeParallelKey(parallelKey)] = `[
const normalizedParallelKey = normalizeParallelKey(parallelKey)
let subtreeCode = pageSubtreeCode
// If it's root not found page, set not-found boundary as children page
if (isNotFoundRoute && normalizedParallelKey === 'children') {
const notFoundPath =
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
'next/dist/client/components/not-found-error'
subtreeCode = `{
children: ['__PAGE__', {}, {
page: [
() => import(/* webpackMode: "eager" */ ${JSON.stringify(
notFoundPath
)}),
${JSON.stringify(notFoundPath)}
]
}]
}`
}
const componentsCode = `{
${definedFilePaths
.map(([file, filePath]) => {
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath
)}), ${JSON.stringify(filePath)}],`
})
.join('\n')}
${createMetadataExportsCode(metadata)}
}`
props[normalizedParallelKey] = `[
'${parallelSegmentKey}',
${subtreeCode},
{
${definedFilePaths
.map(([file, filePath]) => {
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
filePath
)}), ${JSON.stringify(filePath)}],`
})
.join('\n')}
${createMetadataExportsCode(metadata)}
}
${componentsCode}
]`
}
......@@ -585,6 +608,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
}
let treeCodeResult = await createTreeCodeFromPath(pagePath, {
page,
resolveDir,
resolver,
metadataResolver,
......@@ -632,6 +656,7 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
// Clear fs cache, get the new result with the created root layout.
filesInDir.clear()
treeCodeResult = await createTreeCodeFromPath(pagePath, {
page,
resolveDir,
resolver,
metadataResolver,
......
......@@ -950,9 +950,7 @@ export async function renderToHTMLOrFlight(
asNotFound &&
// In development, it could hit the parallel-route-default not found, so we only need to check the segment.
// Or if there's no parallel routes means it reaches the end.
(!parallelRouteMap.length ||
// For production build the original pathname is /_not-found, always render not-found component.
(!renderOpts.dev && renderOpts.originalPathname === '/_not-found'))
!parallelRouteMap.length
) {
notFoundComponent = {
children: (
......@@ -1393,8 +1391,13 @@ export async function renderToHTMLOrFlight(
initialCanonicalUrl={pathname}
initialTree={initialTree}
initialHead={
// Adding requestId as react key to make metadata remount for each render
<MetadataTree key={requestId} />
<>
{res.statusCode > 400 && (
<meta name="robots" content="noindex" />
)}
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={requestId} />
</>
}
globalErrorComponent={GlobalError}
>
......
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
typescript: {
ignoreBuildErrors: true,
},
}
module.exports = nextConfig
import { notFound } from 'next/navigation'
export default function DynamicPage({ params }) {
if (params.slug === '404') {
notFound()
}
return <p id="dynamic">Dynamic page: {params.slug}</p>
}
import React from 'react'
import Link from 'next/link'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<nav>
<div>
<ul>
<li>
<Link id="go-to-index" href="/">
Index
</Link>
</li>
<li>
<Link id="go-to-dynamic" href="/dynamic/foo">
Dynamic page
</Link>
</li>
<li>
<Link id="go-to-404" href="/does-not-exist">
Not found page
</Link>
</li>
<li>
<Link id="go-to-dynamic-404" href="/dynamic/404">
Dynamic not found page
</Link>
</li>
</ul>
</div>
</nav>
{children}
</body>
</html>
)
}
......@@ -95,6 +95,34 @@ export function runTest({ next }) {
expect(await browser.elementByCss('#homepage').text()).toBe('Home')
})
it('should be able to navigate to other page from root not-found page', async () => {
const browser = await next.browser('/')
await browser
.elementByCss('#go-to-404')
.click()
.waitForElementByCss('#not-found-component')
await browser
.elementByCss('#go-to-dynamic')
.click()
.waitForElementByCss('#dynamic')
expect(await browser.elementByCss('#dynamic').text()).toBe(
'Dynamic page: foo'
)
await browser
.elementByCss('#go-to-dynamic-404')
.click()
.waitForElementByCss('#not-found-component')
await browser
.elementByCss('#go-to-index')
.click()
.waitForElementByCss('#homepage')
})
}
createNextDescribe(
......
import { createNextDescribe } from 'e2e-utils'
import { runTest } from './error-boundary-and-not-found-linking.test'
import { runTest } from './index.test'
createNextDescribe(
'app dir - not found navigation - with overridden node env',
......
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