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

Add handling for 404 in new router (#40787)

parent cc1e35d8
...@@ -8,6 +8,7 @@ export const FILE_TYPES = { ...@@ -8,6 +8,7 @@ export const FILE_TYPES = {
template: 'template', template: 'template',
error: 'error', error: 'error',
loading: 'loading', loading: 'loading',
'404': '404',
} as const } as const
// TODO-APP: check if this can be narrowed. // TODO-APP: check if this can be narrowed.
......
...@@ -285,6 +285,47 @@ function LoadingBoundary({ ...@@ -285,6 +285,47 @@ function LoadingBoundary({
return <>{children}</> return <>{children}</>
} }
interface NotFoundBoundaryProps {
notFound?: React.ReactNode
children: React.ReactNode
}
class NotFoundErrorBoundary extends React.Component<
NotFoundBoundaryProps,
{ notFoundTriggered: boolean }
> {
constructor(props: NotFoundBoundaryProps) {
super(props)
this.state = { notFoundTriggered: false }
}
static getDerivedStateFromError(error: any) {
if (error.code === 'NEXT_NOT_FOUND') {
return { notFoundTriggered: true }
}
// Re-throw if error is not for 404
throw error
}
render() {
if (this.state.notFoundTriggered) {
return this.props.notFound
}
return this.props.children
}
}
function NotFoundBoundary({ notFound, children }: NotFoundBoundaryProps) {
return notFound ? (
<NotFoundErrorBoundary notFound={notFound}>
{children}
</NotFoundErrorBoundary>
) : (
<>{children}</>
)
}
type ErrorComponent = React.ComponentType<{ error: Error; reset: () => void }> type ErrorComponent = React.ComponentType<{ error: Error; reset: () => void }>
interface ErrorBoundaryProps { interface ErrorBoundaryProps {
errorComponent: ErrorComponent errorComponent: ErrorComponent
...@@ -355,6 +396,7 @@ export default function OuterLayoutRouter({ ...@@ -355,6 +396,7 @@ export default function OuterLayoutRouter({
error, error,
loading, loading,
template, template,
notFound,
rootLayoutIncluded, rootLayoutIncluded,
}: { }: {
parallelRouterKey: string parallelRouterKey: string
...@@ -363,6 +405,7 @@ export default function OuterLayoutRouter({ ...@@ -363,6 +405,7 @@ export default function OuterLayoutRouter({
error: ErrorComponent error: ErrorComponent
template: React.ReactNode template: React.ReactNode
loading: React.ReactNode | undefined loading: React.ReactNode | undefined
notFound: React.ReactNode | undefined
rootLayoutIncluded: boolean rootLayoutIncluded: boolean
}) { }) {
const { childNodes, tree, url } = useContext(LayoutRouterContext) const { childNodes, tree, url } = useContext(LayoutRouterContext)
...@@ -412,21 +455,23 @@ export default function OuterLayoutRouter({ ...@@ -412,21 +455,23 @@ export default function OuterLayoutRouter({
key={preservedSegment} key={preservedSegment}
value={ value={
<ErrorBoundary errorComponent={error}> <ErrorBoundary errorComponent={error}>
<LoadingBoundary loading={loading}> <NotFoundBoundary notFound={notFound}>
<InnerLayoutRouter <LoadingBoundary loading={loading}>
parallelRouterKey={parallelRouterKey} <InnerLayoutRouter
url={url} parallelRouterKey={parallelRouterKey}
tree={tree} url={url}
childNodes={childNodesForParallelRouter!} tree={tree}
childProp={ childNodes={childNodesForParallelRouter!}
childPropSegment === preservedSegment ? childProp : null childProp={
} childPropSegment === preservedSegment ? childProp : null
segmentPath={segmentPath} }
path={preservedSegment} segmentPath={segmentPath}
isActive={currentChildSegment === preservedSegment} path={preservedSegment}
rootLayoutIncluded={rootLayoutIncluded} isActive={currentChildSegment === preservedSegment}
/> rootLayoutIncluded={rootLayoutIncluded}
</LoadingBoundary> />
</LoadingBoundary>
</NotFoundBoundary>
</ErrorBoundary> </ErrorBoundary>
} }
> >
......
export const NOT_FOUND_ERROR_CODE = 'NEXT_NOT_FOUND'
export function notFound() {
// eslint-disable-next-line no-throw-literal
throw {
code: NOT_FOUND_ERROR_CODE,
}
}
...@@ -727,7 +727,15 @@ export async function renderToHTMLOrFlight( ...@@ -727,7 +727,15 @@ export async function renderToHTMLOrFlight(
loaderTree: [ loaderTree: [
segment, segment,
parallelRoutes, parallelRoutes,
{ layoutOrPagePath, layout, template, error, loading, page }, {
layoutOrPagePath,
layout,
template,
error,
loading,
page,
'404': notFound,
},
], ],
parentParams, parentParams,
firstItem, firstItem,
...@@ -750,6 +758,7 @@ export async function renderToHTMLOrFlight( ...@@ -750,6 +758,7 @@ export async function renderToHTMLOrFlight(
const Template = template const Template = template
? await interopDefault(template()) ? await interopDefault(template())
: React.Fragment : React.Fragment
const NotFound = notFound ? await interopDefault(notFound()) : undefined
const ErrorComponent = error ? await interopDefault(error()) : undefined const ErrorComponent = error ? await interopDefault(error()) : undefined
const Loading = loading ? await interopDefault(loading()) : undefined const Loading = loading ? await interopDefault(loading()) : undefined
const isLayout = typeof layout !== 'undefined' const isLayout = typeof layout !== 'undefined'
...@@ -844,6 +853,7 @@ export async function renderToHTMLOrFlight( ...@@ -844,6 +853,7 @@ export async function renderToHTMLOrFlight(
<RenderFromTemplateContext /> <RenderFromTemplateContext />
</Template> </Template>
} }
notFound={NotFound ? <NotFound /> : undefined}
childProp={childProp} childProp={childProp}
rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove} rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove}
/>, />,
...@@ -882,6 +892,7 @@ export async function renderToHTMLOrFlight( ...@@ -882,6 +892,7 @@ export async function renderToHTMLOrFlight(
<RenderFromTemplateContext /> <RenderFromTemplateContext />
</Template> </Template>
} }
notFound={NotFound ? <NotFound /> : undefined}
childProp={childProp} childProp={childProp}
rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove} rootLayoutIncluded={rootLayoutIncludedAtThisLevelOrAbove}
/>, />,
......
'client'
export default function Page() {
throw new Error('Error during SSR')
}
'client' import ClientComp from './client-component'
import { useHeaders } from 'next/dist/client/components/hooks-server'
export default function Page() { export default function Page() {
throw new Error('Error during SSR') // Opt-in to SSR.
useHeaders()
return <ClientComp />
} }
export default function NotFound() {
return <h1 id="not-found-component">404!</h1>
}
'client'
import { notFound } from 'next/dist/client/components/not-found'
import React from 'react'
export default function Page() {
const [notFoundEnabled, enableNotFound] = React.useState(false)
if (notFoundEnabled) {
notFound()
}
return (
<button onClick={() => React.startTransition(() => enableNotFound(true))}>
Not Found!
</button>
)
}
// TODO-APP: enable when flight error serialization is implemented
import ClientComp from './client-component'
import { useHeaders } from 'next/dist/client/components/hooks-server'
export default function Page() {
// Opt-in to SSR.
useHeaders()
return <ClientComp />
}
'client'
import { notFound } from 'next/dist/client/components/not-found'
export default function ClientComp() {
notFound()
return <></>
}
// TODO-APP: enable when flight error serialization is implemented
import { notFound } from 'next/dist/client/components/not-found'
export default function Page() {
notFound()
return <></>
}
...@@ -1475,6 +1475,34 @@ describe('app dir', () => { ...@@ -1475,6 +1475,34 @@ describe('app dir', () => {
}) })
}) })
describe('404', () => {
it.skip('should trigger 404 in a server component', async () => {
const browser = await webdriver(next.url, '/not-found/servercomponent')
expect(
await browser.waitForElementByCss('#not-found-component').text()
).toBe('404!')
})
it.skip('should trigger 404 in a client component', async () => {
const browser = await webdriver(next.url, '/not-found/clientcomponent')
expect(
await browser.waitForElementByCss('#not-found-component').text()
).toBe('404!')
})
it('should trigger 404 client-side', async () => {
const browser = await webdriver(next.url, '/not-found/client-side')
await browser
.elementByCss('button')
.click()
.waitForElementByCss('#not-found-component')
expect(await browser.elementByCss('#not-found-component').text()).toBe(
'404!'
)
})
})
describe('redirect', () => { describe('redirect', () => {
describe('components', () => { describe('components', () => {
it.skip('should redirect in a server component', async () => { it.skip('should redirect in a server component', async () => {
......
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