Unverified Commit 1fefb4a8 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Reland "Refine the not-found rendering process for app router" (#52985)

Reland #52790
Reverts vercel/next.js#52977

was failed due to failed job
[vercel/next.js/actions/runs/5616458194/job/15220295829](https://github.com/vercel/next.js/actions/runs/5616458194/job/15220295829)

Should be fine to resolve with
https://github.com/vercel/next.js/pull/52979 now

Fixes #52718
Fixes #52739

---------
Co-authored-by: 's avatarAlex Kirszenberg <alex.kirszenberg@vercel.com>
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent 732219e9
...@@ -5,22 +5,12 @@ import { useRouter, usePathname } from 'next/dist/client/components/navigation' ...@@ -5,22 +5,12 @@ import { useRouter, usePathname } from 'next/dist/client/components/navigation'
import { useEffect } from 'react' import { useEffect } from 'react'
import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client' import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import { ReactDevOverlay } from './client' import { ReactDevOverlay } from './client'
import { NotFoundBoundary } from 'next/dist/client/components/not-found-boundary'
type HotReloadProps = React.PropsWithChildren<{ type HotReloadProps = React.PropsWithChildren<{
assetPrefix?: string assetPrefix?: string
notFound?: React.ReactNode
notFoundStyles?: React.ReactNode
asNotFound?: boolean
}> }>
export default function HotReload({ export default function HotReload({ children }: HotReloadProps) {
assetPrefix,
children,
notFound,
notFoundStyles,
asNotFound,
}: HotReloadProps) {
const router = useRouter() const router = useRouter()
const path = usePathname()!.slice(1) const path = usePathname()!.slice(1)
...@@ -41,14 +31,5 @@ export default function HotReload({ ...@@ -41,14 +31,5 @@ export default function HotReload({
return unsubscribe return unsubscribe
}, [router, path]) }, [router, path])
return ( return <ReactDevOverlay globalOverlay={true}>{children}</ReactDevOverlay>
<NotFoundBoundary
key={asNotFound + ''}
notFound={notFound}
notFoundStyles={notFoundStyles}
asNotFound={asNotFound}
>
<ReactDevOverlay globalOverlay={true}>{children}</ReactDevOverlay>
</NotFoundBoundary>
)
} }
...@@ -7,7 +7,6 @@ import { ErrorBoundary } from './ErrorBoundary' ...@@ -7,7 +7,6 @@ import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base' import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles' import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from './styles/CssReset' import { CssReset } from './styles/CssReset'
import { notFound } from 'next/dist/client/components/not-found'
type RefreshState = type RefreshState =
| { | {
...@@ -210,10 +209,6 @@ export default function ReactDevOverlay({ ...@@ -210,10 +209,6 @@ export default function ReactDevOverlay({
const isMounted = hasBuildError || hasRuntimeErrors const isMounted = hasBuildError || hasRuntimeErrors
if (state.notFound) {
notFound()
}
return ( return (
<React.Fragment> <React.Fragment>
<ErrorBoundary <ErrorBoundary
......
...@@ -601,7 +601,7 @@ pub async fn create_app_source( ...@@ -601,7 +601,7 @@ pub async fn create_app_source(
))) )))
.collect(); .collect();
if let Some(&Entrypoint::AppPage { loader_tree }) = entrypoints.get("/") { if let Some(&Entrypoint::AppPage { loader_tree }) = entrypoints.get("/_not-found") {
if loader_tree.await?.components.await?.not_found.is_some() { if loader_tree.await?.components.await?.not_found.is_some() {
// Only add a source for the app 404 page if a top-level not-found page is // Only add a source for the app 404 page if a top-level not-found page is
// defined. Otherwise, the 404 page is handled by the pages logic. // defined. Otherwise, the 404 page is handled by the pages logic.
......
...@@ -14,7 +14,7 @@ use turbopack_binding::{ ...@@ -14,7 +14,7 @@ use turbopack_binding::{
turbopack::core::issue::{Issue, IssueExt, IssueSeverity}, turbopack::core::issue::{Issue, IssueExt, IssueSeverity},
}; };
use crate::next_config::NextConfig; use crate::{next_config::NextConfig, next_import_map::get_next_package};
/// A final route in the app directory. /// A final route in the app directory.
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -675,9 +675,16 @@ async fn directory_tree_to_entrypoints_internal( ...@@ -675,9 +675,16 @@ async fn directory_tree_to_entrypoints_internal(
LoaderTree { LoaderTree {
segment: directory_name.to_string(), segment: directory_name.to_string(),
parallel_routes: indexmap! { parallel_routes: indexmap! {
// TODO(alexkirsz) Next.js has a __DEFAULT__ entry for "children".to_string() => LoaderTree {
// next/dist/client/components/parallel-route-default segment: "__DEFAULT__".to_string(),
// here. parallel_routes: IndexMap::new(),
components: Components {
default: Some(get_next_package(app_dir).join("dist/client/components/parallel-route-default.js".to_string())),
..Default::default()
}
.cell(),
}
.cell(),
}, },
components: components.without_leafs().cell(), components: components.without_leafs().cell(),
} }
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#![cfg(test)] #![cfg(test)]
use std::{ use std::{
collections::{hash_map::Entry, HashMap},
env, env,
fmt::Write, fmt::Write,
future::{pending, Future}, future::{pending, Future},
...@@ -34,6 +35,7 @@ use next_core::turbopack::{ ...@@ -34,6 +35,7 @@ use next_core::turbopack::{
}; };
use next_dev::{EntryRequest, NextDevServerBuilder}; use next_dev::{EntryRequest, NextDevServerBuilder};
use owo_colors::OwoColorize; use owo_colors::OwoColorize;
use parking_lot::Mutex;
use regex::{Captures, Regex, Replacer}; use regex::{Captures, Regex, Replacer};
use serde::Deserialize; use serde::Deserialize;
use tempdir::TempDir; use tempdir::TempDir;
...@@ -637,10 +639,12 @@ struct ChangeFileCommand { ...@@ -637,10 +639,12 @@ struct ChangeFileCommand {
replace_with: String, replace_with: String,
} }
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared, serialization = "none", eq = "manual", cell = "new")]
struct TestIssueReporter { struct TestIssueReporter {
#[turbo_tasks(trace_ignore, debug_ignore)] #[turbo_tasks(trace_ignore, debug_ignore)]
pub issue_tx: State<UnboundedSender<(ReadRef<PlainIssue>, ReadRef<ValueDebugString>)>>, pub issue_tx: State<UnboundedSender<(ReadRef<PlainIssue>, ReadRef<ValueDebugString>)>>,
#[turbo_tasks(trace_ignore, debug_ignore)]
pub already_printed: Mutex<HashMap<String, ()>>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -653,6 +657,7 @@ impl TestIssueReporter { ...@@ -653,6 +657,7 @@ impl TestIssueReporter {
) -> Vc<Self> { ) -> Vc<Self> {
TestIssueReporter { TestIssueReporter {
issue_tx: State::new((*issue_tx).clone()), issue_tx: State::new((*issue_tx).clone()),
already_printed: Default::default(),
} }
.cell() .cell()
} }
...@@ -678,7 +683,11 @@ impl IssueReporter for TestIssueReporter { ...@@ -678,7 +683,11 @@ impl IssueReporter for TestIssueReporter {
for (issue, path) in captured_issues.iter_with_shortest_path() { for (issue, path) in captured_issues.iter_with_shortest_path() {
let plain = NormalizedIssue(issue).cell().into_plain(path); let plain = NormalizedIssue(issue).cell().into_plain(path);
issue_tx.send((plain.await?, plain.dbg().await?))?; issue_tx.send((plain.await?, plain.dbg().await?))?;
println!("{}", format_issue(&*plain.await?, None, &log_options)); let str = format_issue(&*plain.await?, None, &log_options);
if let Entry::Vacant(e) = self.already_printed.lock().entry(str) {
println!("{}", e.key());
e.insert(());
}
} }
Ok(Vc::cell(false)) Ok(Vc::cell(false))
} }
......
...@@ -48,6 +48,7 @@ function runTests(harness: Harness, iframe: HTMLIFrameElement) { ...@@ -48,6 +48,7 @@ function runTests(harness: Harness, iframe: HTMLIFrameElement) {
TIMEOUT TIMEOUT
) )
// TODO: This test is flaky, so it needs a particularly long timeout.
it( it(
'renders a custom 404 page', 'renders a custom 404 page',
async () => { async () => {
...@@ -58,7 +59,7 @@ function runTests(harness: Harness, iframe: HTMLIFrameElement) { ...@@ -58,7 +59,7 @@ function runTests(harness: Harness, iframe: HTMLIFrameElement) {
iframe.contentDocument!.querySelector('[data-test-notfound]') iframe.contentDocument!.querySelector('[data-test-notfound]')
).not.toBeNull() ).not.toBeNull()
}, },
TIMEOUT LONG_TIMEOUT
) )
// TODO: This test is flaky, so it needs a particularly long timeout. // TODO: This test is flaky, so it needs a particularly long timeout.
......
...@@ -54,7 +54,6 @@ import { isBot } from '../../shared/lib/router/utils/is-bot' ...@@ -54,7 +54,6 @@ import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { AppRouterAnnouncer } from './app-router-announcer' import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary' import { RedirectBoundary } from './redirect-boundary'
import { NotFoundBoundary } from './not-found-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache' import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
import { createInfinitePromise } from './infinite-promise' import { createInfinitePromise } from './infinite-promise'
import { NEXT_RSC_UNION_QUERY } from './app-router-headers' import { NEXT_RSC_UNION_QUERY } from './app-router-headers'
...@@ -89,14 +88,6 @@ export function urlToUrlWithoutFlightMarker(url: string): URL { ...@@ -89,14 +88,6 @@ export function urlToUrlWithoutFlightMarker(url: string): URL {
return urlWithoutFlightParameters return urlWithoutFlightParameters
} }
const HotReloader:
| typeof import('./react-dev-overlay/hot-reloader-client').default
| null =
process.env.NODE_ENV === 'production'
? null
: (require('./react-dev-overlay/hot-reloader-client')
.default as typeof import('./react-dev-overlay/hot-reloader-client').default)
type AppRouterProps = Omit< type AppRouterProps = Omit<
Omit<InitialRouterStateParameters, 'isServer' | 'location'>, Omit<InitialRouterStateParameters, 'isServer' | 'location'>,
'initialParallelRoutes' 'initialParallelRoutes'
...@@ -104,9 +95,6 @@ type AppRouterProps = Omit< ...@@ -104,9 +95,6 @@ type AppRouterProps = Omit<
buildId: string buildId: string
initialHead: ReactNode initialHead: ReactNode
assetPrefix: string assetPrefix: string
// Top level boundaries props
notFound: React.ReactNode | undefined
asNotFound?: boolean
} }
function isExternalURL(url: URL) { function isExternalURL(url: URL) {
...@@ -224,8 +212,6 @@ function Router({ ...@@ -224,8 +212,6 @@ function Router({
initialCanonicalUrl, initialCanonicalUrl,
children, children,
assetPrefix, assetPrefix,
notFound,
asNotFound,
}: AppRouterProps) { }: AppRouterProps) {
const initialState = useMemo( const initialState = useMemo(
() => () =>
...@@ -445,9 +431,7 @@ function Router({ ...@@ -445,9 +431,7 @@ function Router({
return findHeadInCache(cache, tree[1]) return findHeadInCache(cache, tree[1])
}, [cache, tree]) }, [cache, tree])
const notFoundProps = { notFound, asNotFound } let content = (
const content = (
<RedirectBoundary> <RedirectBoundary>
{head} {head}
{cache.subTreeData} {cache.subTreeData}
...@@ -455,6 +439,18 @@ function Router({ ...@@ -455,6 +439,18 @@ function Router({
</RedirectBoundary> </RedirectBoundary>
) )
if (process.env.NODE_ENV !== 'production') {
if (typeof window !== 'undefined') {
const DevRootNotFoundBoundary: typeof import('./dev-root-not-found-boundary').DevRootNotFoundBoundary =
require('./dev-root-not-found-boundary').DevRootNotFoundBoundary
content = <DevRootNotFoundBoundary>{content}</DevRootNotFoundBoundary>
}
const HotReloader: typeof import('./react-dev-overlay/hot-reloader-client').default =
require('./react-dev-overlay/hot-reloader-client').default
content = <HotReloader assetPrefix={assetPrefix}>{content}</HotReloader>
}
return ( return (
<> <>
<HistoryUpdater <HistoryUpdater
...@@ -484,16 +480,7 @@ function Router({ ...@@ -484,16 +480,7 @@ function Router({
url: canonicalUrl, url: canonicalUrl,
}} }}
> >
{HotReloader ? ( {content}
// HotReloader implements a separate NotFoundBoundary to maintain the HMR ping interval
<HotReloader assetPrefix={assetPrefix} {...notFoundProps}>
{content}
</HotReloader>
) : (
<NotFoundBoundary {...notFoundProps}>
{content}
</NotFoundBoundary>
)}
</LayoutRouterContext.Provider> </LayoutRouterContext.Provider>
</AppRouterContext.Provider> </AppRouterContext.Provider>
</GlobalLayoutRouterContext.Provider> </GlobalLayoutRouterContext.Provider>
......
'use client'
import React from 'react'
import { NotFoundBoundary } from './not-found-boundary'
export function bailOnNotFound() {
throw new Error('notFound() is not allowed to use in root layout')
}
function NotAllowedRootNotFoundError() {
bailOnNotFound()
return null
}
export function DevRootNotFoundBoundary({
children,
}: {
children: React.ReactNode
}) {
return (
<NotFoundBoundary notFound={<NotAllowedRootNotFoundError />}>
{children}
</NotFoundBoundary>
)
}
...@@ -491,7 +491,6 @@ export default function OuterLayoutRouter({ ...@@ -491,7 +491,6 @@ export default function OuterLayoutRouter({
template, template,
notFound, notFound,
notFoundStyles, notFoundStyles,
asNotFound,
styles, styles,
}: { }: {
parallelRouterKey: string parallelRouterKey: string
...@@ -506,7 +505,6 @@ export default function OuterLayoutRouter({ ...@@ -506,7 +505,6 @@ export default function OuterLayoutRouter({
hasLoading: boolean hasLoading: boolean
notFound: React.ReactNode | undefined notFound: React.ReactNode | undefined
notFoundStyles: React.ReactNode | undefined notFoundStyles: React.ReactNode | undefined
asNotFound?: boolean
styles?: React.ReactNode styles?: React.ReactNode
}) { }) {
const context = useContext(LayoutRouterContext) const context = useContext(LayoutRouterContext)
...@@ -574,7 +572,6 @@ export default function OuterLayoutRouter({ ...@@ -574,7 +572,6 @@ export default function OuterLayoutRouter({
<NotFoundBoundary <NotFoundBoundary
notFound={notFound} notFound={notFound}
notFoundStyles={notFoundStyles} notFoundStyles={notFoundStyles}
asNotFound={asNotFound}
> >
<RedirectBoundary> <RedirectBoundary>
<InnerLayoutRouter <InnerLayoutRouter
......
...@@ -64,6 +64,9 @@ class NotFoundErrorBoundary extends React.Component< ...@@ -64,6 +64,9 @@ class NotFoundErrorBoundary extends React.Component<
return ( return (
<> <>
<meta name="robots" content="noindex" /> <meta name="robots" content="noindex" />
{process.env.NODE_ENV === 'development' && (
<meta name="next-error" content="not-found" />
)}
{this.props.notFoundStyles} {this.props.notFoundStyles}
{this.props.notFound} {this.props.notFound}
</> </>
......
...@@ -10,7 +10,6 @@ import stripAnsi from 'next/dist/compiled/strip-ansi' ...@@ -10,7 +10,6 @@ import stripAnsi from 'next/dist/compiled/strip-ansi'
import formatWebpackMessages from '../../dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../../dev/error-overlay/format-webpack-messages'
import { useRouter } from '../navigation' import { useRouter } from '../navigation'
import { import {
ACTION_NOT_FOUND,
ACTION_VERSION_INFO, ACTION_VERSION_INFO,
INITIAL_OVERLAY_STATE, INITIAL_OVERLAY_STATE,
errorOverlayReducer, errorOverlayReducer,
...@@ -36,8 +35,6 @@ import { ...@@ -36,8 +35,6 @@ import {
} from './internal/helpers/use-websocket' } from './internal/helpers/use-websocket'
import { parseComponentStack } from './internal/helpers/parse-component-stack' import { parseComponentStack } from './internal/helpers/parse-component-stack'
import type { VersionInfo } from '../../../server/dev/parse-version-info' import type { VersionInfo } from '../../../server/dev/parse-version-info'
import { isNotFoundError } from '../not-found'
import { NotFoundBoundary } from '../not-found-boundary'
interface Dispatcher { interface Dispatcher {
onBuildOk(): void onBuildOk(): void
...@@ -45,7 +42,6 @@ interface Dispatcher { ...@@ -45,7 +42,6 @@ interface Dispatcher {
onVersionInfo(versionInfo: VersionInfo): void onVersionInfo(versionInfo: VersionInfo): void
onBeforeRefresh(): void onBeforeRefresh(): void
onRefresh(): void onRefresh(): void
onNotFound(): void
} }
// TODO-APP: add actual type // TODO-APP: add actual type
...@@ -54,8 +50,6 @@ type PongEvent = any ...@@ -54,8 +50,6 @@ type PongEvent = any
let mostRecentCompilationHash: any = null let mostRecentCompilationHash: any = null
let __nextDevClientId = Math.round(Math.random() * 100 + Date.now()) let __nextDevClientId = Math.round(Math.random() * 100 + Date.now())
// let startLatency = undefined
function onBeforeFastRefresh(dispatcher: Dispatcher, hasUpdates: boolean) { function onBeforeFastRefresh(dispatcher: Dispatcher, hasUpdates: boolean) {
if (hasUpdates) { if (hasUpdates) {
dispatcher.onBeforeRefresh() dispatcher.onBeforeRefresh()
...@@ -422,18 +416,30 @@ function processMessage( ...@@ -422,18 +416,30 @@ function processMessage(
fetch(window.location.href, { fetch(window.location.href, {
credentials: 'same-origin', credentials: 'same-origin',
}).then((pageRes) => { }).then((pageRes) => {
if (pageRes.status === 200) { let shouldRefresh = pageRes.ok
// Page exists now, reload // TODO-APP: investigate why edge runtime needs to reload
startTransition(() => { const isEdgeRuntime = pageRes.headers.get('x-edge-runtime') === '1'
// @ts-ignore it exists, it's just hidden if (pageRes.status === 404) {
router.fastRefresh() // Check if head present as document.head could be null
dispatcher.onRefresh()
})
} else if (pageRes.status === 404) {
// We are still on the page, // We are still on the page,
// dispatch an error so it's caught by the NotFound handler // dispatch an error so it's caught by the NotFound handler
dispatcher.onNotFound() const devErrorMetaTag = document.head?.querySelector(
'meta[name="next-error"]'
)
shouldRefresh = !devErrorMetaTag
} }
// Page exists now, reload
startTransition(() => {
if (shouldRefresh) {
if (isEdgeRuntime) {
window.location.reload()
} else {
// @ts-ignore it exists, it's just hidden
router.fastRefresh()
dispatcher.onRefresh()
}
}
})
}) })
} }
return return
...@@ -450,15 +456,9 @@ function processMessage( ...@@ -450,15 +456,9 @@ function processMessage(
export default function HotReload({ export default function HotReload({
assetPrefix, assetPrefix,
children, children,
notFound,
notFoundStyles,
asNotFound,
}: { }: {
assetPrefix: string assetPrefix: string
children?: ReactNode children?: ReactNode
notFound?: React.ReactNode
notFoundStyles?: React.ReactNode
asNotFound?: boolean
}) { }) {
const [state, dispatch] = useReducer( const [state, dispatch] = useReducer(
errorOverlayReducer, errorOverlayReducer,
...@@ -481,9 +481,6 @@ export default function HotReload({ ...@@ -481,9 +481,6 @@ export default function HotReload({
onVersionInfo(versionInfo) { onVersionInfo(versionInfo) {
dispatch({ type: ACTION_VERSION_INFO, versionInfo }) dispatch({ type: ACTION_VERSION_INFO, versionInfo })
}, },
onNotFound() {
dispatch({ type: ACTION_NOT_FOUND })
},
} }
}, [dispatch]) }, [dispatch])
...@@ -505,9 +502,7 @@ export default function HotReload({ ...@@ -505,9 +502,7 @@ export default function HotReload({
frames: parseStack(reason.stack!), frames: parseStack(reason.stack!),
}) })
}, []) }, [])
const handleOnReactError = useCallback((error: Error) => { const handleOnReactError = useCallback(() => {
// not found errors are handled by the parent boundary, not the dev overlay
if (isNotFoundError(error)) throw error
RuntimeErrorHandler.hadRuntimeError = true RuntimeErrorHandler.hadRuntimeError = true
}, []) }, [])
useErrorHandler(handleOnUnhandledError, handleOnUnhandledRejection) useErrorHandler(handleOnUnhandledError, handleOnUnhandledRejection)
...@@ -538,15 +533,8 @@ export default function HotReload({ ...@@ -538,15 +533,8 @@ export default function HotReload({
}, [sendMessage, router, webSocketRef, dispatcher]) }, [sendMessage, router, webSocketRef, dispatcher])
return ( return (
<NotFoundBoundary <ReactDevOverlay onReactError={handleOnReactError} state={state}>
key={`${state.notFound}`} {children}
notFound={notFound} </ReactDevOverlay>
notFoundStyles={notFoundStyles}
asNotFound={asNotFound}
>
<ReactDevOverlay onReactError={handleOnReactError} state={state}>
{children}
</ReactDevOverlay>
</NotFoundBoundary>
) )
} }
...@@ -13,7 +13,6 @@ import { parseStack } from './helpers/parseStack' ...@@ -13,7 +13,6 @@ import { parseStack } from './helpers/parseStack'
import { Base } from './styles/Base' import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles' import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from './styles/CssReset' import { CssReset } from './styles/CssReset'
import { notFound } from '../../not-found'
interface ReactDevOverlayState { interface ReactDevOverlayState {
reactError: SupportedErrorEvent | null reactError: SupportedErrorEvent | null
...@@ -59,10 +58,6 @@ class ReactDevOverlay extends React.PureComponent< ...@@ -59,10 +58,6 @@ class ReactDevOverlay extends React.PureComponent<
reactError || reactError ||
rootLayoutMissingTagsError rootLayoutMissingTagsError
if (state.notFound) {
notFound()
}
return ( return (
<> <>
{reactError ? ( {reactError ? (
......
...@@ -10,7 +10,6 @@ export const ACTION_REFRESH = 'fast-refresh' ...@@ -10,7 +10,6 @@ export const ACTION_REFRESH = 'fast-refresh'
export const ACTION_UNHANDLED_ERROR = 'unhandled-error' export const ACTION_UNHANDLED_ERROR = 'unhandled-error'
export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection' export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection'
export const ACTION_VERSION_INFO = 'version-info' export const ACTION_VERSION_INFO = 'version-info'
export const ACTION_NOT_FOUND = 'not-found'
export const INITIAL_OVERLAY_STATE: OverlayState = { export const INITIAL_OVERLAY_STATE: OverlayState = {
nextId: 1, nextId: 1,
buildError: null, buildError: null,
...@@ -34,10 +33,6 @@ interface FastRefreshAction { ...@@ -34,10 +33,6 @@ interface FastRefreshAction {
type: typeof ACTION_REFRESH type: typeof ACTION_REFRESH
} }
interface NotFoundAction {
type: typeof ACTION_NOT_FOUND
}
export interface UnhandledErrorAction { export interface UnhandledErrorAction {
type: typeof ACTION_UNHANDLED_ERROR type: typeof ACTION_UNHANDLED_ERROR
reason: Error reason: Error
...@@ -96,7 +91,6 @@ export const errorOverlayReducer: React.Reducer< ...@@ -96,7 +91,6 @@ export const errorOverlayReducer: React.Reducer<
| BuildErrorAction | BuildErrorAction
| BeforeFastRefreshAction | BeforeFastRefreshAction
| FastRefreshAction | FastRefreshAction
| NotFoundAction
| UnhandledErrorAction | UnhandledErrorAction
| UnhandledRejectionAction | UnhandledRejectionAction
| VersionInfoAction | VersionInfoAction
...@@ -104,7 +98,7 @@ export const errorOverlayReducer: React.Reducer< ...@@ -104,7 +98,7 @@ export const errorOverlayReducer: React.Reducer<
> = (state, action) => { > = (state, action) => {
switch (action.type) { switch (action.type) {
case ACTION_BUILD_OK: { case ACTION_BUILD_OK: {
return { ...state, buildError: null, notFound: false } return { ...state, buildError: null }
} }
case ACTION_BUILD_ERROR: { case ACTION_BUILD_ERROR: {
return { ...state, buildError: action.message } return { ...state, buildError: action.message }
...@@ -112,14 +106,10 @@ export const errorOverlayReducer: React.Reducer< ...@@ -112,14 +106,10 @@ export const errorOverlayReducer: React.Reducer<
case ACTION_BEFORE_REFRESH: { case ACTION_BEFORE_REFRESH: {
return { ...state, refreshState: { type: 'pending', errors: [] } } return { ...state, refreshState: { type: 'pending', errors: [] } }
} }
case ACTION_NOT_FOUND: {
return { ...state, notFound: true }
}
case ACTION_REFRESH: { case ACTION_REFRESH: {
return { return {
...state, ...state,
buildError: null, buildError: null,
notFound: false,
errors: errors:
// Errors can come in during updates. In this case, UNHANDLED_ERROR // Errors can come in during updates. In this case, UNHANDLED_ERROR
// and UNHANDLED_REJECTION events might be dispatched between the // and UNHANDLED_REJECTION events might be dispatched between the
......
...@@ -75,18 +75,3 @@ export function createServerComponentRenderer<Props>( ...@@ -75,18 +75,3 @@ export function createServerComponentRenderer<Props>(
return use(response) return use(response)
} }
} }
export function ErrorHtml({
head,
children,
}: {
head?: React.ReactNode
children?: React.ReactNode
}) {
return (
<html id="__next_error__">
<head>{head}</head>
<body>{children}</body>
</html>
)
}
...@@ -36,7 +36,7 @@ export async function getLayoutOrPageModule(loaderTree: LoaderTree) { ...@@ -36,7 +36,7 @@ export async function getLayoutOrPageModule(loaderTree: LoaderTree) {
// First check not-found, if it doesn't exist then pick layout // First check not-found, if it doesn't exist then pick layout
export async function getErrorOrLayoutModule( export async function getErrorOrLayoutModule(
loaderTree: LoaderTree, loaderTree: LoaderTree,
errorType: 'error' | 'not-found' errorType: 'not-found'
) { ) {
const { [errorType]: error, layout } = loaderTree[2] const { [errorType]: error, layout } = loaderTree[2]
if (typeof error !== 'undefined') { if (typeof error !== 'undefined') {
......
...@@ -457,7 +457,6 @@ export async function renderToHTMLImpl( ...@@ -457,7 +457,6 @@ export async function renderToHTMLImpl(
let Document = extra.Document let Document = extra.Document
// Component will be wrapped by ServerComponentWrapper for RSC
let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) = let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) =
renderOpts.Component renderOpts.Component
const OriginComponent = Component const OriginComponent = Component
......
...@@ -30,6 +30,25 @@ export const streamToBufferedResult = async ( ...@@ -30,6 +30,25 @@ export const streamToBufferedResult = async (
return renderChunks.join('') return renderChunks.join('')
} }
export function cloneTransformStream(source: TransformStream) {
const sourceReader = source.readable.getReader()
const clone = new TransformStream({
async start(controller) {
while (true) {
const { done, value } = await sourceReader.read()
if (done) {
break
}
controller.enqueue(value)
}
},
// skip the its own written chunks
transform() {},
})
return clone
}
export function readableStreamTee<T = any>( export function readableStreamTee<T = any>(
readable: ReadableStream<T> readable: ReadableStream<T>
): [ReadableStream<T>, ReadableStream<T>] { ): [ReadableStream<T>, ReadableStream<T>] {
......
...@@ -5,7 +5,7 @@ import { redirectAction } from './actions' ...@@ -5,7 +5,7 @@ import { redirectAction } from './actions'
export default function Form() { export default function Form() {
return ( return (
<form> <form>
<input type="text" name="hidden-info" value="hi" hidden /> <input type="text" name="hidden-info" defaultValue="hi" hidden />
<input type="text" name="name" id="client-name" required /> <input type="text" name="name" id="client-name" required />
<button formAction={redirectAction} type="submit" id="there"> <button formAction={redirectAction} type="submit" id="there">
Go there Go there
......
...@@ -45,7 +45,7 @@ export default function Form() { ...@@ -45,7 +45,7 @@ export default function Form() {
<> <>
<hr /> <hr />
<form action={action}> <form action={action}>
<input type="text" name="hidden-info" value="hi" hidden /> <input type="text" name="hidden-info" defaultValue="hi" hidden />
<input type="text" name="name" id="name" required /> <input type="text" name="name" id="name" required />
<button type="submit" id="submit"> <button type="submit" id="submit">
Submit Submit
......
export default function notFound() { export default function NotFound() {
return <h2>root not found page</h2> return <h2>root not found page</h2>
} }
......
...@@ -535,11 +535,18 @@ createNextDescribe( ...@@ -535,11 +535,18 @@ createNextDescribe(
const noIndexTag = '<meta name="robots" content="noindex"/>' const noIndexTag = '<meta name="robots" content="noindex"/>'
const defaultViewportTag = const defaultViewportTag =
'<meta name="viewport" content="width=device-width, initial-scale=1"/>' '<meta name="viewport" content="width=device-width, initial-scale=1"/>'
const devErrorMetadataTag =
'<meta name="next-error" content="not-found"/>'
const html = await next.render('/not-found/suspense') const html = await next.render('/not-found/suspense')
expect(html).toContain(noIndexTag) expect(html).toContain(noIndexTag)
// only contain once // only contain once
expect(html.split(noIndexTag).length).toBe(2) expect(html.split(noIndexTag).length).toBe(2)
expect(html.split(defaultViewportTag).length).toBe(2) expect(html.split(defaultViewportTag).length).toBe(2)
if (isNextDev) {
// only contain dev error tag once
expect(html.split(devErrorMetadataTag).length).toBe(2)
}
}) })
it('should emit refresh meta tag for redirect page when streaming', async () => { it('should emit refresh meta tag for redirect page when streaming', async () => {
......
export default function Layout({ children }) { export default function Layout({ children }) {
return ( return (
<html> <html>
<head> <head />
<title>Hello World</title> <body>
</head> <header>
<body>{children}</body> <nav id="layout-nav">Navbar</nav>
</header>
{children}
<footer>
<p id="layout-footer">Footer</p>
</footer>
</body>
</html> </html>
) )
} }
export default function Page() { export default function NotFound() {
return ( return (
<> <>
<h1>This Is The Not Found Page</h1> <h1>This Is The Not Found Page</h1>
...@@ -7,3 +7,5 @@ export default function Page() { ...@@ -7,3 +7,5 @@ export default function Page() {
</> </>
) )
} }
NotFound.displayName = 'NotFound'
...@@ -10,8 +10,12 @@ createNextDescribe( ...@@ -10,8 +10,12 @@ createNextDescribe(
({ next, isNextDev }) => { ({ next, isNextDev }) => {
const runTests = ({ isEdge }: { isEdge: boolean }) => { const runTests = ({ isEdge }: { isEdge: boolean }) => {
it('should use the not-found page for non-matching routes', async () => { it('should use the not-found page for non-matching routes', async () => {
const html = await next.render('/random-content') const browser = await next.browser('/random-content')
expect(html).toContain('This Is The Not Found Page') expect(await browser.elementByCss('h1').text()).toContain(
'This Is The Not Found Page'
)
// should contain root layout content
expect(await browser.elementByCss('#layout-nav').text()).toBe('Navbar')
}) })
it('should allow to have a valid /not-found route', async () => { it('should allow to have a valid /not-found route', async () => {
......
'use client'
import React, { useState } from 'react'
import { notFound } from 'next/navigation'
import NotFoundTrigger from './not-found-trigger'
export default function Root({ children }) {
// notFound()
const [clicked, setClicked] = useState(false)
if (clicked) {
notFound()
}
return (
<html>
<body>
<NotFoundTrigger />
<button id="trigger-not-found" onClick={() => setClicked(true)}>
Click to not found
</button>
{children}
</body>
</html>
)
}
export const dynamic = 'force-dynamic'
'use client'
import { useSearchParams, notFound } from 'next/navigation'
export default function NotFoundTrigger() {
const searchParams = useSearchParams()
if (searchParams.get('root-not-found')) {
notFound()
}
return null
}
export default function Page() {
return <p>hello world</p>
}
import { createNextDescribe } from 'e2e-utils'
import { check, getRedboxDescription, hasRedbox } from 'next-test-utils'
createNextDescribe(
'app dir - root layout not found',
{
files: __dirname,
skipDeployment: true,
},
({ next, isNextDev }) => {
it('should error on client notFound from root layout in browser', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#trigger-not-found').click()
if (isNextDev) {
await check(async () => {
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxDescription(browser)).toMatch(
/notFound\(\) is not allowed to use in root layout/
)
return 'success'
}, /success/)
} else {
expect(await browser.elementByCss('h2').text()).toBe(
'Application error: a server-side exception has occurred (see the server logs for more information).'
)
expect(await browser.elementByCss('p').text()).toBe(
'Digest: NEXT_NOT_FOUND'
)
}
})
it('should error on server notFound from root layout on server-side', async () => {
const browser = await next.browser('/?root-not-found=1')
if (isNextDev) {
expect(await hasRedbox(browser, true)).toBe(true)
expect(await getRedboxDescription(browser)).toBe(
'Error: notFound() is not allowed to use in root layout'
)
} else {
expect(await browser.elementByCss('h2').text()).toBe(
'Application error: a server-side exception has occurred (see the server logs for more information).'
)
expect(await browser.elementByCss('p').text()).toBe(
'Digest: NEXT_NOT_FOUND'
)
}
})
}
)
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