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

Improve create not found tree and remove asNotFound (#68910)

parent 0a3fa759
...@@ -898,7 +898,6 @@ export async function handleAction({ ...@@ -898,7 +898,6 @@ export async function handleAction({
result: await generateFlight(req, ctx, { result: await generateFlight(req, ctx, {
skipFlight: false, skipFlight: false,
actionResult: promise, actionResult: promise,
asNotFound: true,
}), }),
} }
} }
......
...@@ -133,6 +133,7 @@ import { createInitialRouterState } from '../../client/components/router-reducer ...@@ -133,6 +133,7 @@ import { createInitialRouterState } from '../../client/components/router-reducer
import { createMutableActionQueue } from '../../shared/lib/router/action-queue' import { createMutableActionQueue } from '../../shared/lib/router/action-queue'
import { prerenderAsyncStorage } from './prerender-async-storage.external' import { prerenderAsyncStorage } from './prerender-async-storage.external'
import { getRevalidateReason } from '../instrumentation/utils' import { getRevalidateReason } from '../instrumentation/utils'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -228,7 +229,20 @@ function parseRequestHeaders( ...@@ -228,7 +229,20 @@ function parseRequestHeaders(
function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
// Align the segment with parallel-route-default in next-app-loader // Align the segment with parallel-route-default in next-app-loader
return ['', {}, loaderTree[2]] const components = loaderTree[2]
return [
'',
{
children: [
PAGE_SEGMENT_KEY,
{},
{
page: components['not-found'],
},
],
},
components,
]
} }
export type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath export type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath
...@@ -334,7 +348,6 @@ async function generateDynamicRSCPayload( ...@@ -334,7 +348,6 @@ async function generateDynamicRSCPayload(
options?: { options?: {
actionResult: ActionResult actionResult: ActionResult
skipFlight: boolean skipFlight: boolean
asNotFound?: boolean
} }
): Promise<RSCPayload> { ): Promise<RSCPayload> {
// Flight data that is going to be passed to the browser. // Flight data that is going to be passed to the browser.
...@@ -382,7 +395,6 @@ async function generateDynamicRSCPayload( ...@@ -382,7 +395,6 @@ async function generateDynamicRSCPayload(
injectedJS: new Set(), injectedJS: new Set(),
injectedFontPreloadTags: new Set(), injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false, rootLayoutIncluded: false,
asNotFound: ctx.isNotFoundPath || options?.asNotFound,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
}) })
...@@ -434,7 +446,6 @@ async function generateDynamicFlightRenderResult( ...@@ -434,7 +446,6 @@ async function generateDynamicFlightRenderResult(
options?: { options?: {
actionResult: ActionResult actionResult: ActionResult
skipFlight: boolean skipFlight: boolean
asNotFound?: boolean
componentTree?: CacheNodeSeedData componentTree?: CacheNodeSeedData
preloadCallbacks?: PreloadCallbacks preloadCallbacks?: PreloadCallbacks
} }
...@@ -475,7 +486,7 @@ async function generateDynamicFlightRenderResult( ...@@ -475,7 +486,7 @@ async function generateDynamicFlightRenderResult(
async function getRSCPayload( async function getRSCPayload(
tree: LoaderTree, tree: LoaderTree,
ctx: AppRenderContext, ctx: AppRenderContext,
asNotFound: boolean is404: boolean
) { ) {
const injectedCSS = new Set<string>() const injectedCSS = new Set<string>()
const injectedJS = new Set<string>() const injectedJS = new Set<string>()
...@@ -502,7 +513,7 @@ async function getRSCPayload( ...@@ -502,7 +513,7 @@ async function getRSCPayload(
const [MetadataTree, getMetadataReady] = createMetadataComponents({ const [MetadataTree, getMetadataReady] = createMetadataComponents({
tree, tree,
errorType: asNotFound ? 'not-found' : undefined, errorType: is404 ? 'not-found' : undefined,
query, query,
metadataContext: createMetadataContext(url.pathname, ctx.renderOpts), metadataContext: createMetadataContext(url.pathname, ctx.renderOpts),
getDynamicParamFromSegment: getDynamicParamFromSegment, getDynamicParamFromSegment: getDynamicParamFromSegment,
...@@ -522,7 +533,6 @@ async function getRSCPayload( ...@@ -522,7 +533,6 @@ async function getRSCPayload(
injectedJS, injectedJS,
injectedFontPreloadTags, injectedFontPreloadTags,
rootLayoutIncluded: false, rootLayoutIncluded: false,
asNotFound: asNotFound,
getMetadataReady, getMetadataReady,
missingSlots, missingSlots,
preloadCallbacks, preloadCallbacks,
...@@ -756,6 +766,9 @@ async function renderToHTMLOrFlightImpl( ...@@ -756,6 +766,9 @@ async function renderToHTMLOrFlightImpl(
requestEndedState: { ended?: boolean } requestEndedState: { ended?: boolean }
) { ) {
const isNotFoundPath = pagePath === '/404' const isNotFoundPath = pagePath === '/404'
if (isNotFoundPath) {
res.statusCode = 404
}
// A unique request timestamp used by development to ensure that it's // A unique request timestamp used by development to ensure that it's
// consistent and won't change during this request. This is important to // consistent and won't change during this request. This is important to
...@@ -948,14 +961,12 @@ async function renderToHTMLOrFlightImpl( ...@@ -948,14 +961,12 @@ async function renderToHTMLOrFlightImpl(
prerenderToStream prerenderToStream
) )
const asNotFound = isNotFoundPath
let response = await prerenderToStreamWithTracing( let response = await prerenderToStreamWithTracing(
req, req,
res, res,
ctx, ctx,
metadata, metadata,
staticGenerationStore, staticGenerationStore,
asNotFound,
loaderTree loaderTree
) )
...@@ -1060,12 +1071,11 @@ async function renderToHTMLOrFlightImpl( ...@@ -1060,12 +1071,11 @@ async function renderToHTMLOrFlightImpl(
if (actionRequestResult) { if (actionRequestResult) {
if (actionRequestResult.type === 'not-found') { if (actionRequestResult.type === 'not-found') {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree) const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
const asNotFound = true res.statusCode = 404
const stream = await renderToStreamWithTracing( const stream = await renderToStreamWithTracing(
req, req,
res, res,
ctx, ctx,
asNotFound,
notFoundLoaderTree, notFoundLoaderTree,
formState formState
) )
...@@ -1086,12 +1096,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -1086,12 +1096,10 @@ async function renderToHTMLOrFlightImpl(
metadata, metadata,
} }
const asNotFound = isNotFoundPath
const stream = await renderToStreamWithTracing( const stream = await renderToStreamWithTracing(
req, req,
res, res,
ctx, ctx,
asNotFound,
loaderTree, loaderTree,
formState formState
) )
...@@ -1188,8 +1196,6 @@ async function renderToStream( ...@@ -1188,8 +1196,6 @@ async function renderToStream(
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
ctx: AppRenderContext, ctx: AppRenderContext,
asNotFound: boolean,
tree: LoaderTree, tree: LoaderTree,
formState: any formState: any
): Promise<ReadableStream<Uint8Array>> { ): Promise<ReadableStream<Uint8Array>> {
...@@ -1276,7 +1282,7 @@ async function renderToStream( ...@@ -1276,7 +1282,7 @@ async function renderToStream(
try { try {
// This is a dynamic render. We don't do dynamic tracking because we're not prerendering // This is a dynamic render. We don't do dynamic tracking because we're not prerendering
const RSCPayload = await getRSCPayload(tree, ctx, asNotFound) const RSCPayload = await getRSCPayload(tree, ctx, res.statusCode === 404)
const reactServerStream = ComponentMod.renderToReadableStream( const reactServerStream = ComponentMod.renderToReadableStream(
RSCPayload, RSCPayload,
clientReferenceManifest.clientModules, clientReferenceManifest.clientModules,
...@@ -1597,8 +1603,6 @@ async function prerenderToStream( ...@@ -1597,8 +1603,6 @@ async function prerenderToStream(
ctx: AppRenderContext, ctx: AppRenderContext,
metadata: AppPageRenderResultMetadata, metadata: AppPageRenderResultMetadata,
staticGenerationStore: StaticGenerationStore, staticGenerationStore: StaticGenerationStore,
asNotFound: boolean,
tree: LoaderTree tree: LoaderTree
): Promise<PrenderToStringResult> { ): Promise<PrenderToStringResult> {
// When prerendering formState is always null. We still include it // When prerendering formState is always null. We still include it
...@@ -1703,7 +1707,7 @@ async function prerenderToStream( ...@@ -1703,7 +1707,7 @@ async function prerenderToStream(
const reactServerPrerenderStore = { const reactServerPrerenderStore = {
dynamicTracking, dynamicTracking,
} }
const RSCPayload = await getRSCPayload(tree, ctx, asNotFound) const RSCPayload = await getRSCPayload(tree, ctx, res.statusCode === 404)
const reactServerStream: ReadableStream<Uint8Array> = const reactServerStream: ReadableStream<Uint8Array> =
prerenderAsyncStorage.run( prerenderAsyncStorage.run(
reactServerPrerenderStore, reactServerPrerenderStore,
...@@ -1867,7 +1871,7 @@ async function prerenderToStream( ...@@ -1867,7 +1871,7 @@ async function prerenderToStream(
} else { } else {
// This is a regular static generation. We don't do dynamic tracking because we rely on // This is a regular static generation. We don't do dynamic tracking because we rely on
// the old-school dynamic error handling to bail out of static generation // the old-school dynamic error handling to bail out of static generation
const RSCPayload = await getRSCPayload(tree, ctx, asNotFound) const RSCPayload = await getRSCPayload(tree, ctx, res.statusCode === 404)
const reactServerStream = ComponentMod.renderToReadableStream( const reactServerStream = ComponentMod.renderToReadableStream(
RSCPayload, RSCPayload,
clientReferenceManifest.clientModules, clientReferenceManifest.clientModules,
......
...@@ -33,7 +33,6 @@ export function createComponentTree(props: { ...@@ -33,7 +33,6 @@ export function createComponentTree(props: {
injectedCSS: Set<string> injectedCSS: Set<string>
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
asNotFound?: boolean
getMetadataReady: () => Promise<void> getMetadataReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
...@@ -65,7 +64,6 @@ async function createComponentTreeInternal({ ...@@ -65,7 +64,6 @@ async function createComponentTreeInternal({
injectedCSS, injectedCSS,
injectedJS, injectedJS,
injectedFontPreloadTags, injectedFontPreloadTags,
asNotFound,
getMetadataReady, getMetadataReady,
ctx, ctx,
missingSlots, missingSlots,
...@@ -79,7 +77,6 @@ async function createComponentTreeInternal({ ...@@ -79,7 +77,6 @@ async function createComponentTreeInternal({
injectedCSS: Set<string> injectedCSS: Set<string>
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
asNotFound?: boolean
getMetadataReady: () => Promise<void> getMetadataReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
missingSlots?: Set<string> missingSlots?: Set<string>
...@@ -437,7 +434,6 @@ async function createComponentTreeInternal({ ...@@ -437,7 +434,6 @@ async function createComponentTreeInternal({
injectedCSS: injectedCSSWithCurrentLayout, injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout, injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
asNotFound,
// getMetadataReady is used to conditionally throw. In the case of parallel routes we will have more than one page // getMetadataReady is used to conditionally throw. In the case of parallel routes we will have more than one page
// but we only want to throw on the first one. // but we only want to throw on the first one.
getMetadataReady: isChildrenRouteKey getMetadataReady: isChildrenRouteKey
...@@ -545,27 +541,6 @@ async function createComponentTreeInternal({ ...@@ -545,27 +541,6 @@ async function createComponentTreeInternal({
// We avoid cloning this object because it gets consumed here exclusively. // We avoid cloning this object because it gets consumed here exclusively.
const props: { [prop: string]: any } = parallelRouteProps const props: { [prop: string]: any } = parallelRouteProps
// If it's a not found route, and we don't have any matched parallel
// routes, we try to render the not found component if it exists.
if (
NotFound &&
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
) {
props.children = (
<>
<meta name="robots" content="noindex" />
{process.env.NODE_ENV === 'development' && (
<meta name="next-error" content="not-found" />
)}
{notFoundStyles}
<NotFound />
</>
)
}
// Assign params to props // Assign params to props
if ( if (
process.env.NODE_ENV === 'development' && process.env.NODE_ENV === 'development' &&
......
...@@ -37,7 +37,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -37,7 +37,6 @@ export async function walkTreeWithFlightRouterState({
injectedJS, injectedJS,
injectedFontPreloadTags, injectedFontPreloadTags,
rootLayoutIncluded, rootLayoutIncluded,
asNotFound,
getMetadataReady, getMetadataReady,
ctx, ctx,
preloadCallbacks, preloadCallbacks,
...@@ -53,7 +52,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -53,7 +52,6 @@ export async function walkTreeWithFlightRouterState({
injectedJS: Set<string> injectedJS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
asNotFound?: boolean
getMetadataReady: () => Promise<void> getMetadataReady: () => Promise<void>
ctx: AppRenderContext ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
...@@ -153,7 +151,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -153,7 +151,6 @@ export async function walkTreeWithFlightRouterState({
injectedFontPreloadTags, injectedFontPreloadTags,
// 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,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
} }
...@@ -214,7 +211,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -214,7 +211,6 @@ export async function walkTreeWithFlightRouterState({
injectedJS: injectedJSWithCurrentLayout, injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
asNotFound,
getMetadataReady, getMetadataReady,
preloadCallbacks, preloadCallbacks,
}) })
......
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