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

Fix not found hangs the build with overridden node env (#53106)

### Why

In #52985 the not found solution introduces `NODE_ENV` to determine if it his the not found boundary and should render the not found, as in the next build mode, we have `/_not-found` as a special route which has a empty parallel route, but in next dev mode so far it his the `parallel-default-route`. This could dependend on the `NODE_ENV` passing to next server but not necessarily.

### What

Fixes #53082
Fixes #53083 

### How

When server actions `not-found` hits, now we create a new loader tree based on the previous one, including `layout` and other components but not the children parallel routes

For production case, to make the rendering independent from the `NODE_ENV`, we're using original pathname to check if it's `/_not-found` to determine if it's production build 404 page

To support replace the loader tree of action, did a little refactor that passing down the loader tree from top level to `bodyResult`. Then we can change the loader tree itself before rendering, in short, we tweak it from original tree to one for not-found case, so server actions could render it properly
parent 9da305fe
...@@ -102,6 +102,11 @@ function ErrorHtml({ ...@@ -102,6 +102,11 @@ function ErrorHtml({
) )
} }
function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
// Align the segment with parallel-route-default in next-app-loader
return ['__DEFAULT__', {}, loaderTree[2]]
}
// Find the closest matched component in the loader tree for a given component type // Find the closest matched component in the loader tree for a given component type
function findMatchedComponent( function findMatchedComponent(
loaderTree: LoaderTree, loaderTree: LoaderTree,
...@@ -614,7 +619,7 @@ export async function renderToHTMLOrFlight( ...@@ -614,7 +619,7 @@ export async function renderToHTMLOrFlight(
firstItem?: boolean firstItem?: boolean
injectedCSS: Set<string> injectedCSS: Set<string>
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
asNotFound?: boolean | 'force' asNotFound?: boolean
}): Promise<{ }): Promise<{
Component: React.ComponentType Component: React.ComponentType
styles: React.ReactNode styles: React.ReactNode
...@@ -944,18 +949,15 @@ export async function renderToHTMLOrFlight( ...@@ -944,18 +949,15 @@ export async function renderToHTMLOrFlight(
// If it's a not found route, and we don't have any matched parallel // 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. // routes, we try to render the not found component if it exists.
let isLeaf =
process.env.NODE_ENV === 'production'
? !segment && !rootLayoutIncluded
: !parallelRouteMap.length && segment === '__DEFAULT__' // hit parallel-route-default
let notFoundComponent = {} let notFoundComponent = {}
if ( if (
NotFound && NotFound &&
// For action not-found we force render the NotFound and stop checking the parallel routes. asNotFound &&
(asNotFound === 'force' || // In development, it could hit the parallel-route-default not found, so we only need to check the segment.
// For normal case where we should look up for not-found, keep checking the parallel routes. // Or if there's no parallel routes means it reaches the end.
(asNotFound && isLeaf)) ((segment === '__DEFAULT__' && !parallelRouteMap.length) ||
// For production build the original pathname is /_not-found, always render not-found component.
renderOpts.originalPathname === '/_not-found')
) { ) {
notFoundComponent = { notFoundComponent = {
children: ( children: (
...@@ -1382,69 +1384,70 @@ export async function renderToHTMLOrFlight( ...@@ -1382,69 +1384,70 @@ export async function renderToHTMLOrFlight(
* A new React Component that renders the provided React Component * A new React Component that renders the provided React Component
* using Flight which can then be rendered to HTML. * using Flight which can then be rendered to HTML.
*/ */
const ServerComponentsRenderer = createServerComponentRenderer<{ const createServerComponentsRenderer = (loaderTreeToRender: LoaderTree) =>
asNotFound: boolean | 'force' createServerComponentRenderer<{
}>( asNotFound: boolean
async (props) => { }>(
// Create full component tree from root to leaf. async (props) => {
const injectedCSS = new Set<string>() // Create full component tree from root to leaf.
const injectedFontPreloadTags = new Set<string>() const injectedCSS = new Set<string>()
const injectedFontPreloadTags = new Set<string>()
const { Component: ComponentTree, styles } = await createComponentTree({
createSegmentPath: (child) => child,
loaderTree,
parentParams: {},
firstItem: true,
injectedCSS,
injectedFontPreloadTags,
rootLayoutIncluded: false,
asNotFound: props.asNotFound,
})
const createMetadata = (tree: LoaderTree, errorType?: 'not-found') => ( const { Component: ComponentTree, styles } =
// Adding key={requestId} to make metadata remount for each render await createComponentTree({
// @ts-expect-error allow to use async server component createSegmentPath: (child) => child,
<MetadataTree loaderTree: loaderTreeToRender,
key={requestId} parentParams: {},
tree={tree} firstItem: true,
errorType={errorType} injectedCSS,
pathname={pathname} injectedFontPreloadTags,
searchParams={providedSearchParams} rootLayoutIncluded: false,
getDynamicParamFromSegment={getDynamicParamFromSegment} asNotFound: props.asNotFound,
appUsingSizeAdjust={appUsingSizeAdjust} })
/>
)
const initialTree = createFlightRouterStateFromLoaderTree( const createMetadata = (errorType?: 'not-found') => (
loaderTree, // Adding key={requestId} to make metadata remount for each render
getDynamicParamFromSegment, // @ts-expect-error allow to use async server component
query <MetadataTree
) key={requestId}
tree={loaderTreeToRender}
errorType={errorType}
pathname={pathname}
searchParams={providedSearchParams}
getDynamicParamFromSegment={getDynamicParamFromSegment}
appUsingSizeAdjust={appUsingSizeAdjust}
/>
)
return ( const initialTree = createFlightRouterStateFromLoaderTree(
<> loaderTreeToRender,
{styles} getDynamicParamFromSegment,
<AppRouter query
buildId={renderOpts.buildId} )
assetPrefix={assetPrefix}
initialCanonicalUrl={pathname} return (
initialTree={initialTree} <>
initialHead={createMetadata( {styles}
loaderTree, <AppRouter
props.asNotFound ? 'not-found' : undefined buildId={renderOpts.buildId}
)} assetPrefix={assetPrefix}
globalErrorComponent={GlobalError} initialCanonicalUrl={pathname}
> initialTree={initialTree}
<ComponentTree /> initialHead={createMetadata(
</AppRouter> props.asNotFound ? 'not-found' : undefined
</> )}
) globalErrorComponent={GlobalError}
}, >
ComponentMod, <ComponentTree />
serverComponentsRenderOpts, </AppRouter>
serverComponentsErrorHandler, </>
nonce )
) },
ComponentMod,
serverComponentsRenderOpts,
serverComponentsErrorHandler,
nonce
)
const { HeadManagerContext } = const { HeadManagerContext } =
require('../../shared/lib/head-manager-context') as typeof import('../../shared/lib/head-manager-context') require('../../shared/lib/head-manager-context') as typeof import('../../shared/lib/head-manager-context')
...@@ -1465,15 +1468,16 @@ export async function renderToHTMLOrFlight( ...@@ -1465,15 +1468,16 @@ export async function renderToHTMLOrFlight(
}, },
async ({ async ({
asNotFound, asNotFound,
tree,
}: { }: {
/** /**
* This option is used to indicate that the page should be rendered as * This option is used to indicate that the page should be rendered as
* if it was not found. When it's enabled, instead of rendering the * if it was not found. When it's enabled, instead of rendering the
* page component, it renders the not-found segment. * page component, it renders the not-found segment.
* *
* If it's 'force', we don't traverse the tree and directly render the NotFound.
*/ */
asNotFound: boolean | 'force' asNotFound: boolean
tree: LoaderTree
}) => { }) => {
const polyfills = buildManifest.polyfillFiles const polyfills = buildManifest.polyfillFiles
.filter( .filter(
...@@ -1487,6 +1491,7 @@ export async function renderToHTMLOrFlight( ...@@ -1487,6 +1491,7 @@ export async function renderToHTMLOrFlight(
integrity: subresourceIntegrityManifest?.[polyfill], integrity: subresourceIntegrityManifest?.[polyfill],
})) }))
const ServerComponentsRenderer = createServerComponentsRenderer(tree)
const content = ( const content = (
<HeadManagerContext.Provider <HeadManagerContext.Provider
value={{ value={{
...@@ -1643,12 +1648,12 @@ export async function renderToHTMLOrFlight( ...@@ -1643,12 +1648,12 @@ export async function renderToHTMLOrFlight(
const injectedCSS = new Set<string>() const injectedCSS = new Set<string>()
const injectedFontPreloadTags = new Set<string>() const injectedFontPreloadTags = new Set<string>()
const [RootLayout, rootStyles] = await getRootLayout( const [RootLayout, rootStyles] = await getRootLayout(
loaderTree, tree,
injectedCSS, injectedCSS,
injectedFontPreloadTags injectedFontPreloadTags
) )
const [NotFound, notFoundStyles] = await getNotFound( const [NotFound, notFoundStyles] = await getNotFound(
loaderTree, tree,
injectedCSS, injectedCSS,
pathname pathname
) )
...@@ -1690,7 +1695,7 @@ export async function renderToHTMLOrFlight( ...@@ -1690,7 +1695,7 @@ export async function renderToHTMLOrFlight(
{/* @ts-expect-error allow to use async server component */} {/* @ts-expect-error allow to use async server component */}
<MetadataTree <MetadataTree
key={requestId} key={requestId}
tree={loaderTree} tree={tree}
pathname={pathname} pathname={pathname}
errorType={errorType} errorType={errorType}
searchParams={providedSearchParams} searchParams={providedSearchParams}
...@@ -1702,8 +1707,8 @@ export async function renderToHTMLOrFlight( ...@@ -1702,8 +1707,8 @@ export async function renderToHTMLOrFlight(
) )
const notFoundLoaderTree: LoaderTree = is404 const notFoundLoaderTree: LoaderTree = is404
? ['__DEFAULT__', {}, loaderTree[2]] ? createNotFoundLoaderTree(tree)
: loaderTree : tree
const initialTree = createFlightRouterStateFromLoaderTree( const initialTree = createFlightRouterStateFromLoaderTree(
notFoundLoaderTree, notFoundLoaderTree,
...@@ -1777,7 +1782,7 @@ export async function renderToHTMLOrFlight( ...@@ -1777,7 +1782,7 @@ export async function renderToHTMLOrFlight(
}) })
} catch (finalErr: any) { } catch (finalErr: any) {
if ( if (
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV === 'development' &&
isNotFoundError(finalErr) isNotFoundError(finalErr)
) { ) {
const bailOnNotFound: typeof import('../../client/components/dev-root-not-found-boundary').bailOnNotFound = const bailOnNotFound: typeof import('../../client/components/dev-root-not-found-boundary').bailOnNotFound =
...@@ -1804,7 +1809,13 @@ export async function renderToHTMLOrFlight( ...@@ -1804,7 +1809,13 @@ export async function renderToHTMLOrFlight(
}) })
if (actionRequestResult === 'not-found') { if (actionRequestResult === 'not-found') {
return new RenderResult(await bodyResult({ asNotFound: 'force' })) const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
return new RenderResult(
await bodyResult({
asNotFound: true,
tree: notFoundLoaderTree,
})
)
} else if (actionRequestResult) { } else if (actionRequestResult) {
return actionRequestResult return actionRequestResult
} }
...@@ -1812,6 +1823,7 @@ export async function renderToHTMLOrFlight( ...@@ -1812,6 +1823,7 @@ export async function renderToHTMLOrFlight(
const renderResult = new RenderResult( const renderResult = new RenderResult(
await bodyResult({ await bodyResult({
asNotFound: pagePath === '/404', asNotFound: pagePath === '/404',
tree: loaderTree,
}) })
) )
......
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
createNextDescribe( export function runTest({ next }) {
'not-found-linking', it('should allow navigation on not-found', async () => {
{ const browser = await next.browser('/trigger-404')
files: __dirname, expect(await browser.elementByCss('#not-found-component').text()).toBe(
}, 'Not Found!'
({ next }) => { )
it('should allow navigation on not-found', async () => {
const browser = await next.browser('/trigger-404') expect(
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!'
)
expect(
await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.text()
).toBe('Result Page!')
})
it('should allow navigation on error', async () => {
const browser = await next.browser('/trigger-error')
expect(await browser.elementByCss('#error-component').text()).toBe(
'Error Happened!'
)
expect(
await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.text()
).toBe('Result Page!')
})
it('should allow navigation to other routes on route that was initially not-found', async () => {
// Intentionally non-existent route.
const browser = await next.browser('/testabc')
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!'
)
expect(
await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.text()
).toBe('Result Page!')
})
it('should allow navigation back to route that was initially not-found', async () => {
// Intentionally non-existent route.
const browser = await next.browser('/testabc')
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!'
)
await browser await browser
.elementByCss('#to-result') .elementByCss('#to-result')
.click() .click()
.waitForElementByCss('#result-page') .waitForElementByCss('#result-page')
.back() .text()
.waitForElementByCss('#not-found-component') ).toBe('Result Page!')
}) })
it('should allow navigating to a page calling notfound', async () => { it('should allow navigation on error', async () => {
const browser = await next.browser('/') const browser = await next.browser('/trigger-error')
expect(await browser.elementByCss('#error-component').text()).toBe(
'Error Happened!'
)
expect(
await browser await browser
.elementByCss('#trigger-404-link') .elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.text()
).toBe('Result Page!')
})
it('should allow navigation to other routes on route that was initially not-found', async () => {
// Intentionally non-existent route.
const browser = await next.browser('/testabc')
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!'
)
expect(
await browser
.elementByCss('#to-result')
.click() .click()
.waitForElementByCss('#not-found-component') .waitForElementByCss('#result-page')
.text()
).toBe('Result Page!')
})
expect(await browser.elementByCss('#not-found-component').text()).toBe( it('should allow navigation back to route that was initially not-found', async () => {
'Not Found!' // Intentionally non-existent route.
) const browser = await next.browser('/testabc')
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!'
)
await browser.back().waitForElementByCss('#homepage') await browser
.elementByCss('#to-result')
.click()
.waitForElementByCss('#result-page')
.back()
.waitForElementByCss('#not-found-component')
})
expect(await browser.elementByCss('#homepage').text()).toBe('Home') it('should allow navigating to a page calling notfound', async () => {
}) const browser = await next.browser('/')
it('should allow navigating to a non-existent page', async () => { await browser
const browser = await next.browser('/') .elementByCss('#trigger-404-link')
.click()
.waitForElementByCss('#not-found-component')
await browser expect(await browser.elementByCss('#not-found-component').text()).toBe(
.elementByCss('#non-existent-link') 'Not Found!'
.click() )
.waitForElementByCss('#not-found-component')
await browser.back().waitForElementByCss('#homepage')
expect(await browser.elementByCss('#homepage').text()).toBe('Home')
})
it('should allow navigating to a non-existent page', async () => {
const browser = await next.browser('/')
await browser
.elementByCss('#non-existent-link')
.click()
.waitForElementByCss('#not-found-component')
expect(await browser.elementByCss('#not-found-component').text()).toBe( expect(await browser.elementByCss('#not-found-component').text()).toBe(
'Not Found!' 'Not Found!'
) )
await browser.back().waitForElementByCss('#homepage') await browser.back().waitForElementByCss('#homepage')
expect(await browser.elementByCss('#homepage').text()).toBe('Home') expect(await browser.elementByCss('#homepage').text()).toBe('Home')
}) })
}
createNextDescribe(
'app dir - not found navigation',
{
files: __dirname,
},
({ next }) => {
runTest({ next })
} }
) )
import { createNextDescribe } from 'e2e-utils'
import { runTest } from './error-boundary-and-not-found-linking.test'
createNextDescribe(
'app dir - not found navigation - with overridden node env',
{
files: __dirname,
env: { NODE_ENV: 'test' },
},
({ next }) => {
runTest({ next })
}
)
...@@ -45,7 +45,7 @@ export class NextDevInstance extends NextInstance { ...@@ -45,7 +45,7 @@ export class NextDevInstance extends NextInstance {
env: { env: {
...process.env, ...process.env,
...this.env, ...this.env,
NODE_ENV: '' as any, NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort || '0', PORT: this.forcedPort || '0',
__NEXT_TEST_MODE: 'e2e', __NEXT_TEST_MODE: 'e2e',
__NEXT_TEST_WITH_DEVTOOL: '1', __NEXT_TEST_WITH_DEVTOOL: '1',
......
...@@ -48,7 +48,7 @@ export class NextStartInstance extends NextInstance { ...@@ -48,7 +48,7 @@ export class NextStartInstance extends NextInstance {
env: { env: {
...process.env, ...process.env,
...this.env, ...this.env,
NODE_ENV: '' as any, NODE_ENV: this.env.NODE_ENV || ('' as any),
PORT: this.forcedPort || '0', PORT: this.forcedPort || '0',
__NEXT_TEST_MODE: 'e2e', __NEXT_TEST_MODE: 'e2e',
}, },
......
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