Unverified Commit c98d2b92 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix: handle 404 errors in HotReload client (#51637)

### What?
In dev mode, routing to a 404 page will result in an infinite redirect
cycle. This PR is an attempt to bring back similar functionality
currently implemented in the [pages
router.](https://github.com/vercel/next.js/blob/canary/packages/next/src/client/dev/on-demand-entries-client.ts#L41-L59)

### Why?
When the `pong` event (emitted from `onHMR`) occurs on a page that
doesn't exist, it will result in frequent calls to
`router.fastRefresh()`. Because the server response is an error, it'll
trigger a mpa navigation
[here](https://github.com/vercel/next.js/blob/61ab4aadecb1f553fcb42ff9055d5b7af63c3f02/packages/next/src/client/components/router-reducer/fetch-server-response.ts#L115-L117),
which is treated as an external route
[here](https://github.com/vercel/next.js/blob/61ab4aadecb1f553fcb42ff9055d5b7af63c3f02/packages/next/src/client/components/router-reducer/reducers/fast-refresh-reducer.ts#L45-L53)
(and thus the window is reloaded)

In the case where you're on the page and it goes away, since we don't
have access to `__NEXT_DATA__`, I opted to use the dispatcher which will
trigger the parent `NotFoundBoundary`. This part felt a little awkward
-- I'm open to suggestions on a better way to handle this.

Closes NEXT-1299
Fixes #50585

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent a9870df1
...@@ -434,18 +434,14 @@ function Router({ ...@@ -434,18 +434,14 @@ function Router({
return findHeadInCache(cache, tree[1]) return findHeadInCache(cache, tree[1])
}, [cache, tree]) }, [cache, tree])
const notFoundProps = { notFound, notFoundStyles, asNotFound }
const content = ( const content = (
<NotFoundBoundary <RedirectBoundary>
notFound={notFound} {head}
notFoundStyles={notFoundStyles} {cache.subTreeData}
asNotFound={asNotFound} <AppRouterAnnouncer tree={tree} />
> </RedirectBoundary>
<RedirectBoundary>
{head}
{cache.subTreeData}
<AppRouterAnnouncer tree={tree} />
</RedirectBoundary>
</NotFoundBoundary>
) )
return ( return (
...@@ -478,9 +474,14 @@ function Router({ ...@@ -478,9 +474,14 @@ function Router({
}} }}
> >
{HotReloader ? ( {HotReloader ? (
<HotReloader assetPrefix={assetPrefix}>{content}</HotReloader> // HotReloader implements a separate NotFoundBoundary to maintain the HMR ping interval
<HotReloader assetPrefix={assetPrefix} {...notFoundProps}>
{content}
</HotReloader>
) : ( ) : (
content <NotFoundBoundary {...notFoundProps}>
{content}
</NotFoundBoundary>
)} )}
</LayoutRouterContext.Provider> </LayoutRouterContext.Provider>
</AppRouterContext.Provider> </AppRouterContext.Provider>
......
...@@ -10,6 +10,7 @@ import stripAnsi from 'next/dist/compiled/strip-ansi' ...@@ -10,6 +10,7 @@ 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,
errorOverlayReducer, errorOverlayReducer,
} from './internal/error-overlay-reducer' } from './internal/error-overlay-reducer'
...@@ -34,6 +35,8 @@ import { ...@@ -34,6 +35,8 @@ 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
...@@ -41,6 +44,7 @@ interface Dispatcher { ...@@ -41,6 +44,7 @@ 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
...@@ -414,8 +418,22 @@ function processMessage( ...@@ -414,8 +418,22 @@ function processMessage(
if (invalid) { if (invalid) {
// Payload can be invalid even if the page does exist. // Payload can be invalid even if the page does exist.
// So, we check if it can be created. // So, we check if it can be created.
// @ts-ignore it exists, it's just hidden fetch(window.location.href, {
router.fastRefresh() credentials: 'same-origin',
}).then((pageRes) => {
if (pageRes.status === 200) {
// Page exists now, reload
startTransition(() => {
// @ts-ignore it exists, it's just hidden
router.fastRefresh()
dispatcher.onRefresh()
})
} else {
// We are still on the page,
// dispatch an error so it's caught by the NotFound handler
dispatcher.onNotFound()
}
})
} }
return return
} }
...@@ -428,14 +446,21 @@ function processMessage( ...@@ -428,14 +446,21 @@ 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(errorOverlayReducer, { const [state, dispatch] = useReducer(errorOverlayReducer, {
nextId: 1, nextId: 1,
buildError: null, buildError: null,
errors: [], errors: [],
notFound: false,
refreshState: { type: 'idle' }, refreshState: { type: 'idle' },
versionInfo: { installed: '0.0.0', staleness: 'unknown' }, versionInfo: { installed: '0.0.0', staleness: 'unknown' },
}) })
...@@ -456,6 +481,9 @@ export default function HotReload({ ...@@ -456,6 +481,9 @@ 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])
...@@ -477,7 +505,9 @@ export default function HotReload({ ...@@ -477,7 +505,9 @@ export default function HotReload({
frames: parseStack(reason.stack!), frames: parseStack(reason.stack!),
}) })
}, []) }, [])
const handleOnReactError = useCallback(() => { const handleOnReactError = useCallback((error: Error) => {
// 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)
...@@ -487,6 +517,7 @@ export default function HotReload({ ...@@ -487,6 +517,7 @@ export default function HotReload({
const sendMessage = useSendMessage(webSocketRef) const sendMessage = useSendMessage(webSocketRef)
const router = useRouter() const router = useRouter()
useEffect(() => { useEffect(() => {
const handler = (event: MessageEvent<PongEvent>) => { const handler = (event: MessageEvent<PongEvent>) => {
try { try {
...@@ -507,8 +538,15 @@ export default function HotReload({ ...@@ -507,8 +538,15 @@ export default function HotReload({
}, [sendMessage, router, webSocketRef, dispatcher]) }, [sendMessage, router, webSocketRef, dispatcher])
return ( return (
<ReactDevOverlay onReactError={handleOnReactError} state={state}> <NotFoundBoundary
{children} key={`${state.notFound}`}
</ReactDevOverlay> notFound={notFound}
notFoundStyles={notFoundStyles}
asNotFound={asNotFound}
>
<ReactDevOverlay onReactError={handleOnReactError} state={state}>
{children}
</ReactDevOverlay>
</NotFoundBoundary>
) )
} }
...@@ -13,6 +13,7 @@ import { parseStack } from './helpers/parseStack' ...@@ -13,6 +13,7 @@ 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
...@@ -58,6 +59,10 @@ class ReactDevOverlay extends React.PureComponent< ...@@ -58,6 +59,10 @@ class ReactDevOverlay extends React.PureComponent<
reactError || reactError ||
rootLayoutMissingTagsError rootLayoutMissingTagsError
if (state.notFound) {
notFound()
}
return ( return (
<> <>
{reactError ? ( {reactError ? (
......
...@@ -10,6 +10,7 @@ export const ACTION_REFRESH = 'fast-refresh' ...@@ -10,6 +10,7 @@ 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'
interface BuildOkAction { interface BuildOkAction {
type: typeof ACTION_BUILD_OK type: typeof ACTION_BUILD_OK
...@@ -24,6 +25,11 @@ interface BeforeFastRefreshAction { ...@@ -24,6 +25,11 @@ interface BeforeFastRefreshAction {
interface FastRefreshAction { 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
...@@ -59,6 +65,7 @@ export interface OverlayState { ...@@ -59,6 +65,7 @@ export interface OverlayState {
} }
refreshState: FastRefreshState refreshState: FastRefreshState
versionInfo: VersionInfo versionInfo: VersionInfo
notFound: boolean
} }
function pushErrorFilterDuplicates( function pushErrorFilterDuplicates(
...@@ -81,6 +88,7 @@ export const errorOverlayReducer: React.Reducer< ...@@ -81,6 +88,7 @@ export const errorOverlayReducer: React.Reducer<
| BuildErrorAction | BuildErrorAction
| BeforeFastRefreshAction | BeforeFastRefreshAction
| FastRefreshAction | FastRefreshAction
| NotFoundAction
| UnhandledErrorAction | UnhandledErrorAction
| UnhandledRejectionAction | UnhandledRejectionAction
| VersionInfoAction | VersionInfoAction
...@@ -88,7 +96,7 @@ export const errorOverlayReducer: React.Reducer< ...@@ -88,7 +96,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 } return { ...state, buildError: null, notFound: false }
} }
case ACTION_BUILD_ERROR: { case ACTION_BUILD_ERROR: {
return { ...state, buildError: action.message } return { ...state, buildError: action.message }
...@@ -96,10 +104,14 @@ export const errorOverlayReducer: React.Reducer< ...@@ -96,10 +104,14 @@ 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
......
...@@ -50,7 +50,6 @@ export function useWebsocketPing( ...@@ -50,7 +50,6 @@ export function useWebsocketPing(
useEffect(() => { useEffect(() => {
// Taken from on-demand-entries-client.js // Taken from on-demand-entries-client.js
// TODO-APP: check 404 case
const interval = setInterval(() => { const interval = setInterval(() => {
sendMessage( sendMessage(
JSON.stringify({ JSON.stringify({
......
export default function Page() { export default function Page() {
return <h1>This Is The Not Found Page</h1> return (
<>
<h1>This Is The Not Found Page</h1>
<div id="timestamp">{Date.now()}</div>
</>
)
} }
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe( createNextDescribe(
'app dir - not-found', 'app dir - not-found',
...@@ -18,6 +19,34 @@ createNextDescribe( ...@@ -18,6 +19,34 @@ createNextDescribe(
expect(html).toContain("I'm still a valid page") expect(html).toContain("I'm still a valid page")
}) })
if (isNextDev) {
it('should not reload the page', async () => {
const browser = await next.browser('/random-content')
const timestamp = await browser.elementByCss('#timestamp').text()
await new Promise((resolve) => {
setTimeout(resolve, 3000)
})
await check(async () => {
const newTimestamp = await browser.elementByCss('#timestamp').text()
return newTimestamp !== timestamp ? 'failure' : 'success'
}, 'success')
})
it('should render the 404 page when the file is removed, and restore the page when re-added', async () => {
const browser = await next.browser('/')
await check(() => browser.elementByCss('h1').text(), 'My page')
await next.renameFile('./app/page.js', './app/foo.js')
await check(
() => browser.elementByCss('h1').text(),
'This Is The Not Found Page'
)
await next.renameFile('./app/foo.js', './app/page.js')
await check(() => browser.elementByCss('h1').text(), 'My page')
})
}
if (!isNextDev) { if (!isNextDev) {
it('should create the 404 mapping and copy the file to pages', async () => { it('should create the 404 mapping and copy the file to pages', async () => {
const html = await next.readFile('.next/server/pages/404.html') const html = await next.readFile('.next/server/pages/404.html')
......
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