Unverified Commit c262e611 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Consistently use /_not-found for not found page in App Router (#62679)

## What?

#62528 caused test/e2e/app-dir/not-found/conflict-route to fail
compilation in Turbopack, this compiler error was previously already
reported by Turbopack but Next.js didn't show it, which #62528 resolved.

This PR changes the handling for the not-found handling to be consistent
between development and build, which ensures that the "special" page no
longer conflicts with app/not-found/page.js.

Closes NEXT-2617


Note: this is a reworked iteration of
https://github.com/vercel/next.js/pull/62585 which wasn't sufficient.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent 9ae437f4
...@@ -1035,54 +1035,38 @@ async fn directory_tree_to_entrypoints_internal_untraced( ...@@ -1035,54 +1035,38 @@ async fn directory_tree_to_entrypoints_internal_untraced(
// Next.js has this logic in "collect-app-paths", where the root not-found page // Next.js has this logic in "collect-app-paths", where the root not-found page
// is considered as its own entry point. // is considered as its own entry point.
let not_found_tree = if components.not_found.is_some() { let not_found_tree = LoaderTree {
LoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: directory_name.clone(), segment: directory_name.clone(),
parallel_routes: indexmap! { parallel_routes: indexmap! {
"children".to_string() => LoaderTree { "children".to_string() => LoaderTree {
page: app_page.clone(), page: app_page.clone(),
segment: "__DEFAULT__".to_string(), segment: "/_not-found".to_string(),
parallel_routes: IndexMap::new(), parallel_routes: indexmap! {
components: Components { "children".to_string() => LoaderTree {
default: Some(get_next_package(app_dir).join("dist/client/components/parallel-route-default.js".to_string())), page: app_page.clone(),
..Default::default() segment: "__PAGE__".to_string(),
}.cell(), parallel_routes: IndexMap::new(),
global_metadata, components: Components {
}.cell(), page: components.not_found.or_else(|| Some(get_next_package(app_dir).join("dist/client/components/not-found-error.js".to_string()))),
}, ..Default::default()
components: components.without_leafs().cell(), }.cell(),
global_metadata, global_metadata
}.cell() }.cell()
} else { },
// Create default not-found page for production if there's no customized components: Components::default().cell(),
// not-found
LoaderTree {
page: app_page.clone(),
segment: directory_name.to_string(),
parallel_routes: indexmap! {
"children".to_string() => LoaderTree {
page: app_page.clone(),
segment: "__PAGE__".to_string(),
parallel_routes: IndexMap::new(),
components: Components {
page: Some(get_next_package(app_dir).join("dist/client/components/not-found-error.js".to_string())),
..Default::default()
}.cell(),
global_metadata, global_metadata,
}.cell(), }.cell(),
}, },
components: components.without_leafs().cell(), components: components.without_leafs().cell(),
global_metadata, global_metadata,
}.cell() }
}; .cell();
{ {
let app_page = app_page.clone_push_str("not-found")?; let app_page = app_page
add_app_page(app_dir, &mut result, app_page, not_found_tree).await?; .clone_push_str("_not-found")?
} .complete(PageType::Page)?;
{
let app_page = app_page.clone_push_str("_not-found")?;
add_app_page(app_dir, &mut result, app_page, not_found_tree).await?; add_app_page(app_dir, &mut result, app_page, not_found_tree).await?;
} }
} }
......
...@@ -25,7 +25,11 @@ import { ...@@ -25,7 +25,11 @@ import {
} from '../lib/constants' } from '../lib/constants'
import { isAPIRoute } from '../lib/is-api-route' import { isAPIRoute } from '../lib/is-api-route'
import { isEdgeRuntime } from '../lib/is-edge-runtime' import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { APP_CLIENT_INTERNALS, RSC_MODULE_TYPES } from '../shared/lib/constants' import {
APP_CLIENT_INTERNALS,
RSC_MODULE_TYPES,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../shared/lib/constants'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
...@@ -243,7 +247,9 @@ export function createPagesMapping({ ...@@ -243,7 +247,9 @@ export function createPagesMapping({
let pageKey = getPageFromPath(pagePath, pageExtensions) let pageKey = getPageFromPath(pagePath, pageExtensions)
if (isAppRoute) { if (isAppRoute) {
pageKey = pageKey.replace(/%5F/g, '_') pageKey = pageKey.replace(/%5F/g, '_')
pageKey = pageKey.replace(/^\/not-found$/g, '/_not-found') if (pageKey === '/not-found') {
pageKey = UNDERSCORE_NOT_FOUND_ROUTE_ENTRY
}
} }
const normalizedPath = normalizePathSep( const normalizedPath = normalizePathSep(
...@@ -277,7 +283,8 @@ export function createPagesMapping({ ...@@ -277,7 +283,8 @@ export function createPagesMapping({
// If there's any app pages existed, add a default not-found page. // If there's any app pages existed, add a default not-found page.
// If there's any custom not-found page existed, it will override the default one. // If there's any custom not-found page existed, it will override the default one.
...(hasAppPages && { ...(hasAppPages && {
'/_not-found': 'next/dist/client/components/not-found-error', [UNDERSCORE_NOT_FOUND_ROUTE_ENTRY]:
'next/dist/client/components/not-found-error',
}), }),
...pages, ...pages,
} }
...@@ -582,6 +589,7 @@ export async function createEntrypoints( ...@@ -582,6 +589,7 @@ export async function createEntrypoints(
: pagesType === PAGE_TYPES.APP : pagesType === PAGE_TYPES.APP
? posix.join('app', bundleFile) ? posix.join('app', bundleFile)
: bundleFile.slice(1) : bundleFile.slice(1)
const absolutePagePath = mappings[page] const absolutePagePath = mappings[page]
// Handle paths that have aliases // Handle paths that have aliases
......
...@@ -72,6 +72,8 @@ import { ...@@ -72,6 +72,8 @@ import {
MIDDLEWARE_REACT_LOADABLE_MANIFEST, MIDDLEWARE_REACT_LOADABLE_MANIFEST,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
FUNCTIONS_CONFIG_MANIFEST, FUNCTIONS_CONFIG_MANIFEST,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils' import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
import type { __ApiPreviewProps } from '../server/api-utils' import type { __ApiPreviewProps } from '../server/api-utils'
...@@ -1034,7 +1036,7 @@ export default async function build( ...@@ -1034,7 +1036,7 @@ export default async function build(
const conflictingPublicFiles: string[] = [] const conflictingPublicFiles: string[] = []
const hasPages404 = mappedPages['/404']?.startsWith(PAGES_DIR_ALIAS) const hasPages404 = mappedPages['/404']?.startsWith(PAGES_DIR_ALIAS)
const hasApp404 = !!mappedAppPages?.['/_not-found'] const hasApp404 = !!mappedAppPages?.[UNDERSCORE_NOT_FOUND_ROUTE_ENTRY]
const hasCustomErrorPage = const hasCustomErrorPage =
mappedPages['/_error'].startsWith(PAGES_DIR_ALIAS) mappedPages['/_error'].startsWith(PAGES_DIR_ALIAS)
...@@ -2436,7 +2438,9 @@ export default async function build( ...@@ -2436,7 +2438,9 @@ export default async function build(
!hasPages500 && !hasNonStaticErrorPage && !customAppGetInitialProps !hasPages500 && !hasNonStaticErrorPage && !customAppGetInitialProps
const combinedPages = [...staticPages, ...ssgPages] const combinedPages = [...staticPages, ...ssgPages]
const isApp404Static = appStaticPaths.has('/_not-found') const isApp404Static = appStaticPaths.has(
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY
)
const hasStaticApp404 = hasApp404 && isApp404Static const hasStaticApp404 = hasApp404 && isApp404Static
// we need to trigger automatic exporting when we have // we need to trigger automatic exporting when we have
...@@ -2679,7 +2683,7 @@ export default async function build( ...@@ -2679,7 +2683,7 @@ export default async function build(
routes.forEach((route) => { routes.forEach((route) => {
if (isDynamicRoute(page) && route === page) return if (isDynamicRoute(page) && route === page) return
if (route === '/_not-found') return if (route === UNDERSCORE_NOT_FOUND_ROUTE) return
const { const {
revalidate = appConfig.revalidate ?? false, revalidate = appConfig.revalidate ?? false,
......
...@@ -52,7 +52,10 @@ import { ...@@ -52,7 +52,10 @@ import {
INSTRUMENTATION_HOOK_FILENAME, INSTRUMENTATION_HOOK_FILENAME,
WEBPACK_LAYERS, WEBPACK_LAYERS,
} from '../lib/constants' } from '../lib/constants'
import { MODERN_BROWSERSLIST_TARGET } from '../shared/lib/constants' import {
MODERN_BROWSERSLIST_TARGET,
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../shared/lib/constants'
import prettyBytes from '../lib/pretty-bytes' import prettyBytes from '../lib/pretty-bytes'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex' import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher' import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
...@@ -688,7 +691,10 @@ export async function printTreeView( ...@@ -688,7 +691,10 @@ export async function printTreeView(
}) })
// If there's no app /_notFound page present, then the 404 is still using the pages/404 // If there's no app /_notFound page present, then the 404 is still using the pages/404
if (!lists.pages.includes('/404') && !lists.app?.includes('/_not-found')) { if (
!lists.pages.includes('/404') &&
!lists.app?.includes(UNDERSCORE_NOT_FOUND_ROUTE)
) {
lists.pages = [...lists.pages, '/404'] lists.pages = [...lists.pages, '/404']
} }
......
import type webpack from 'next/dist/compiled/webpack/webpack' import type webpack from 'next/dist/compiled/webpack/webpack'
import type { ValueOf } from '../../../shared/lib/constants' import {
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
type ValueOf,
} from '../../../shared/lib/constants'
import type { ModuleReference, CollectedMetadata } from './metadata/types' import type { ModuleReference, CollectedMetadata } from './metadata/types'
import path from 'path' import path from 'path'
...@@ -192,7 +196,8 @@ async function createTreeCodeFromPath( ...@@ -192,7 +196,8 @@ async function createTreeCodeFromPath(
globalError: string globalError: string
}> { }> {
const splittedPath = pagePath.split(/[\\/]/, 1) const splittedPath = pagePath.split(/[\\/]/, 1)
const isNotFoundRoute = page === '/_not-found' const isNotFoundRoute = page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY
const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath) const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath)
const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0] const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0]
const hasRootNotFound = await resolver( const hasRootNotFound = await resolver(
...@@ -410,14 +415,16 @@ async function createTreeCodeFromPath( ...@@ -410,14 +415,16 @@ async function createTreeCodeFromPath(
defaultNotFoundPath defaultNotFoundPath
nestedCollectedAsyncImports.push(notFoundPath) nestedCollectedAsyncImports.push(notFoundPath)
subtreeCode = `{ subtreeCode = `{
children: ['${PAGE_SEGMENT_KEY}', {}, { children: [${JSON.stringify(UNDERSCORE_NOT_FOUND_ROUTE)}, {
page: [ children: ['${PAGE_SEGMENT_KEY}', {}, {
() => import(/* webpackMode: "eager" */ ${JSON.stringify( page: [
notFoundPath () => import(/* webpackMode: "eager" */ ${JSON.stringify(
)}), notFoundPath
${JSON.stringify(notFoundPath)} )}),
] ${JSON.stringify(notFoundPath)}
}] ]
}]
}, {}]
}` }`
} }
......
...@@ -22,6 +22,7 @@ import { ...@@ -22,6 +22,7 @@ import {
DEFAULT_RUNTIME_WEBPACK, DEFAULT_RUNTIME_WEBPACK,
EDGE_RUNTIME_WEBPACK, EDGE_RUNTIME_WEBPACK,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { import {
getActions, getActions,
...@@ -333,6 +334,23 @@ export class FlightClientEntryPlugin { ...@@ -333,6 +334,23 @@ export class FlightClientEntryPlugin {
bundlePath, bundlePath,
absolutePagePath: entryRequest, absolutePagePath: entryRequest,
}) })
// The webpack implementation of writing the client reference manifest relies on all entrypoints writing a page.js even when there is no client components in the page.
// It needs the file in order to write the reference manifest for the path in the `.next/server` folder.
// TODO-APP: This could be better handled, however Turbopack does not have the same problem as we resolve client components in a single graph.
if (
name === `app${UNDERSCORE_NOT_FOUND_ROUTE_ENTRY}` &&
bundlePath === 'app/not-found'
) {
clientEntriesToInject.push({
compiler,
compilation,
entryName: name,
clientComponentImports: {},
bundlePath: `app${UNDERSCORE_NOT_FOUND_ROUTE_ENTRY}`,
absolutePagePath: entryRequest,
})
}
} }
// Make sure CSS imports are deduplicated before injecting the client entry // Make sure CSS imports are deduplicated before injecting the client entry
......
...@@ -456,13 +456,6 @@ export class ClientReferenceManifestPlugin { ...@@ -456,13 +456,6 @@ export class ClientReferenceManifestPlugin {
manifestEntryFiles.push(entryName.replace(/\/page(\.[^/]+)?$/, '/page')) manifestEntryFiles.push(entryName.replace(/\/page(\.[^/]+)?$/, '/page'))
} }
// Special case for the root not-found page.
// dev: app/not-found
// prod: app/_not-found
if (/^app\/_?not-found(\.[^.]+)?$/.test(entryName)) {
manifestEntryFiles.push(this.dev ? 'app/not-found' : 'app/_not-found')
}
const groupName = entryNameToGroupName(entryName) const groupName = entryNameToGroupName(entryName)
if (!manifestsPerGroup.has(groupName)) { if (!manifestsPerGroup.has(groupName)) {
manifestsPerGroup.set(groupName, []) manifestsPerGroup.set(groupName, [])
...@@ -503,16 +496,6 @@ export class ClientReferenceManifestPlugin { ...@@ -503,16 +496,6 @@ export class ClientReferenceManifestPlugin {
pagePath.slice('app'.length) pagePath.slice('app'.length)
)}]=${json}` )}]=${json}`
) as unknown as webpack.sources.RawSource ) as unknown as webpack.sources.RawSource
if (pagePath === 'app/not-found') {
// Create a separate special manifest for the root not-found page.
assets['server/app/_not-found_' + CLIENT_REFERENCE_MANIFEST + '.js'] =
new sources.RawSource(
`globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST[${JSON.stringify(
'/_not-found'
)}]=${json}`
) as unknown as webpack.sources.RawSource
}
} }
pluginState.ASYNC_CLIENT_MODULES = [] pluginState.ASYNC_CLIENT_MODULES = []
......
...@@ -7,6 +7,7 @@ import type { NodeFileTraceReasons } from 'next/dist/compiled/@vercel/nft' ...@@ -7,6 +7,7 @@ import type { NodeFileTraceReasons } from 'next/dist/compiled/@vercel/nft'
import { import {
CLIENT_REFERENCE_MANIFEST, CLIENT_REFERENCE_MANIFEST,
TRACE_OUTPUT_VERSION, TRACE_OUTPUT_VERSION,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../../../shared/lib/constants' } from '../../../shared/lib/constants'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack' import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { import {
...@@ -242,8 +243,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance { ...@@ -242,8 +243,7 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
// include the client reference manifest // include the client reference manifest
const clientManifestsForPage = const clientManifestsForPage =
entrypoint.name.endsWith('/page') || entrypoint.name.endsWith('/page') ||
entrypoint.name === 'app/not-found' || entrypoint.name === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY
entrypoint.name === 'app/_not-found'
? nodePath.join( ? nodePath.join(
outputPath, outputPath,
'..', '..',
......
import type { FlightRouterState } from '../../../server/app-render/types' import type { FlightRouterState } from '../../../server/app-render/types'
import { GLOBAL_NOT_FOUND_SEGMENT_KEY } from '../../../shared/lib/segment'
export function isNavigatingToNewRootLayout( export function isNavigatingToNewRootLayout(
currentTree: FlightRouterState, currentTree: FlightRouterState,
...@@ -9,9 +8,6 @@ export function isNavigatingToNewRootLayout( ...@@ -9,9 +8,6 @@ export function isNavigatingToNewRootLayout(
const currentTreeSegment = currentTree[0] const currentTreeSegment = currentTree[0]
const nextTreeSegment = nextTree[0] const nextTreeSegment = nextTree[0]
// We currently special-case the global not found segment key, but we don't want it to be treated as a root layout change
if (currentTreeSegment === GLOBAL_NOT_FOUND_SEGMENT_KEY) return false
// If any segment is different before we find the root layout, the root layout has changed. // If any segment is different before we find the root layout, the root layout has changed.
// E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js // E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js
// First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed. // First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.
......
...@@ -22,10 +22,7 @@ import { handleMutable } from '../handle-mutable' ...@@ -22,10 +22,7 @@ import { handleMutable } from '../handle-mutable'
import { applyFlightData } from '../apply-flight-data' import { applyFlightData } from '../apply-flight-data'
import { prefetchQueue } from './prefetch-reducer' import { prefetchQueue } from './prefetch-reducer'
import { createEmptyCacheNode } from '../../app-router' import { createEmptyCacheNode } from '../../app-router'
import { import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'
DEFAULT_SEGMENT_KEY,
GLOBAL_NOT_FOUND_SEGMENT_KEY,
} from '../../../../shared/lib/segment'
import { import {
listenForDynamicRequest, listenForDynamicRequest,
updateCacheNodeOnNavigation, updateCacheNodeOnNavigation,
...@@ -203,28 +200,6 @@ function navigateReducer_noPPR( ...@@ -203,28 +200,6 @@ function navigateReducer_noPPR(
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
) )
if (
!applied &&
// if we've navigated away from the global not found segment but didn't apply the flight data, we need to refetch
// as otherwise we'd be incorrectly using the global not found cache node for the incoming page
currentTree[0] === GLOBAL_NOT_FOUND_SEGMENT_KEY
) {
applied = addRefetchToLeafSegments(
cache,
currentCache,
flightSegmentPath,
treePatch,
// eslint-disable-next-line no-loop-func
() =>
fetchServerResponse(
url,
currentTree,
state.nextUrl,
state.buildId
)
)
}
const hardNavigate = shouldHardNavigate( const hardNavigate = shouldHardNavigate(
// TODO-APP: remove '' // TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, flightSegmentPathWithLeadingEmpty,
...@@ -450,28 +425,6 @@ function navigateReducer_PPR( ...@@ -450,28 +425,6 @@ function navigateReducer_PPR(
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
) )
if (
!applied &&
// if we've navigated away from the global not found segment but didn't apply the flight data, we need to refetch
// as otherwise we'd be incorrectly using the global not found cache node for the incoming page
currentTree[0] === GLOBAL_NOT_FOUND_SEGMENT_KEY
) {
applied = addRefetchToLeafSegments(
cache,
currentCache,
flightSegmentPath,
treePatch,
// eslint-disable-next-line no-loop-func
() =>
fetchServerResponse(
url,
currentTree,
state.nextUrl,
state.buildId
)
)
}
const hardNavigate = shouldHardNavigate( const hardNavigate = shouldHardNavigate(
// TODO-APP: remove '' // TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, flightSegmentPathWithLeadingEmpty,
......
...@@ -41,6 +41,7 @@ export async function exportAppPage( ...@@ -41,6 +41,7 @@ export async function exportAppPage(
fileWriter: FileWriter fileWriter: FileWriter
): Promise<ExportRouteResult> { ): Promise<ExportRouteResult> {
// If the page is `/_not-found`, then we should update the page to be `/404`. // If the page is `/_not-found`, then we should update the page to be `/404`.
// UNDERSCORE_NOT_FOUND_ROUTE value used here, however we don't want to import it here as it causes constants to be inlined which we don't want here.
if (page === '/_not-found') { if (page === '/_not-found') {
pathname = '/404' pathname = '/404'
} }
......
...@@ -101,7 +101,6 @@ import { ...@@ -101,7 +101,6 @@ import {
usedDynamicAPIs, usedDynamicAPIs,
createPostponedAbortSignal, createPostponedAbortSignal,
} from './dynamic-rendering' } from './dynamic-rendering'
import { GLOBAL_NOT_FOUND_SEGMENT_KEY } from '../../shared/lib/segment'
import { import {
getClientComponentLoaderMetrics, getClientComponentLoaderMetrics,
wrapClientComponentLoader, wrapClientComponentLoader,
...@@ -412,16 +411,6 @@ async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) { ...@@ -412,16 +411,6 @@ async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) {
query query
) )
// If the page we're rendering is being treated as the global not-found page, we want to special-case
// the segment key so it doesn't collide with a page matching the same path.
// This is necessary because when rendering the global not-found, it will always be the root segment.
// If the not-found page prefetched a link to the root page, it would have the same data path
// (e.g., ['', { children: ['__PAGE__', {}] }]). Without this disambiguation, the router would interpret
// these pages as being able to share the same cache nodes, which is not the case as they render different things.
if (asNotFound) {
initialTree[0] = GLOBAL_NOT_FOUND_SEGMENT_KEY
}
const [MetadataTree, MetadataOutlet] = createMetadataComponents({ const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree, tree,
errorType: asNotFound ? 'not-found' : undefined, errorType: asNotFound ? 'not-found' : undefined,
......
...@@ -49,6 +49,8 @@ import { ...@@ -49,6 +49,8 @@ import {
NEXT_BUILTIN_DOCUMENT, NEXT_BUILTIN_DOCUMENT,
PAGES_MANIFEST, PAGES_MANIFEST,
STATIC_STATUS_PAGES, STATIC_STATUS_PAGES,
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { isDynamicRoute } from '../shared/lib/router/utils' import { isDynamicRoute } from '../shared/lib/router/utils'
import { checkIsOnDemandRevalidate } from './api-utils' import { checkIsOnDemandRevalidate } from './api-utils'
...@@ -1726,7 +1728,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1726,7 +1728,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
): Promise<ResponsePayload | null> { ): Promise<ResponsePayload | null> {
const is404Page = const is404Page =
// For edge runtime 404 page, /_not-found needs to be treated as 404 page // For edge runtime 404 page, /_not-found needs to be treated as 404 page
(process.env.NEXT_RUNTIME === 'edge' && pathname === '/_not-found') || (process.env.NEXT_RUNTIME === 'edge' &&
pathname === UNDERSCORE_NOT_FOUND_ROUTE) ||
pathname === '/404' pathname === '/404'
// Strip the internal headers. // Strip the internal headers.
...@@ -3234,7 +3237,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -3234,7 +3237,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (this.enabledDirectories.app) { if (this.enabledDirectories.app) {
// Use the not-found entry in app directory // Use the not-found entry in app directory
result = await this.findPageComponents({ result = await this.findPageComponents({
page: this.renderOpts.dev ? '/not-found' : '/_not-found', page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
query, query,
params: {}, params: {},
isAppPath: true, isAppPath: true,
......
...@@ -34,6 +34,8 @@ import { ...@@ -34,6 +34,8 @@ import {
COMPILER_INDEXES, COMPILER_INDEXES,
COMPILER_NAMES, COMPILER_NAMES,
RSC_MODULE_TYPES, RSC_MODULE_TYPES,
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types' import { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types'
...@@ -427,6 +429,29 @@ export async function findPagePathData( ...@@ -427,6 +429,29 @@ export async function findPagePathData(
// Check appDir first falling back to pagesDir // Check appDir first falling back to pagesDir
if (appDir) { if (appDir) {
if (page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY) {
const notFoundPath = await findPageFile(
appDir,
'not-found',
extensions,
true
)
if (notFoundPath) {
return {
filename: join(appDir, notFoundPath),
bundlePath: `app${UNDERSCORE_NOT_FOUND_ROUTE_ENTRY}`,
page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
}
}
return {
filename: require.resolve(
'next/dist/client/components/not-found-error'
),
bundlePath: `app${UNDERSCORE_NOT_FOUND_ROUTE_ENTRY}`,
page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
}
}
pagePath = await findPageFile(appDir, normalizedPagePath, extensions, true) pagePath = await findPageFile(appDir, normalizedPagePath, extensions, true)
if (pagePath) { if (pagePath) {
const pageUrl = ensureLeadingSlash( const pageUrl = ensureLeadingSlash(
...@@ -467,14 +492,6 @@ export async function findPagePathData( ...@@ -467,14 +492,6 @@ export async function findPagePathData(
} }
} }
if (page === '/not-found' && appDir) {
return {
filename: require.resolve('next/dist/client/components/not-found-error'),
bundlePath: 'app/not-found',
page: '/not-found',
}
}
if (page === '/_error') { if (page === '/_error') {
return { return {
filename: require.resolve('next/dist/pages/_error'), filename: require.resolve('next/dist/pages/_error'),
......
...@@ -32,6 +32,7 @@ import { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-ur ...@@ -32,6 +32,7 @@ import { parseUrl as parseUrlUtil } from '../../shared/lib/router/utils/parse-ur
import { import {
PHASE_PRODUCTION_SERVER, PHASE_PRODUCTION_SERVER,
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { RedirectStatusCode } from '../../client/components/redirect-status-code' import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import { DevBundlerService } from './dev-bundler-service' import { DevBundlerService } from './dev-bundler-service'
...@@ -532,14 +533,14 @@ export async function initialize(opts: { ...@@ -532,14 +533,14 @@ export async function initialize(opts: {
const appNotFound = opts.dev const appNotFound = opts.dev
? developmentBundler?.serverFields.hasAppNotFound ? developmentBundler?.serverFields.hasAppNotFound
: await fsChecker.getItem('/_not-found') : await fsChecker.getItem(UNDERSCORE_NOT_FOUND_ROUTE)
res.statusCode = 404 res.statusCode = 404
if (appNotFound) { if (appNotFound) {
return await invokeRender( return await invokeRender(
parsedUrl, parsedUrl,
opts.dev ? '/not-found' : '/_not-found', UNDERSCORE_NOT_FOUND_ROUTE,
handleIndex, handleIndex,
{ {
'x-invoke-status': '404', 'x-invoke-status': '404',
......
...@@ -19,6 +19,7 @@ import { ...@@ -19,6 +19,7 @@ import {
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
CLIENT_REFERENCE_MANIFEST, CLIENT_REFERENCE_MANIFEST,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { join } from 'path' import { join } from 'path'
import { requirePage } from './require' import { requirePage } from './require'
...@@ -139,8 +140,7 @@ async function loadComponentsImpl<N = any>({ ...@@ -139,8 +140,7 @@ async function loadComponentsImpl<N = any>({
// Make sure to avoid loading the manifest for Route Handlers // Make sure to avoid loading the manifest for Route Handlers
const hasClientManifest = const hasClientManifest =
isAppPath && isAppPath && (page.endsWith('/page') || page === UNDERSCORE_NOT_FOUND_ROUTE)
(page.endsWith('/page') || page === '/not-found' || page === '/_not-found')
// Load the manifest files first // Load the manifest files first
const [ const [
......
...@@ -40,6 +40,8 @@ import { ...@@ -40,6 +40,8 @@ import {
SERVER_DIRECTORY, SERVER_DIRECTORY,
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { findDir } from '../lib/find-pages-dir' import { findDir } from '../lib/find-pages-dir'
import { NodeNextRequest, NodeNextResponse } from './base-http/node' import { NodeNextRequest, NodeNextResponse } from './base-http/node'
...@@ -1306,25 +1308,23 @@ export default class NextNodeServer extends BaseServer { ...@@ -1306,25 +1308,23 @@ export default class NextNodeServer extends BaseServer {
const is404 = res.statusCode === 404 const is404 = res.statusCode === 404
if (is404 && this.enabledDirectories.app) { if (is404 && this.enabledDirectories.app) {
const notFoundPathname = this.renderOpts.dev
? '/not-found'
: '/_not-found'
if (this.renderOpts.dev) { if (this.renderOpts.dev) {
await this.ensurePage({ await this.ensurePage({
page: notFoundPathname, page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
clientOnly: false, clientOnly: false,
url: req.url, url: req.url,
}).catch(() => {}) }).catch(() => {})
} }
if (this.getEdgeFunctionsPages().includes(notFoundPathname)) { if (
this.getEdgeFunctionsPages().includes(UNDERSCORE_NOT_FOUND_ROUTE_ENTRY)
) {
await this.runEdgeFunction({ await this.runEdgeFunction({
req: req as BaseNextRequest, req: req as BaseNextRequest,
res: res as BaseNextResponse, res: res as BaseNextResponse,
query: query || {}, query: query || {},
params: {}, params: {},
page: notFoundPathname, page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
appPaths: null, appPaths: null,
}) })
return null return null
......
...@@ -32,6 +32,7 @@ import { IncrementalCache } from './lib/incremental-cache' ...@@ -32,6 +32,7 @@ import { IncrementalCache } from './lib/incremental-cache'
import type { PAGE_TYPES } from '../lib/page-types' import type { PAGE_TYPES } from '../lib/page-types'
import type { Rewrite } from '../lib/load-custom-routes' import type { Rewrite } from '../lib/load-custom-routes'
import { buildCustomRoute } from '../lib/build-custom-route' import { buildCustomRoute } from '../lib/build-custom-route'
import { UNDERSCORE_NOT_FOUND_ROUTE } from '../api/constants'
interface WebServerOptions extends Options { interface WebServerOptions extends Options {
webServerConfig: { webServerConfig: {
...@@ -242,7 +243,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -242,7 +243,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
// For edge runtime if the pathname hit as /_not-found entrypoint, // For edge runtime if the pathname hit as /_not-found entrypoint,
// override the pathname to /404 for rendering // override the pathname to /404 for rendering
if (pathname === (renderOpts.dev ? '/not-found' : '/_not-found')) { if (pathname === UNDERSCORE_NOT_FOUND_ROUTE) {
pathname = '/404' pathname = '/404'
} }
return renderToHTML( return renderToHTML(
......
...@@ -33,6 +33,8 @@ export const COMPILER_INDEXES: { ...@@ -33,6 +33,8 @@ export const COMPILER_INDEXES: {
[COMPILER_NAMES.edgeServer]: 2, [COMPILER_NAMES.edgeServer]: 2,
} as const } as const
export const UNDERSCORE_NOT_FOUND_ROUTE = '/_not-found'
export const UNDERSCORE_NOT_FOUND_ROUTE_ENTRY = `${UNDERSCORE_NOT_FOUND_ROUTE}/page`
export const PHASE_EXPORT = 'phase-export' export const PHASE_EXPORT = 'phase-export'
export const PHASE_PRODUCTION_BUILD = 'phase-production-build' export const PHASE_PRODUCTION_BUILD = 'phase-production-build'
export const PHASE_PRODUCTION_SERVER = 'phase-production-server' export const PHASE_PRODUCTION_SERVER = 'phase-production-server'
......
...@@ -5,4 +5,3 @@ export function isGroupSegment(segment: string) { ...@@ -5,4 +5,3 @@ export function isGroupSegment(segment: string) {
export const PAGE_SEGMENT_KEY = '__PAGE__' export const PAGE_SEGMENT_KEY = '__PAGE__'
export const DEFAULT_SEGMENT_KEY = '__DEFAULT__' export const DEFAULT_SEGMENT_KEY = '__DEFAULT__'
export const GLOBAL_NOT_FOUND_SEGMENT_KEY = '__NOT_FOUND__'
...@@ -228,8 +228,8 @@ describe('next.rs api', () => { ...@@ -228,8 +228,8 @@ describe('next.rs api', () => {
}) })
it('should detect the correct routes', async () => { it('should detect the correct routes', async () => {
const entrypointsSubscribtion = project.entrypointsSubscribe() const entrypointsSubscription = project.entrypointsSubscribe()
const entrypoints = await entrypointsSubscribtion.next() const entrypoints = await entrypointsSubscription.next()
expect(entrypoints.done).toBe(false) expect(entrypoints.done).toBe(false)
expect(Array.from(entrypoints.value.routes.keys()).sort()).toEqual([ expect(Array.from(entrypoints.value.routes.keys()).sort()).toEqual([
'/', '/',
...@@ -239,7 +239,6 @@ describe('next.rs api', () => { ...@@ -239,7 +239,6 @@ describe('next.rs api', () => {
'/app', '/app',
'/app-edge', '/app-edge',
'/app-nodejs', '/app-nodejs',
'/not-found',
'/page-edge', '/page-edge',
'/page-nodejs', '/page-nodejs',
'/route-edge', '/route-edge',
...@@ -249,7 +248,7 @@ describe('next.rs api', () => { ...@@ -249,7 +248,7 @@ describe('next.rs api', () => {
expect(normalizeDiagnostics(entrypoints.value.diagnostics)).toMatchSnapshot( expect(normalizeDiagnostics(entrypoints.value.diagnostics)).toMatchSnapshot(
'diagnostics' 'diagnostics'
) )
entrypointsSubscribtion.return() entrypointsSubscription.return()
}) })
const routes = [ const routes = [
......
...@@ -504,9 +504,9 @@ createNextDescribe( ...@@ -504,9 +504,9 @@ createNextDescribe(
"(new)/custom/page.js", "(new)/custom/page.js",
"(new)/custom/page_client-reference-manifest.js", "(new)/custom/page_client-reference-manifest.js",
"_not-found.html", "_not-found.html",
"_not-found.js",
"_not-found.rsc", "_not-found.rsc",
"_not-found_client-reference-manifest.js", "_not-found/page.js",
"_not-found/page_client-reference-manifest.js",
"api/draft-mode/route.js", "api/draft-mode/route.js",
"api/large-data/route.js", "api/large-data/route.js",
"api/revalidate-path-edge/route.js", "api/revalidate-path-edge/route.js",
......
...@@ -31,12 +31,6 @@ createNextDescribe( ...@@ -31,12 +31,6 @@ createNextDescribe(
expect(await browser.elementByCss('html').getAttribute('class')).toBe( expect(await browser.elementByCss('html').getAttribute('class')).toBe(
'root-layout-html' 'root-layout-html'
) )
if (isNextDev) {
const cliOutput = next.cliOutput
expect(cliOutput).toContain('/not-found')
expect(cliOutput).not.toContain('/_error')
}
}) })
it('should error on server notFound from root layout on server-side', async () => { it('should error on server notFound from root layout on server-side', async () => {
......
...@@ -28,11 +28,11 @@ createNextDescribe( ...@@ -28,11 +28,11 @@ createNextDescribe(
if (isNextStart) { if (isNextStart) {
it('should include not found client reference manifest in the file trace', async () => { it('should include not found client reference manifest in the file trace', async () => {
const fileTrace = JSON.parse( const fileTrace = JSON.parse(
await next.readFile('.next/server/app/_not-found.js.nft.json') await next.readFile('.next/server/app/_not-found/page.js.nft.json')
) )
const isTraced = fileTrace.files.some((filePath) => const isTraced = fileTrace.files.some((filePath) =>
filePath.includes('_not-found_client-reference-manifest.js') filePath.includes('page_client-reference-manifest.js')
) )
expect(isTraced).toBe(true) expect(isTraced).toBe(true)
......
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