Unverified Commit 69776cc3 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[dev-overlay] remove special handling for missing tag error (#77147)

### What

We had a few existing hacks for the missing html tag errors, we used a
lot of tricks and components to deal with it specifically. It was quite
a pain to handle on specific error across the entire codebase. This PR
leverage the existing SSR error template we sent through the rendering.
We now inject a open `<html>` tag to intercept the HTML. And then it
will be consumed as a SSR error. We added one more thing that we'll open
the error overlay automatically by default. It doesn't have to be build
error since the display was not ideal.

Now it's just one of the normal error, such like it can show the version
indicator as well. Except we had a little bit logic to make it pop up by
default.

The idea is to insert a piece of errored html like what we expect for
erroring rendered html. So it inserts a new start point of the html, and
then React will hydrate it with the error template.

```html
<!-- layout / page content -->
<meta .. />
<script .. />

<!-- we insert a html for missing tag error -->
<html id="__next_error__">
  <template data-next-error-message=".." ..></template>

<!-- next.js always render close tag -->
</body>
</html>
```


| After | Before |
|:-- |:--|
| <img width="1048" alt="image"
src="https://github.com/user-attachments/assets/713812cf-50cd-4b14-8906-44ed3795ef12"
/> | <img width="1020" alt="image"
src="https://github.com/user-attachments/assets/ac7614d9-da3b-48d1-bab1-c97355c27963"
/> |
parent 95490329
......@@ -25,7 +25,6 @@ import type { InitialRSCPayload } from '../server/app-render/types'
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state'
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime'
import { setAppBuildId } from './app-build-id'
import { shouldRenderRootLevelErrorOverlay } from './lib/is-error-thrown-while-rendering-rsc'
/// <reference types="react-dom/experimental" />
......@@ -250,16 +249,10 @@ export function hydrate() {
</StrictModeIfEnabled>
)
if (
document.documentElement.id === '__next_error__' ||
!!window.__next_root_layout_missing_tags?.length
) {
if (document.documentElement.id === '__next_error__') {
let element = reactEl
// Server rendering failed, fall back to client-side rendering
if (
process.env.NODE_ENV !== 'production' &&
shouldRenderRootLevelErrorOverlay()
) {
if (process.env.NODE_ENV !== 'production') {
const { createRootLevelDevOverlayElement } =
require('./components/react-dev-overlay/app/client-entry') as typeof import('./components/react-dev-overlay/app/client-entry')
......
import type { OverlayState } from '../shared'
import type { GlobalErrorComponent } from '../../error-boundary'
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
import { FontStyles } from '../font/font-styles'
import { DevOverlay } from '../ui/dev-overlay'
import { handleClientError } from '../../errors/use-error-handler'
import { isNextRouterError } from '../../is-next-router-error'
import { MISSING_ROOT_TAGS_ERROR } from '../../../../shared/lib/errors/constants'
function readSsrError(): Error | null {
function readSsrError(): (Error & { digest?: string }) | null {
if (typeof document === 'undefined') {
return null
}
......@@ -40,7 +41,11 @@ function readSsrError(): Error | null {
// Needs to be in the same error boundary as the shell.
// If it commits, we know we recovered from an SSR error.
// If it doesn't commit, we errored again and React will take care of error reporting.
function ReplaySsrOnlyErrors() {
function ReplaySsrOnlyErrors({
onBlockingError,
}: {
onBlockingError: () => void
}) {
if (process.env.NODE_ENV !== 'production') {
// Need to read during render. The attributes will be gone after commit.
const ssrError = readSsrError()
......@@ -51,8 +56,13 @@ function ReplaySsrOnlyErrors() {
// TODO(veil): Mark as recoverable error
// TODO(veil): console.error
handleClientError(ssrError, [])
// If it's missing root tags, we can't recover, make it blocking.
if (ssrError.digest === MISSING_ROOT_TAGS_ERROR) {
onBlockingError()
}
}
}, [ssrError])
}, [ssrError, onBlockingError])
}
return null
......@@ -68,6 +78,9 @@ export function AppDevOverlay({
children: React.ReactNode
}) {
const [isErrorOverlayOpen, setIsErrorOverlayOpen] = useState(false)
const openOverlay = useCallback(() => {
setIsErrorOverlayOpen(true)
}, [])
return (
<>
......@@ -75,17 +88,18 @@ export function AppDevOverlay({
globalError={globalError}
onError={setIsErrorOverlayOpen}
>
<ReplaySsrOnlyErrors />
<ReplaySsrOnlyErrors onBlockingError={openOverlay} />
{children}
</AppDevOverlayErrorBoundary>
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlay
state={state}
isErrorOverlayOpen={isErrorOverlayOpen}
setIsErrorOverlayOpen={setIsErrorOverlayOpen}
/>
<>
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlay
state={state}
isErrorOverlayOpen={isErrorOverlayOpen}
setIsErrorOverlayOpen={setIsErrorOverlayOpen}
/>
</>
</>
)
}
import React from 'react'
import { AppDevOverlay } from './app-dev-overlay'
import { getSocketUrl } from '../utils/get-socket-url'
import { INITIAL_OVERLAY_STATE } from '../shared'
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types'
import GlobalError from '../../error-boundary'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
const noop = () => {}
// if an error is thrown while rendering an RSC stream, this will catch it in dev
// and show the error overlay
export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) {
const rootLayoutMissingTags = window.__next_root_layout_missing_tags
const hasMissingTags = !!rootLayoutMissingTags?.length
const socketUrl = getSocketUrl(process.env.__NEXT_ASSET_PREFIX || '')
const socket = new window.WebSocket(`${socketUrl}/_next/webpack-hmr`)
......@@ -31,26 +30,12 @@ export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) {
socket.addEventListener('message', handler)
const FallbackLayout = hasMissingTags
? ({ children }: { children: React.ReactNode }) => (
<html id="__next_error__">
<body>{children}</body>
</html>
)
: React.Fragment
return (
<FallbackLayout>
<AppDevOverlay
state={{
...INITIAL_OVERLAY_STATE,
rootLayoutMissingTags,
routerType: 'app',
}}
globalError={[GlobalError, null]}
>
{reactEl}
</AppDevOverlay>
</FallbackLayout>
<AppDevOverlayErrorBoundary
globalError={[GlobalError, null]}
onError={noop}
>
{reactEl}
</AppDevOverlayErrorBoundary>
)
}
import type { ReactNode } from 'react'
import {
useCallback,
useEffect,
startTransition,
useMemo,
useRef,
useSyncExternalStore,
} from 'react'
import { useCallback, useEffect, startTransition, useMemo, useRef } from 'react'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import formatWebpackMessages from '../utils/format-webpack-messages'
import { useRouter } from '../../navigation'
......@@ -47,7 +40,6 @@ import type { HydrationErrorState } from '../../errors/hydration-error-info'
import type { DebugInfo } from '../types'
import { useUntrackedPathname } from '../../navigation-untracked'
import { getReactStitchedError } from '../../errors/stitched-error'
import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown-while-rendering-rsc'
import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events'
import type { GlobalErrorComponent } from '../../error-boundary'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
......@@ -553,15 +545,6 @@ export default function HotReload({
}
}, [dispatch])
// We render a separate error overlay at the root when an error is thrown from rendering RSC, so
// we should not render an additional error overlay in the descendent. However, we need to
// keep rendering these hooks to ensure HMR works when the error is addressed.
const shouldRenderErrorOverlay = useSyncExternalStore(
() => () => {},
() => !shouldRenderRootLevelErrorOverlay(),
() => true
)
const handleOnUnhandledError = useCallback(
(error: Error): void => {
const errorDetails = (error as any).details as
......@@ -681,13 +664,9 @@ export default function HotReload({
appIsrManifestRef,
])
if (shouldRenderErrorOverlay) {
return (
<AppDevOverlay state={state} globalError={globalError}>
{children}
</AppDevOverlay>
)
}
return children
return (
<AppDevOverlay state={state} globalError={globalError}>
{children}
</AppDevOverlay>
)
}
......@@ -19,7 +19,6 @@ export interface OverlayState {
buildError: string | null
errors: SupportedErrorEvent[]
refreshState: FastRefreshState
rootLayoutMissingTags: typeof window.__next_root_layout_missing_tags
versionInfo: VersionInfo
notFound: boolean
staticIndicator: boolean
......@@ -127,7 +126,6 @@ export const INITIAL_OVERLAY_STATE: Omit<OverlayState, 'routerType'> = {
// To prevent flickering, set the initial state to disabled.
disableDevIndicator: true,
refreshState: { type: 'idle' },
rootLayoutMissingTags: [],
versionInfo: { installed: '0.0.0', staleness: 'unknown' },
debugInfo: { devtoolsFrontendUrl: undefined },
}
......
......@@ -51,7 +51,6 @@ const state: OverlayState = {
errors: [],
refreshState: { type: 'idle' },
disableDevIndicator: false,
rootLayoutMissingTags: [],
versionInfo: mockVersionInfo,
notFound: false,
staticIndicator: true,
......
......@@ -3,7 +3,6 @@ import type { OverlayState } from '../../../../shared'
import { Suspense } from 'react'
import { BuildError } from '../../../container/build-error'
import { Errors } from '../../../container/errors'
import { RootLayoutMissingTagsError } from '../../../container/root-layout-missing-tags-error'
import { useDelayedRender } from '../../../hooks/use-delayed-render'
import type { ReadyRuntimeError } from '../../../../utils/get-error-by-type'
......@@ -41,17 +40,6 @@ export function ErrorOverlay({
versionInfo: state.versionInfo,
}
if (!!state.rootLayoutMissingTags?.length) {
return (
<RootLayoutMissingTagsError
{...commonProps}
// This is not a runtime error, forcedly display error overlay
rendered
missingTags={state.rootLayoutMissingTags}
/>
)
}
if (state.buildError !== null) {
return (
<BuildError
......
import type { Meta, StoryObj } from '@storybook/react'
import { RootLayoutMissingTagsError } from './root-layout-missing-tags-error'
import { withShadowPortal } from '../storybook/with-shadow-portal'
const meta: Meta<typeof RootLayoutMissingTagsError> = {
component: RootLayoutMissingTagsError,
parameters: {
layout: 'fullscreen',
},
decorators: [withShadowPortal],
}
export default meta
type Story = StoryObj<typeof RootLayoutMissingTagsError>
export const Default: Story = {
args: {
missingTags: ['html', 'body'],
versionInfo: {
installed: '15.0.0',
staleness: 'fresh',
},
},
}
export const SingleTag: Story = {
args: {
missingTags: ['html'],
versionInfo: {
installed: '15.0.0',
staleness: 'fresh',
},
},
}
export const Turbopack: Story = {
args: {
...Default.args,
isTurbopack: true,
},
}
import { useCallback } from 'react'
import { HotlinkedText } from '../components/hot-linked-text'
import { ErrorOverlayLayout } from '../components/errors/error-overlay-layout/error-overlay-layout'
import type { ErrorBaseProps } from '../components/errors/error-overlay/error-overlay'
interface RootLayoutMissingTagsErrorProps extends ErrorBaseProps {
missingTags: string[]
}
export function RootLayoutMissingTagsError({
missingTags,
...props
}: RootLayoutMissingTagsErrorProps) {
const noop = useCallback(() => {}, [])
const error = new Error(
`The following tags are missing in the Root Layout: ${missingTags
.map((tagName) => `<${tagName}>`)
.join(
', '
)}.\nRead more at https://nextjs.org/docs/messages/missing-root-layout-tags`
)
return (
<ErrorOverlayLayout
errorType="Missing Required HTML Tag"
error={error}
errorMessage={<HotlinkedText text={error.message} />}
onClose={noop}
{...props}
/>
)
}
......@@ -41,8 +41,7 @@ type Props = {
export const RenderError = (props: Props) => {
const { state } = props
const isBuildError =
!!state.rootLayoutMissingTags?.length || !!state.buildError
const isBuildError = !!state.buildError
if (isBuildError) {
return <RenderBuildError {...props} />
......
......@@ -73,7 +73,6 @@ const state: OverlayState = {
},
],
refreshState: { type: 'idle' },
rootLayoutMissingTags: [],
notFound: false,
staticIndicator: false,
debugInfo: { devtoolsFrontendUrl: undefined },
......
export const shouldRenderRootLevelErrorOverlay = () => {
return !!window.__next_root_layout_missing_tags?.length
}
......@@ -8,6 +8,7 @@ import {
isEquivalentUint8Arrays,
removeFromUint8Array,
} from './uint8array-helpers'
import { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants'
function voidCatch() {
// this catcher is designed to be used with pipeTo where we expect the underlying
......@@ -489,7 +490,7 @@ export function createRootLayoutValidatorStream(): TransformStream<
controller.enqueue(chunk)
},
flush(controller) {
const missingTags: typeof window.__next_root_layout_missing_tags = []
const missingTags: ('html' | 'body')[] = []
if (!foundHtml) missingTags.push('html')
if (!foundBody) missingTags.push('body')
......@@ -497,9 +498,17 @@ export function createRootLayoutValidatorStream(): TransformStream<
controller.enqueue(
encoder.encode(
`<script>self.__next_root_layout_missing_tags=${JSON.stringify(
missingTags
)}</script>`
`<html id="__next_error__">
<template
data-next-error-message="Missing ${missingTags
.map((c) => `<${c}>`)
.join(
missingTags.length > 1 ? ' and ' : ''
)} tags in the root layout.\nRead more at https://nextjs.org/docs/messages/missing-root-layout-tags""
data-next-error-digest="${MISSING_ROOT_TAGS_ERROR}"
data-next-error-stack=""
></template>
`
)
)
},
......
export const MISSING_ROOT_TAGS_ERROR = 'NEXT_MISSING_ROOT_TAGS'
......@@ -2,15 +2,13 @@ import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
assertNoRedbox,
getRedboxDescription,
getToastErrorCount,
hasErrorToast,
retry,
} from 'next-test-utils'
import { outdent } from 'outdent'
describe('app-dir - missing required html tags', () => {
const { next } = nextTestSetup({ files: __dirname })
const { next, isTurbopack } = nextTestSetup({ files: __dirname })
it('should display correct error count in dev indicator', async () => {
const browser = await next.browser('/')
......@@ -18,24 +16,23 @@ describe('app-dir - missing required html tags', () => {
retry(async () => {
expect(await hasErrorToast(browser)).toBe(true)
})
// Dev indicator should show 1 error
expect(await getToastErrorCount(browser)).toBe(1)
})
it('should show error overlay', async () => {
const browser = await next.browser('/')
// There was a bug where multiple dialogs were being rendered when required
// html tags were missing. This test ensures there is no regression.
await retry(async () => {
const dialogs = await browser.elementsByCss('nextjs-portal')
expect(dialogs).toHaveLength(1)
})
await assertHasRedbox(browser)
expect(await getRedboxDescription(browser)).toMatchInlineSnapshot(`
"The following tags are missing in the Root Layout: <html>, <body>.
Read more at https://nextjs.org/docs/messages/missing-root-layout-tags"
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: Missing <html> and <body> tags in the root layout.
Read more at https://nextjs.org/docs/messages/missing-root-layout-tags",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": null,
"stack": [],
}
`)
})
......@@ -47,13 +44,18 @@ describe('app-dir - missing required html tags', () => {
)
await assertHasRedbox(browser)
// Wait for the HMR to apply and the updated error to show.
await retry(async () => {
expect(await getRedboxDescription(browser)).toEqual(outdent`
The following tags are missing in the Root Layout: <html>.
Read more at https://nextjs.org/docs/messages/missing-root-layout-tags
`)
})
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: Missing <html> tags in the root layout.
Read more at https://nextjs.org/docs/messages/missing-root-layout-tags",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": null,
"stack": [],
}
`)
await next.patchFile('app/layout.js', (code) =>
code.replace(
......@@ -73,15 +75,19 @@ describe('app-dir - missing required html tags', () => {
)
)
if (process.env.TURBOPACK) {
if (isTurbopack) {
await assertHasRedbox(browser)
// Wait for the HMR to apply and the updated error to show.
await retry(async () => {
expect(await getRedboxDescription(browser)).toEqual(outdent`
The following tags are missing in the Root Layout: <html>, <body>.
Read more at https://nextjs.org/docs/messages/missing-root-layout-tags
`)
})
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: Missing <html> and <body> tags in the root layout.
Read more at https://nextjs.org/docs/messages/missing-root-layout-tags",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": null,
"stack": [],
}
`)
} else {
// TODO(NDX-768): Should show "missing tags" error
await assertNoRedbox(browser)
......
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