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

Fix dynamic route not-found boundary matching (#53564)

### What & Why

The dynamic not-found boundary didn't work as expected as it was using the `pathname` to match how many levels of the segements should be matched. For dynamic routes this doesn't work, unlike normal page, the unmatched segment can also hit the not found boundary in the same level.

### How

Use `segment` of loader tree nodes to determine if not-found boundary searching is reached to the end instead of using `pathname`. 
> NOTE: For production `/_not-found` case since it's a valid page on production and still has the original tree, so we handle that as a special case to use the not found loader tree (with empty child routes) to render.

Fixes #53344
parent cc4879d1
......@@ -111,15 +111,14 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
function findMatchedComponent(
loaderTree: LoaderTree,
componentType: Exclude<keyof ComponentsType, 'metadata'>,
depth: number,
result?: ModuleReference
): ModuleReference | undefined {
const [, parallelRoutes, components] = loaderTree
const [segment, parallelRoutes, components] = loaderTree
const childKeys = Object.keys(parallelRoutes)
result = components[componentType] || result
// reached the end of the tree
if (depth <= 0 || childKeys.length === 0) {
if (segment === '__DEFAULT__' || segment === '__PAGE__') {
return result
}
......@@ -128,7 +127,6 @@ function findMatchedComponent(
const matchedComponent = findMatchedComponent(
childTree,
componentType,
depth - 1,
result
)
if (matchedComponent) {
......@@ -966,7 +964,7 @@ export async function renderToHTMLOrFlight(
// Or if there's no parallel routes means it reaches the end.
((segment === '__DEFAULT__' && !parallelRouteMap.length) ||
// For production build the original pathname is /_not-found, always render not-found component.
renderOpts.originalPathname === '/_not-found')
(!renderOpts.dev && renderOpts.originalPathname === '/_not-found'))
) {
notFoundComponent = {
children: (
......@@ -1354,17 +1352,8 @@ export async function renderToHTMLOrFlight(
}
: {}
async function getNotFound(
tree: LoaderTree,
injectedCSS: Set<string>,
requestPathname: string
) {
// `depth` represents how many layers we need to search into the tree.
// For instance:
// pathname '/abc' will be 0 depth, means stop at the root level
// pathname '/abc/def' will be 1 depth, means stop at the first level
const depth = requestPathname.split('/').length - 2
const notFound = findMatchedComponent(tree, 'not-found', depth)
async function getNotFound(tree: LoaderTree, injectedCSS: Set<string>) {
const notFound = findMatchedComponent(tree, 'not-found')
const [NotFound, notFoundStyles] = notFound
? await createComponentAndStyles({
filePath: notFound[1],
......@@ -1661,19 +1650,6 @@ export async function renderToHTMLOrFlight(
const is404 = res.statusCode === 404
const injectedCSS = new Set<string>()
const injectedFontPreloadTags = new Set<string>()
const [RootLayout, rootStyles] = await getRootLayout(
tree,
injectedCSS,
injectedFontPreloadTags
)
const [NotFound, notFoundStyles] = await getNotFound(
tree,
injectedCSS,
pathname
)
// Preserve the existing RSC inline chunks from the page rendering.
// For 404 errors: the metadata from layout can be skipped with the error page.
// For other errors (such as redirection): it can still be re-thrown on client.
......@@ -1732,6 +1708,20 @@ export async function renderToHTMLOrFlight(
query
)
const injectedCSS = new Set<string>()
const injectedFontPreloadTags = new Set<string>()
const [RootLayout, rootStyles] = await getRootLayout(
tree,
injectedCSS,
injectedFontPreloadTags
)
const [NotFound, notFoundStyles] = await getNotFound(
!renderOpts.dev && renderOpts.originalPathname === '/_not-found'
? notFoundLoaderTree
: tree,
injectedCSS
)
const GlobalNotFound = NotFound || DefaultNotFound
const ErrorLayout = RootLayout || ErrorHtml
......
export default function notFound() {
return <h2>local found boundary</h2>
return <h2>Local found boundary</h2>
}
export const metadata = {
......
......@@ -574,7 +574,7 @@ createNextDescribe(
let hasRootNotFoundFlight = false
for (const el of $('script').toArray()) {
const text = $(el).text()
if (text.includes('root not found page')) {
if (text.includes('Local found boundary')) {
hasRootNotFoundFlight = true
}
}
......@@ -590,7 +590,7 @@ createNextDescribe(
const browser = await next.browser('/async/not-found')
expect(await browser.elementByCss('h2').text()).toBe(
'root not found page'
'Local found boundary'
)
const matchMultiDom = createMultiDomMatcher(browser)
......
export default function NotFound() {
return <div id="not-found">{`dynamic/[id] not found`}</div>
}
import { notFound } from 'next/navigation'
// avoid static generation to fill the dynamic params
export const dynamic = 'force-dynamic'
export default function Page() {
notFound()
return <>{`dynamic [id]`}</>
}
export default function Test() {
return <div>dynamic</div>
}
......@@ -6,7 +6,7 @@ export default function Layout({ children }) {
<header>
<nav id="layout-nav">Navbar</nav>
</header>
{children}
<main>{children}</main>
<footer>
<p id="layout-footer">Footer</p>
</footer>
......
......@@ -37,6 +37,15 @@ createNextDescribe(
expect(html).toContain("I'm still a valid page")
})
it('should match dynamic route not-found boundary correctly', async () => {
const $dynamic = await next.render$('/dynamic')
const $dynamicId = await next.render$('/dynamic/123')
// `/dynamic` display works
expect($dynamic('main').text()).toBe('dynamic')
// `/dynamic/[id]` calling notFound() will match the same level not-found boundary
expect($dynamicId('#not-found').text()).toBe('dynamic/[id] not found')
})
if (isNextDev) {
it('should not reload the page', async () => {
const browser = await next.browser('/random-content')
......
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