Unverified Commit 4d925698 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Expose App Router runtime errors over HMR (#98438)

Ported from #98040 by @marcoshernanz.

> [!TIP]
> Best reviewed commit by commit.

### Why?

External development tools need browser runtime-error state, not just
build errors, to display application failures. Reporting remains opt-in
so applications that do not need it avoid client serialization, HMR
transport, server formatting, buffering, and rebroadcast overhead.

### How?

Add `experimental.exposeRuntimeErrorsToHMR` for App Router development
with Webpack and Turbopack. Internal integrations can also enable the
same behavior without changing `next.config` by setting
`__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR` to any non-empty value. When
enabled, the HMR WebSocket emits `runtimeErrors` snapshots containing:

- The current pathname and browser client/document identifiers.
- Error types, names, messages, and source-mapped stacks.
- Fatality and optional catching-boundary details (`default-global`,
`custom-global`, or `custom`).

Snapshots update as errors and navigation change. New or reconnected
observers receive the current state, and disconnecting a browser clears
its reported errors. An empty snapshot means there are no currently
reported errors; it does not guarantee application recovery.

Reporting is disabled by default. Pages Router, MCP `get_errors`, and
production behavior are unchanged.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent 3c9d1ca7
......@@ -369,6 +369,10 @@ export function getDefineEnv({
(config.logging && config.logging.browserToTerminal) || false
),
'process.env.__NEXT_MCP_SERVER': !!config.experimental.mcpServer,
'process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR':
dev &&
(config.experimental.exposeRuntimeErrorsToHMR ||
Boolean(process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR)),
// The devtools need to know whether or not to show an option to clear the
// bundler cache. This option may be removed later once Turbopack's
......
......@@ -17,6 +17,11 @@ appBootstrap((assetPrefix) => {
try {
hydrate(instrumentationModules, assetPrefix)
} finally {
renderAppDevOverlay(getOwnerStack, isRecoverableError, enableCacheIndicator)
renderAppDevOverlay(
getOwnerStack,
isRecoverableError,
enableCacheIndicator,
Boolean(process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR)
)
}
})
......@@ -22,7 +22,8 @@ appBootstrap((assetPrefix) => {
renderAppDevOverlay(
getOwnerStack,
isRecoverableError,
enableCacheIndicator
enableCacheIndicator,
Boolean(process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR)
)
}
}
......
......@@ -15,9 +15,9 @@ import {
} from 'next/dist/compiled/next-devtools'
import { ReplaySsrOnlyErrors } from '../../../../next-devtools/userspace/app/errors/replay-ssr-only-errors'
import { AppDevOverlayErrorBoundary } from '../../../../next-devtools/userspace/app/app-dev-overlay-error-boundary'
import { useErrorHandler } from '../../../../next-devtools/userspace/app/errors/use-error-handler'
import { RuntimeErrorHandler } from '../../runtime-error-handler'
import { useWebSocketPing } from './web-socket'
import { useErrorHandler } from '../../../../next-devtools/userspace/app/errors/use-error-handler'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
......@@ -527,6 +527,10 @@ export function processMessage(
return
}
case HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS: {
// Runtime error state is consumed by external HMR observers.
return
}
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE: {
const errorState = getSerializedOverlayState()
const response: McpErrorStateResponse = {
......@@ -604,13 +608,29 @@ export default function HotReload({
webSocket: WebSocket | undefined
staticIndicatorState: StaticIndicatorState | undefined
}) {
useErrorHandler(dispatcher.onUnhandledError, dispatcher.onUnhandledRejection)
useWebSocketPing(webSocket)
// We don't want access of the pathname for the dev tools to trigger a dynamic
// access (as the dev overlay will never be present in production).
const pathname = useUntrackedPathname()
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
// Republish after navigation commits so HMR observers receive the current
// pathname even when the captured errors haven't changed.
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
const { reportCurrentRuntimeErrorState } =
require('../runtime-error-state') as typeof import('../runtime-error-state')
reportCurrentRuntimeErrorState()
}, [pathname])
} else {
// eslint-disable-next-line react-hooks/rules-of-hooks
useErrorHandler(
dispatcher.onUnhandledError,
dispatcher.onUnhandledRejection
)
}
if (process.env.__NEXT_DEV_INDICATOR) {
// this conditional is only for dead-code elimination which
// isn't a runtime conditional only build-time so ignore hooks rule
......
......@@ -39,6 +39,16 @@ export function createWebSocket(
webSocket.send(data)
}
}
let runtimeErrorStateReporter: ReturnType<
typeof import('../runtime-error-state').createRuntimeErrorStateReporter
> | null
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
const { createRuntimeErrorStateReporter } =
require('../runtime-error-state') as typeof import('../runtime-error-state')
runtimeErrorStateReporter = createRuntimeErrorStateReporter(sendMessage)
} else {
runtimeErrorStateReporter = null
}
const processTurbopackMessage = createProcessTurbopackMessage(sendMessage)
......@@ -55,6 +65,7 @@ export function createWebSocket(
function handleOnline() {
logQueue.onSocketReady(newWebSocket)
runtimeErrorStateReporter?.reportCurrent()
reconnections = 0
window.console.log('[HMR] connected')
......
......@@ -401,6 +401,7 @@ function processMessage(message: HmrMessageSentToBrowser) {
dispatcher.onDevToolsConfig(message.data)
break
case HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR:
case HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE:
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK:
case HMR_MESSAGE_SENT_TO_BROWSER.ERRORS_TO_SHOW_IN_BROWSER:
......
import {
getSerializedRuntimeErrorState,
subscribeToRuntimeErrorState,
} from 'next/dist/compiled/next-devtools'
import type { SerializedRuntimeErrorState } from '../../../next-devtools/dev-overlay.browser'
import {
HMR_MESSAGE_SENT_TO_SERVER,
type RuntimeErrorStateUpdate,
} from '../../../server/dev/hot-reloader-types'
let reportCurrentState: (() => void) | null = null
export function reportCurrentRuntimeErrorState(): void {
reportCurrentState?.()
}
export function createRuntimeErrorStateReporter(
sendMessage: (message: string) => void
) {
let lastSerializedState: string | null = null
const report = (errorState: SerializedRuntimeErrorState, force = false) => {
const pathname = window.location.pathname
const serializedState = JSON.stringify({ pathname, errorState })
if (!force && serializedState === lastSerializedState) {
return
}
lastSerializedState = serializedState
const update: RuntimeErrorStateUpdate = {
event: HMR_MESSAGE_SENT_TO_SERVER.RUNTIME_ERRORS,
pathname,
errorState,
}
sendMessage(JSON.stringify(update))
}
subscribeToRuntimeErrorState((state: SerializedRuntimeErrorState) =>
report(state)
)
const reportCurrent = (force: boolean) => {
const state = getSerializedRuntimeErrorState()
if (state) {
report({ errors: state.errors, routerType: state.routerType }, force)
}
}
reportCurrentState = () => reportCurrent(false)
return {
reportCurrent(): void {
reportCurrent(true)
},
}
}
......@@ -123,6 +123,7 @@ export function pageBootstrap(assetPrefix: string) {
case HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG:
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE:
case HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA:
case HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE:
......
......@@ -6,6 +6,7 @@ import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-cs
import { reportGlobalError } from './report-global-error'
import { ErrorBoundaryHandler } from '../components/error-boundary'
import DefaultErrorBoundary from '../components/builtin/global-error'
import type { RuntimeErrorBoundary } from '../../server/dev/hot-reloader-types'
const devToolErrorMod: typeof import('../../next-devtools/userspace/app/errors') =
process.env.NODE_ENV !== 'production'
......@@ -23,6 +24,7 @@ export function onCaughtError(
const errorBoundaryComponent = errorInfo.errorBoundary?.constructor
let isImplicitErrorBoundary
let boundary: RuntimeErrorBoundary | undefined
if (process.env.NODE_ENV !== 'production') {
const { AppDevOverlayErrorBoundary } =
......@@ -30,6 +32,32 @@ export function onCaughtError(
isImplicitErrorBoundary =
errorBoundaryComponent === AppDevOverlayErrorBoundary
if (
process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR &&
errorInfo.errorBoundary
) {
let component: any = errorBoundaryComponent
let kind: 'default-global' | 'custom-global' | 'custom' = 'custom'
if (errorBoundaryComponent === AppDevOverlayErrorBoundary) {
component = (
errorInfo.errorBoundary as InstanceType<
typeof AppDevOverlayErrorBoundary
>
).props.globalError[0]
kind =
component === DefaultErrorBoundary
? 'default-global'
: 'custom-global'
} else if (errorBoundaryComponent === ErrorBoundaryHandler) {
component = (
errorInfo.errorBoundary as InstanceType<typeof ErrorBoundaryHandler>
).props.errorComponent
kind = component === DefaultErrorBoundary ? 'default-global' : 'custom'
}
const name = component?.displayName || component?.name
boundary = { kind, ...(typeof name === 'string' && name ? { name } : {}) }
}
}
isImplicitErrorBoundary =
......@@ -54,7 +82,7 @@ export function onCaughtError(
// We don't consider errors caught unless they're caught by an explicit error
// boundary. The built-in ones are considered implicit.
// This mimics how the same app would behave without Next.js.
return onUncaughtError(thrownValue)
return reportUncaughtError(thrownValue, boundary)
}
// Skip certain custom errors which are not expected to be reported on client
......@@ -89,18 +117,34 @@ export function onCaughtError(
// Log and report the error with location but without modifying the error stack
devToolErrorMod.originConsoleError('%o\n\n%s', thrownValue, errorLocation)
devToolErrorMod.handleClientError(error)
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
devToolErrorMod.handleClientError(error, { fatal: false, boundary })
} else {
devToolErrorMod.handleClientError(error)
}
} else {
devToolErrorMod.originConsoleError(thrownValue)
}
}
export function onUncaughtError(thrownValue: unknown) {
reportUncaughtError(thrownValue)
}
function reportUncaughtError(
thrownValue: unknown,
boundary: RuntimeErrorBoundary | undefined = undefined
) {
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(thrownValue) || isNextRouterError(thrownValue)) return
if (process.env.NODE_ENV !== 'production') {
const error = devToolErrorMod.decorateDevError(thrownValue)
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
const { setRuntimeErrorMetadata } =
require('../../next-devtools/userspace/app/errors/runtime-error-metadata') as typeof import('../../next-devtools/userspace/app/errors/runtime-error-metadata')
setRuntimeErrorMetadata(error, { fatal: true, boundary })
}
// TODO: Add an adendum to the overlay telling people about custom error boundaries.
reportGlobalError(error)
......
import type {
RuntimeErrorMetadata,
RuntimeErrorStateUpdate,
} from '../server/dev/hot-reloader-types'
import { getErrorSource } from '../shared/lib/error-source'
import type { RuntimeErrorEvent } from './dev-overlay/container/runtime-error/render-error'
import {
ACTION_BEFORE_REFRESH,
ACTION_BUILD_ERROR,
......@@ -68,8 +74,8 @@ export interface Dispatcher {
onStaticIndicator(status: 'pending' | 'static' | 'dynamic' | 'disabled'): void
onDevIndicator(devIndicator: DevIndicatorServerState): void
onDevToolsConfig(config: DevToolsConfig): void
onUnhandledError(reason: Error): void
onUnhandledRejection(reason: Error): void
onUnhandledError(reason: Error, metadata?: RuntimeErrorMetadata): void
onUnhandledRejection(reason: Error, metadata?: RuntimeErrorMetadata): void
openErrorOverlay(): void
closeErrorOverlay(): void
toggleErrorOverlay(): void
......@@ -102,13 +108,18 @@ type OverlayStateWithRouter = OverlayState & { routerType: 'pages' | 'app' }
let currentOverlayState: OverlayStateWithRouter | null = null
export function getSerializedOverlayState(): OverlayStateWithRouter | null {
// Serialize error objects properly since Error properties are non-enumerable
// This is used when sending state via HMR/JSON.stringify
if (!currentOverlayState) return null
export type SerializedRuntimeErrorState = RuntimeErrorStateUpdate['errorState']
let runtimeErrorStateListeners: Set<
(state: SerializedRuntimeErrorState) => void
> | null = null
export function getSerializedOverlayState(): OverlayStateWithRouter | null {
if (!currentOverlayState) {
return null
}
return {
...currentOverlayState,
// Error properties are non-enumerable; serialize them explicitly.
errors: currentOverlayState.errors.map((errorEvent: any) => ({
...errorEvent,
error: errorEvent.error
......@@ -122,6 +133,47 @@ export function getSerializedOverlayState(): OverlayStateWithRouter | null {
}
}
function serializeRuntimeErrorState(
state: Pick<OverlayStateWithRouter, 'errors' | 'routerType'>
): SerializedRuntimeErrorState {
return {
routerType: state.routerType,
errors: state.errors.map((event) => {
const { error, isFatal, boundary, ...details } =
event as RuntimeErrorEvent
return {
...details,
fatal: isFatal,
...(boundary ? { boundary } : {}),
error: {
name: error.name,
message: error.message,
stack: error.stack,
source: getErrorSource(error),
},
}
}),
}
}
export function getSerializedRuntimeErrorState(): SerializedRuntimeErrorState | null {
return currentOverlayState
? serializeRuntimeErrorState(currentOverlayState)
: null
}
export function subscribeToRuntimeErrorState(
listener: (state: SerializedRuntimeErrorState) => void
) {
const listeners = (runtimeErrorStateListeners ??= new Set())
listeners.add(listener)
const state = getSerializedRuntimeErrorState()
if (state) {
listener({ errors: state.errors, routerType: state.routerType })
}
return () => listeners.delete(listener)
}
export function getSegmentTrieData(): SegmentTrieData | null {
if (!currentOverlayState) {
return null
......@@ -190,18 +242,32 @@ export const dispatcher: Dispatcher = {
dispatch({ type: ACTION_DEVTOOLS_CONFIG, devToolsConfig })
}
),
onUnhandledError: createQueuable((dispatch: Dispatch, error: Error) => {
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
})
}),
onUnhandledRejection: createQueuable((dispatch: Dispatch, error: Error) => {
dispatch({
type: ACTION_UNHANDLED_REJECTION,
reason: error,
})
}),
onUnhandledError: createQueuable(
(
dispatch: Dispatch,
error: Error,
metadata: RuntimeErrorMetadata | undefined = undefined
) => {
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
...(metadata === undefined ? {} : { metadata }),
})
}
),
onUnhandledRejection: createQueuable(
(
dispatch: Dispatch,
error: Error,
metadata: RuntimeErrorMetadata | undefined = undefined
) => {
dispatch({
type: ACTION_UNHANDLED_REJECTION,
reason: error,
...(metadata === undefined ? {} : { metadata }),
})
}
),
openErrorOverlay: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
}),
......@@ -255,6 +321,7 @@ export const dispatcher: Dispatcher = {
function DevOverlayRoot({
enableCacheIndicator,
enableRuntimeErrorReporting,
getOwnerStack,
getSquashedHydrationErrorDetails,
isRecoverableError,
......@@ -262,6 +329,7 @@ function DevOverlayRoot({
shadowRoot,
}: {
enableCacheIndicator: boolean
enableRuntimeErrorReporting: boolean
getOwnerStack: (error: Error) => string | null | undefined
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
isRecoverableError: (error: Error) => boolean
......@@ -272,7 +340,8 @@ function DevOverlayRoot({
routerType,
getOwnerStack,
isRecoverableError,
enableCacheIndicator
enableCacheIndicator,
enableRuntimeErrorReporting
)
useEffect(() => {
......@@ -307,14 +376,19 @@ function DevOverlayRoot({
}
}, [])
const runtimeErrorPublisher = enableRuntimeErrorReporting ? (
<RuntimeErrorStatePublisher state={state} />
) : null
if (process.env.__NEXT_DISABLE_DEV_OVERLAY_UX) {
return null
return runtimeErrorPublisher
}
const { DevOverlay, FontStyles } = loadDevOverlayUX()
return (
<>
{runtimeErrorPublisher}
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlayContext
......@@ -330,6 +404,23 @@ function DevOverlayRoot({
</>
)
}
function RuntimeErrorStatePublisher({
state,
}: {
state: OverlayStateWithRouter
}) {
const { errors, routerType } = state
useEffect(() => {
if (runtimeErrorStateListeners) {
const snapshot = serializeRuntimeErrorState({ errors, routerType })
for (const listener of runtimeErrorStateListeners) {
listener(snapshot)
}
}
}, [errors, routerType])
return null
}
export const DevOverlayContext = createContext<{
shadowRoot: ShadowRoot
state: OverlayState & {
......@@ -351,7 +442,8 @@ function getSquashedHydrationErrorDetailsApp() {
export function renderAppDevOverlay(
getOwnerStack: (error: Error) => string | null | undefined,
isRecoverableError: (error: Error) => boolean,
enableCacheIndicator: boolean
enableCacheIndicator: boolean,
enableRuntimeErrorReporting: boolean
): void {
if (isPagesMounted) {
// Switching between App and Pages Router is always a hard navigation
......@@ -397,6 +489,7 @@ export function renderAppDevOverlay(
root.render(
<DevOverlayRoot
enableCacheIndicator={enableCacheIndicator}
enableRuntimeErrorReporting={enableRuntimeErrorReporting}
getOwnerStack={getOwnerStack}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetailsApp}
isRecoverableError={isRecoverableError}
......@@ -467,6 +560,7 @@ export function renderPagesDevOverlay(
<DevOverlayRoot
// Pages Router does not support Cache Components
enableCacheIndicator={false}
enableRuntimeErrorReporting={false}
getOwnerStack={getOwnerStack}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
isRecoverableError={isRecoverableError}
......
import type { RuntimeErrorBoundary } from '../../../../server/dev/hot-reloader-types'
import type { OverlayState } from '../../shared'
import type { StackFrame } from '../../../shared/stack-frame'
......@@ -15,6 +16,12 @@ export type SupportedErrorEvent = {
type: 'runtime' | 'recoverable' | 'console'
}
export type RuntimeErrorEvent = SupportedErrorEvent & {
/** A React root failure or a Next.js unrecoverable rendering path. */
isFatal: boolean
boundary: RuntimeErrorBoundary | undefined
}
type Props = {
children: (params: {
runtimeErrors: ReadyRuntimeError[]
......@@ -41,7 +48,12 @@ const RenderRuntimeError = ({ children, state, isAppDir }: Props) => {
const { errors } = state
const [lookups, setLookups] = useState<{
[eventId: string]: ReadyRuntimeError
[eventId: string]:
| ReadyRuntimeError
| {
event: RuntimeErrorEvent
resolved: ReadyRuntimeError
}
}>({})
const [runtimeErrors, nextError] = useMemo<
......@@ -55,11 +67,30 @@ const RenderRuntimeError = ({ children, state, isAppDir }: Props) => {
const e = errors[idx]
const { id } = e
if (id in lookups) {
ready.push(lookups[id])
const lookup = lookups[id]
if (!('event' in lookup)) {
ready.push(lookup)
continue
}
const resolved = lookup.resolved
if (lookup.event !== e) {
// Dedupe promotion preserves the ID while replacing the event.
// Keep the overlay mounted while resolving the replacement frames.
if (next === null) {
next = e
}
ready.push(
resolved.type === e.type ? resolved : { ...resolved, type: e.type }
)
continue
}
ready.push(resolved)
continue
}
next = e
if (next === null) {
next = e
}
break
}
......@@ -73,7 +104,13 @@ const RenderRuntimeError = ({ children, state, isAppDir }: Props) => {
const resolved = getErrorByType(nextError, isAppDir)
// eslint-disable-next-line react-hooks/set-state-in-effect -- TODO: fetch-while-rendering
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
setLookups((m) => ({
...m,
[resolved.id]:
'isFatal' in nextError
? { event: nextError as RuntimeErrorEvent, resolved }
: resolved,
}))
}, [nextError, isAppDir])
const totalErrorCount = errors.length
......
......@@ -7,10 +7,12 @@ import {
} from '../../server/app-render/blocking-route-messages'
import {
getInstantErrorRoute,
mergeErrorEvent,
routeTemplateMatchesPath,
updateRequestInsights,
} from './shared'
import type { RequestInsight } from '../shared/request-insights'
import type { RuntimeErrorEvent } from './container/runtime-error/render-error'
const STATIC_ROUTE = '/example'
const DYNAMIC_ROUTE_TEMPLATE = '/posts/[slug]'
......@@ -33,6 +35,95 @@ function createRequestInsight(
}
}
function createErrorEvent(
id: number,
error: Error,
isFatal: boolean = false
): RuntimeErrorEvent {
return {
id,
error,
frames: [],
type: isFatal ? 'runtime' : 'console',
isFatal,
boundary: undefined,
}
}
const noOwnerStack = () => null
describe('mergeErrorEvent', () => {
it('keeps errors with different messages when their stacks match', () => {
const firstError = new Error('first')
const secondError = new Error('second')
firstError.stack = secondError.stack = 'shared stack'
const first = createErrorEvent(0, firstError)
const second = createErrorEvent(1, secondError)
expect(mergeErrorEvent([first], second, noOwnerStack)).toEqual([
first,
second,
])
})
it('dedupes stacks that only differ below the StrictMode frame', () => {
const firstError = new Error('repeated')
const secondError = new Error('repeated')
firstError.stack =
'Error: repeated\n at Component\n at Object.react_stack_bottom_frame (react.js:1:1)\n at first pass'
secondError.stack =
'Error: repeated\n at Component\n at Object.react_stack_bottom_frame (react.js:1:1)\n at second pass'
const first = createErrorEvent(0, firstError)
const events = [first]
expect(
mergeErrorEvent(events, createErrorEvent(1, secondError), noOwnerStack)
).toBe(events)
})
it('preserves occurrences caught by different boundaries', () => {
const error = new Error('same error')
const first = {
...createErrorEvent(0, error),
boundary: { kind: 'custom' as const, name: 'Boundary' },
}
const second = {
...createErrorEvent(1, error, true),
boundary: { kind: 'default-global' as const },
}
expect(mergeErrorEvent([first], second, noOwnerStack)).toEqual([
first,
second,
])
})
it('promotes an uncaught console report to a fatal boundary occurrence', () => {
const error = new Error('reused')
const first = createErrorEvent(4, error)
const fatal = {
...createErrorEvent(5, error, true),
boundary: { kind: 'default-global' as const },
}
const promoted = mergeErrorEvent([first], fatal, noOwnerStack)
expect(promoted).toEqual([{ ...fatal, id: first.id }])
expect(mergeErrorEvent(promoted, { ...fatal, id: 6 }, noOwnerStack)).toBe(
promoted
)
})
it('promotes a fatal duplicate while preserving its id', () => {
const firstError = new Error('repeated')
const fatalError = new Error('repeated')
firstError.stack = fatalError.stack = 'shared stack'
const first = createErrorEvent(4, firstError)
const fatal = createErrorEvent(5, fatalError, true)
expect(mergeErrorEvent([first], fatal, noOwnerStack)).toEqual([
{ ...fatal, id: first.id },
])
})
})
describe('updateRequestInsights', () => {
it('updates request kinds independently when request IDs match', () => {
const request = createRequestInsight('request', 25)
......
import type { RuntimeErrorMetadata } from '../../server/dev/hot-reloader-types'
import { useReducer } from 'react'
import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { VersionInfo } from '../../server/dev/parse-version-info'
import type { SupportedErrorEvent } from './container/runtime-error/render-error'
import type {
SupportedErrorEvent,
RuntimeErrorEvent,
} from './container/runtime-error/render-error'
import type { DebugInfo } from '../shared/types'
import type { DevIndicatorServerState } from '../../server/dev/dev-indicator-server-state'
import { parseStack } from '../../server/lib/parse-stack'
......@@ -178,10 +182,12 @@ interface FastRefreshAction {
interface UnhandledErrorAction {
type: typeof ACTION_UNHANDLED_ERROR
reason: Error
metadata?: RuntimeErrorMetadata
}
interface UnhandledRejectionAction {
type: typeof ACTION_UNHANDLED_REJECTION
reason: Error
metadata?: RuntimeErrorMetadata
}
interface DebugInfoAction {
......@@ -412,16 +418,62 @@ function getInitialState(
}
}
export function mergeErrorEvent(
events: readonly RuntimeErrorEvent[],
pendingEvent: RuntimeErrorEvent,
getOwnerStack: (error: Error) => string | null | undefined
): readonly RuntimeErrorEvent[] {
const matchesError = (event: RuntimeErrorEvent) =>
// SpiderMonkey and JavaScriptCore don't include the error message in the stack.
// We don't want to dedupe errors with different messages for which we don't have a good stack.
'' + event.error === '' + pendingEvent.error &&
(event.error.stack === pendingEvent.error.stack ||
// TODO: Let ReactDevTools control deduping instead?
getStackIgnoringStrictMode(event.error.stack) ===
getStackIgnoringStrictMode(pendingEvent.error.stack)) &&
getOwnerStack(event.error) === getOwnerStack(pendingEvent.error)
let duplicateIndex = events.findIndex(
(event) =>
matchesError(event) &&
event.boundary?.kind === pendingEvent.boundary?.kind &&
event.boundary?.name === pendingEvent.boundary?.name
)
if (duplicateIndex === -1 && pendingEvent.isFatal) {
// A previous console report may become a fatal render error. Preserve its
// ID while attaching the catcher, without merging different caught paths.
duplicateIndex = events.findIndex(
(event) =>
matchesError(event) && !event.isFatal && event.boundary === undefined
)
}
if (duplicateIndex === -1) {
return [...events, pendingEvent]
}
const duplicate = events[duplicateIndex]
if (pendingEvent.isFatal && !duplicate.isFatal) {
return events.map((event, index) =>
index === duplicateIndex ? { ...pendingEvent, id: duplicate.id } : event
)
}
return events
}
export function useErrorOverlayReducer(
routerType: 'pages' | 'app',
getOwnerStack: (error: Error) => string | null | undefined,
isRecoverableError: (error: Error) => boolean,
enableCacheIndicator: boolean
enableCacheIndicator: boolean,
enableRuntimeErrorReporting: boolean = false
) {
function pushErrorFilterDuplicates(
events: readonly SupportedErrorEvent[],
id: number,
error: Error
error: Error,
metadata: RuntimeErrorMetadata | undefined
): readonly SupportedErrorEvent[] {
const ownerStack = getOwnerStack(error)
const frames = parseStack((error.stack || '') + (ownerStack || ''))
......@@ -429,31 +481,39 @@ export function useErrorOverlayReducer(
id,
error,
frames,
type: isRecoverableError(error)
? 'recoverable'
: isConsoleError(error)
? 'console'
: 'runtime',
type:
enableRuntimeErrorReporting && metadata !== undefined
? 'runtime'
: isRecoverableError(error)
? 'recoverable'
: isConsoleError(error)
? 'console'
: 'runtime',
}
if (enableRuntimeErrorReporting) {
return mergeErrorEvent(
events as readonly RuntimeErrorEvent[],
{
...pendingEvent,
isFatal: metadata?.fatal ?? false,
boundary: metadata?.boundary,
},
getOwnerStack
)
}
const pendingEvents = events.filter((event) => {
// Filter out duplicate errors
return (
// SpiderMonkey and JavaScriptCore don't include the error message in the stack.
// We don't want to dedupe errors with different messages for which we don't have a good stack
'' + event.error !== '' + pendingEvent.error ||
(event.error.stack !== pendingEvent.error.stack &&
// TODO: Let ReactDevTools control deduping instead?
getStackIgnoringStrictMode(event.error.stack) !==
getStackIgnoringStrictMode(pendingEvent.error.stack)) ||
getOwnerStack(event.error) !== getOwnerStack(pendingEvent.error)
)
})
// If there's nothing filtered out, the event is a brand new error
if (pendingEvents.length === events.length) {
pendingEvents.push(pendingEvent)
return pendingEvents
}
// Otherwise remain the same events
return events
}
......@@ -505,7 +565,8 @@ export function useErrorOverlayReducer(
errors: pushErrorFilterDuplicates(
state.errors,
state.nextId,
action.reason
action.reason,
action.metadata
),
}
}
......@@ -518,7 +579,8 @@ export function useErrorOverlayReducer(
errors: pushErrorFilterDuplicates(
state.errors,
state.nextId,
action.reason
action.reason,
action.metadata
),
},
}
......
import type { RuntimeErrorMetadata } from '../../../../server/dev/hot-reloader-types'
const pendingMetadata = new WeakMap<Error, RuntimeErrorMetadata>()
// Used only for the synchronous reportError -> window.error handoff.
export function setRuntimeErrorMetadata(
error: Error,
metadata: RuntimeErrorMetadata
) {
pendingMetadata.set(error, metadata)
}
export function takeRuntimeErrorMetadata(error: Error) {
const metadata = pendingMetadata.get(error)
pendingMetadata.delete(error)
return metadata
}
import { useEffect } from 'react'
import type { RuntimeErrorMetadata } from '../../../../server/dev/hot-reloader-types'
import { isNextRouterError } from '../../../../client/components/is-next-router-error'
import {
formatConsoleArgs,
......@@ -35,24 +36,44 @@ export function handleConsoleError(
}
setOwnerStackIfAvailable(error)
errorQueue.push(error)
for (const handler of errorHandlers) {
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(() => {
handler(error)
})
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
const { dispatcher } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
queueMicroTask(() => dispatcher.onUnhandledError(error))
} else {
errorQueue.push(error)
for (const handler of errorHandlers) {
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(() => {
handler(error)
})
}
}
}
export function handleClientError(error: Error) {
errorQueue.push(error)
for (const handler of errorHandlers) {
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(() => {
handler(error)
})
export function handleClientError(
error: Error,
metadata: RuntimeErrorMetadata | undefined = undefined
) {
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
const { dispatcher } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
const { takeRuntimeErrorMetadata } =
require('./runtime-error-metadata') as typeof import('./runtime-error-metadata')
const occurrence = metadata ?? takeRuntimeErrorMetadata(error)
// The overlay queues events until its own root mounts. Do not depend on
// HotReload committing: an initial application failure can prevent that.
queueMicroTask(() => dispatcher.onUnhandledError(error, occurrence))
} else {
errorQueue.push(error)
for (const handler of errorHandlers) {
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(() => {
handler(error)
})
}
}
}
......@@ -95,7 +116,19 @@ function onUnhandledError(event: WindowEventMap['error']): void | boolean {
if (thrownValue) {
const error = coerceError(thrownValue)
setOwnerStackIfAvailable(error)
handleClientError(error)
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
const { takeRuntimeErrorMetadata } =
require('./runtime-error-metadata') as typeof import('./runtime-error-metadata')
const { isRecoverableError } =
require('../../../../client/react-client-callbacks/on-recoverable-error') as typeof import('../../../../client/react-client-callbacks/on-recoverable-error')
handleClientError(
error,
takeRuntimeErrorMetadata(error) ??
(isRecoverableError(error) ? undefined : { fatal: false })
)
} else {
handleClientError(error)
}
forwardUnhandledError(error)
}
}
......@@ -110,9 +143,15 @@ function onUnhandledRejection(ev: WindowEventMap['unhandledrejection']): void {
const error = coerceError(reason)
setOwnerStackIfAvailable(error)
rejectionQueue.push(error)
for (const handler of rejectionHandlers) {
handler(error)
if (process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR) {
const { dispatcher } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
dispatcher.onUnhandledRejection(error, { fatal: false })
} else {
rejectionQueue.push(error)
for (const handler of rejectionHandlers) {
handler(error)
}
}
logUnhandledRejection(reason)
......
......@@ -314,6 +314,7 @@ export const experimentalSchema = {
proxyTimeout: z.number().gte(0).optional(),
rootParams: z.boolean().optional(),
mcpServer: z.boolean().optional(),
exposeRuntimeErrorsToHMR: z.boolean().optional(),
removeUncaughtErrorAndRejectionListeners: z.boolean().optional(),
validateRSCRequestHeaders: z.boolean().optional(),
scrollRestoration: z.boolean().optional(),
......
......@@ -1515,6 +1515,9 @@ export interface ExperimentalConfig {
*/
mcpServer?: boolean
/** Report runtime errors and their catching boundary over the development HMR socket. */
exposeRuntimeErrorsToHMR?: boolean
/**
* Acquires a lockfile at `<distDir>/lock` when starting `next dev` or `next
* build`. Failing to acquire the lock causes the process to exit with an
......@@ -2393,6 +2396,7 @@ export const defaultConfig = Object.freeze({
proxyClientMaxBodySize: 10_485_760, // 10MB
hideLogsAfterAbort: false,
mcpServer: true,
exposeRuntimeErrorsToHMR: false,
turbopackFileSystemCacheForDev: true,
turbopackFileSystemCacheForBuild: true,
turbopackStaleOutputMaxAge: 7 * 24 * 60 * 60 * 1000, // One week
......
......@@ -26,7 +26,10 @@ import type ws from 'next/dist/compiled/ws'
import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared'
import { isMiddlewareFilename } from '../../build/utils'
import type { VersionInfo } from './parse-version-info'
import type { HmrMessageSentToBrowser } from './hot-reloader-types'
import type {
HmrMessageSentToBrowser,
RuntimeErrorStateMessage,
} from './hot-reloader-types'
import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'
import { devIndicatorServerState } from './dev-indicator-server-state'
import { createBinaryHmrMessageData } from './messages'
......@@ -77,6 +80,11 @@ function getStatsForSyncEvent(
export class WebpackHotMiddleware {
private clientsWithoutHtmlRequestId = new Set<ws>()
private clientsByHtmlRequestId: Map<string, ws> = new Map()
private runtimeErrorStates =
this.config.experimental.exposeRuntimeErrorsToHMR ||
Boolean(process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR)
? new Map<string, RuntimeErrorStateMessage>()
: null
private closed = false
private clientLatestStats: { ts: number; stats: webpack.Stats } | null = null
private middlewareLatestStats: { ts: number; stats: webpack.Stats } | null =
......@@ -184,6 +192,12 @@ export class WebpackHotMiddleware {
}
})
if (this.runtimeErrorStates) {
for (const message of this.runtimeErrorStates.values()) {
this.publishToClient(client, message)
}
}
const syncStats = getStatsForSyncEvent(
this.clientLatestStats,
this.serverLatestStats
......@@ -258,6 +272,17 @@ export class WebpackHotMiddleware {
return
}
if (
this.runtimeErrorStates &&
message.type === HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS
) {
if (message.errors.length === 0) {
this.runtimeErrorStates.delete(message.clientId)
} else {
this.runtimeErrorStates.set(message.clientId, message)
}
}
for (const wsClient of [
...this.clientsWithoutHtmlRequestId,
...this.clientsByHtmlRequestId.values(),
......@@ -307,6 +332,7 @@ export class WebpackHotMiddleware {
this.clientsWithoutHtmlRequestId.clear()
this.clientsByHtmlRequestId.clear()
this.runtimeErrorStates?.clear()
}
deleteClient = (client: ws, htmlRequestId: string | null) => {
......
......@@ -12,12 +12,16 @@ import { store as consoleStore } from '../../build/output/store'
import type {
CompilationError,
HmrMessageSentToBrowser,
RuntimeErrorStateMessage,
NextJsHotReloaderInterface,
ReloadPageMessage,
SyncMessage,
TurbopackConnectedMessage,
} from './hot-reloader-types'
import { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
} from './hot-reloader-types'
import { recursiveDeleteSyncWithAsyncRetries } from '../../lib/recursive-delete'
import type {
Update as TurbopackUpdate,
......@@ -140,6 +144,7 @@ import { resolvePathToRoute } from '../mcp/tools/utils/resolve-path-to-route'
import { handleErrorStateResponse } from '../mcp/tools/get-errors'
import { handlePageMetadataResponse } from '../mcp/tools/get-page-metadata'
import { setStackFrameResolver } from '../mcp/tools/utils/format-errors'
import { createRuntimeErrorStateHandler } from './runtime-error-state'
import { recordMcpTelemetry } from '../mcp/mcp-telemetry-tracker'
import { getFileLogger } from './browser-logs/file-logger'
import type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'
......@@ -859,6 +864,11 @@ export async function createHotReloaderTurbopack(
const clientsWithoutHtmlRequestId = new Set<ws>()
const clientsByHtmlRequestId = new Map<string, ws>()
const runtimeErrorStates =
nextConfig.experimental.exposeRuntimeErrorsToHMR ||
Boolean(process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR)
? new Map<string, RuntimeErrorStateMessage>()
: null
const cacheStatusesByHtmlRequestId = new Map<string, ServerCacheStatus>()
const clientStates = new WeakMap<ws, ClientState>()
......@@ -1536,7 +1546,23 @@ export async function createHotReloaderTurbopack(
subscriptions,
})
if (runtimeErrorStates) {
for (const message of runtimeErrorStates.values()) {
sendToClient(client, message)
}
}
const runtimeErrorStateHandler =
nextConfig.experimental.exposeRuntimeErrorsToHMR ||
Boolean(process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR)
? createRuntimeErrorStateHandler((message) =>
hotReloader.send({ ...message, htmlRequestId })
)
: undefined
client.on('close', () => {
runtimeErrorStateHandler?.dispose()
// Remove active subscriptions
for (const subscription of subscriptions.values()) {
subscription.return?.()
......@@ -1627,6 +1653,11 @@ export async function createHotReloaderTurbopack(
break
}
case HMR_MESSAGE_SENT_TO_SERVER.RUNTIME_ERRORS: {
void runtimeErrorStateHandler?.handle(parsedData).catch(() => {})
break
}
case 'mcp-error-state-response': {
handleErrorStateResponse(
parsedData.requestId,
......@@ -1731,6 +1762,17 @@ export async function createHotReloaderTurbopack(
},
send(action) {
if (
runtimeErrorStates &&
action.type === HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS
) {
if (action.errors.length === 0) {
runtimeErrorStates.delete(action.clientId)
} else {
runtimeErrorStates.set(action.clientId, action)
}
}
const payload = JSON.stringify(action)
for (const client of [
......@@ -2114,6 +2156,7 @@ export async function createHotReloaderTurbopack(
}
clientsWithoutHtmlRequestId.clear()
clientsByHtmlRequestId.clear()
runtimeErrorStates?.clear()
},
}
......
......@@ -42,6 +42,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER {
DEV_INDICATOR = 'devIndicator',
DEVTOOLS_CONFIG = 'devtoolsConfig',
REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState',
RUNTIME_ERRORS = 'runtimeErrors',
REQUEST_PAGE_METADATA = 'requestPageMetadata',
REQUEST_INSIGHTS_UPDATE = 'requestInsightsUpdate',
......@@ -53,6 +54,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER {
export const enum HMR_MESSAGE_SENT_TO_SERVER {
// JSON messages:
MCP_ERROR_STATE_RESPONSE = 'mcp-error-state-response',
RUNTIME_ERRORS = 'runtimeErrors',
MCP_PAGE_METADATA_RESPONSE = 'mcp-page-metadata-response',
PING = 'ping',
}
......@@ -185,6 +187,68 @@ export interface RequestCurrentErrorStateMessage {
requestId: string
}
export type RuntimeErrorBoundary = {
kind: 'default-global' | 'custom-global' | 'custom'
name?: string
}
export interface RuntimeErrorMetadata {
fatal: boolean
boundary?: RuntimeErrorBoundary
}
export interface FormattedRuntimeError {
type: string
errorName: string
message: string
/** A React root failure or a Next.js unrecoverable rendering path. */
fatal: boolean
boundary?: RuntimeErrorBoundary
stack: Array<{
file: string
methodName: string
line: number | null
column: number | null
}>
}
export interface RuntimeErrorStateError {
id: number
error: {
name?: string
message?: string
stack?: string
source: 'server' | 'edge-server' | null
} | null
frames: readonly {
file: string | null
methodName: string
line1: number | null
column1: number | null
}[]
type: 'runtime' | 'recoverable' | 'console'
fatal: boolean
boundary?: RuntimeErrorBoundary
}
export interface RuntimeErrorStateUpdate {
event: HMR_MESSAGE_SENT_TO_SERVER.RUNTIME_ERRORS
pathname: string
errorState: {
errors: readonly RuntimeErrorStateError[]
routerType: 'app' | 'pages'
}
}
export interface RuntimeErrorStateMessage {
type: HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS
clientId: string
/** The producer document's existing HMR request ID, when available. */
htmlRequestId?: string | null
pathname: string
errors: FormattedRuntimeError[]
}
export interface RequestPageMetadataMessage {
type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_PAGE_METADATA
requestId: string
......@@ -221,6 +285,7 @@ export type HmrMessageSentToBrowser =
| ErrorsToShowInBrowserMessage
| ReactDebugChunkMessage
| RequestCurrentErrorStateMessage
| RuntimeErrorStateMessage
| RequestPageMetadataMessage
| CacheIndicatorMessage
| RequestInsightsUpdateMessage
......
......@@ -466,7 +466,11 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
}
this.webpackHotMiddleware.onHMR(client, htmlRequestId)
this.onDemandEntries?.onHMR(client, () => this.hmrServerError)
this.onDemandEntries?.onHMR(
client,
() => this.hmrServerError,
htmlRequestId
)
const enableCacheComponents = this.config.cacheComponents
// Clients with a request ID are inferred App Router clients. If Cache
......
......@@ -48,6 +48,7 @@ import { PAGE_TYPES } from '../../lib/page-types'
import { getNextFlightSegmentPath } from '../../client/flight-data-helpers'
import { handleErrorStateResponse } from '../mcp/tools/get-errors'
import { handlePageMetadataResponse } from '../mcp/tools/get-page-metadata'
import { createRuntimeErrorStateHandler } from './runtime-error-state'
const debug = createDebug('next:on-demand-entry-handler')
......@@ -1078,11 +1079,23 @@ export function onDemandEntryHandler({
})
})
},
onHMR(client: ws, getHmrServerError: () => Error | null) {
onHMR(
client: ws,
getHmrServerError: () => Error | null,
htmlRequestId: string | null
) {
let bufferedHmrServerError: Error | null = null
const runtimeErrorStateHandler =
nextConfig.experimental.exposeRuntimeErrorsToHMR ||
Boolean(process.env.__NEXT_EXPOSE_RUNTIME_ERRORS_TO_HMR)
? createRuntimeErrorStateHandler((message) =>
hotReloader.send({ ...message, htmlRequestId })
)
: undefined
client.addEventListener('close', () => {
bufferedHmrServerError = null
runtimeErrorStateHandler?.dispose()
})
client.addEventListener('message', ({ data }) => {
try {
......@@ -1107,6 +1120,10 @@ export function onDemandEntryHandler({
} else {
handlePing(parsedData.page)
}
} else if (
parsedData.event === HMR_MESSAGE_SENT_TO_SERVER.RUNTIME_ERRORS
) {
void runtimeErrorStateHandler?.handle(parsedData).catch(() => {})
} else if (
parsedData.event ===
HMR_MESSAGE_SENT_TO_SERVER.MCP_ERROR_STATE_RESPONSE
......
import { randomUUID } from 'crypto'
import type {
FormattedRuntimeError,
RuntimeErrorStateError,
RuntimeErrorStateUpdate,
} from './hot-reloader-types'
import {
HMR_MESSAGE_SENT_TO_BROWSER,
HMR_MESSAGE_SENT_TO_SERVER,
type RuntimeErrorStateMessage,
} from './hot-reloader-types'
import { resolveStackFrames } from '../mcp/tools/utils/format-errors'
type StackFrameForFormatting = {
file: string | null
methodName: string
line1: number | null
column1: number | null
}
type RuntimeErrorStateFormatter = (
errors: readonly RuntimeErrorStateError[],
isAppDirectory: boolean
) => Promise<FormattedRuntimeError[]>
const formatStackFrameToObject = (
frame: StackFrameForFormatting
): FormattedRuntimeError['stack'][number] => {
return {
file: frame.file || '<unknown>',
methodName: frame.methodName || '<anonymous>',
line: frame.line1,
column: frame.column1,
}
}
const resolveErrorFrames = async (
frames: readonly StackFrameForFormatting[],
context: {
isServer: boolean
isEdgeServer: boolean
isAppDirectory: boolean
}
): Promise<FormattedRuntimeError['stack']> => {
try {
const resolvedFrames = await resolveStackFrames({
frames: frames.map((frame) => ({
file: frame.file || null,
methodName: frame.methodName || '<anonymous>',
arguments: [],
line1: frame.line1 || null,
column1: frame.column1 || null,
})),
isServer: context.isServer,
isEdgeServer: context.isEdgeServer,
isAppDirectory: context.isAppDirectory,
})
return resolvedFrames.flatMap((resolvedFrame, index) => {
if (
resolvedFrame.status === 'fulfilled' &&
resolvedFrame.value.originalStackFrame?.ignored
) {
return []
}
return [
resolvedFrame.status === 'fulfilled' &&
resolvedFrame.value.originalStackFrame
? formatStackFrameToObject(resolvedFrame.value.originalStackFrame)
: formatStackFrameToObject(frames[index]),
]
})
} catch {
return frames.map(formatStackFrameToObject)
}
}
export async function formatRuntimeErrors(
errors: readonly RuntimeErrorStateError[],
isAppDirectory: boolean
): Promise<FormattedRuntimeError[]> {
const formattedErrors: FormattedRuntimeError[] = []
for (const error of errors) {
const errorName = error.error?.name || 'Error'
const message = error.error?.message || 'Unknown error'
let stack: FormattedRuntimeError['stack'] = []
if (error.frames?.length) {
const errorSource = error.error?.source
stack = await resolveErrorFrames(error.frames, {
isServer: errorSource === 'server',
isEdgeServer: errorSource === 'edge-server',
isAppDirectory,
})
}
formattedErrors.push({
type: error.type,
errorName,
message,
fatal: error.fatal,
...(error.boundary ? { boundary: error.boundary } : {}),
stack,
})
}
return formattedErrors
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
function isNullableString(value: unknown): value is string | null {
return value === null || typeof value === 'string'
}
function isNullableNumber(value: unknown): value is number | null {
return value === null || (typeof value === 'number' && Number.isFinite(value))
}
function isRuntimeErrorStateError(
value: unknown
): value is RuntimeErrorStateError {
if (
!isRecord(value) ||
typeof value.id !== 'number' ||
!Number.isFinite(value.id) ||
(value.type !== 'runtime' &&
value.type !== 'recoverable' &&
value.type !== 'console') ||
typeof value.fatal !== 'boolean' ||
(value.boundary !== undefined &&
(!isRecord(value.boundary) ||
!['default-global', 'custom-global', 'custom'].includes(
value.boundary.kind as string
) ||
(value.boundary.name !== undefined &&
typeof value.boundary.name !== 'string'))) ||
!Array.isArray(value.frames)
) {
return false
}
if (value.error !== null) {
if (!isRecord(value.error)) {
return false
}
if (
(value.error.name !== undefined &&
typeof value.error.name !== 'string') ||
(value.error.message !== undefined &&
typeof value.error.message !== 'string') ||
(value.error.stack !== undefined &&
typeof value.error.stack !== 'string') ||
(value.error.source !== null &&
value.error.source !== 'server' &&
value.error.source !== 'edge-server')
) {
return false
}
}
return value.frames.every(
(frame) =>
isRecord(frame) &&
isNullableString(frame.file) &&
typeof frame.methodName === 'string' &&
isNullableNumber(frame.line1) &&
isNullableNumber(frame.column1)
)
}
export function isRuntimeErrorStateUpdate(
value: unknown
): value is RuntimeErrorStateUpdate {
if (
!isRecord(value) ||
value.event !== HMR_MESSAGE_SENT_TO_SERVER.RUNTIME_ERRORS ||
typeof value.pathname !== 'string' ||
!value.pathname.startsWith('/') ||
value.pathname.includes('?') ||
value.pathname.includes('#') ||
!isRecord(value.errorState) ||
!Array.isArray(value.errorState.errors) ||
value.errorState.routerType !== 'app'
) {
return false
}
return value.errorState.errors.every(isRuntimeErrorStateError)
}
export function createRuntimeErrorStateHandler(
sendHmrMessage: (message: RuntimeErrorStateMessage) => void,
format: RuntimeErrorStateFormatter = formatRuntimeErrors,
clientId: string = randomUUID()
) {
let generation = 0
let disposed = false
let lastPublishedMessage: RuntimeErrorStateMessage | null = null
const formattedErrorCache = new Map<string, Promise<FormattedRuntimeError>>()
async function formatWithCache(
errors: readonly RuntimeErrorStateError[],
isAppDirectory: boolean
): Promise<FormattedRuntimeError[]> {
const keys = errors.map(
(error) => `${isAppDirectory ? 'app' : 'pages'}:${JSON.stringify(error)}`
)
const activeKeys = new Set(keys)
const pending: Array<Promise<FormattedRuntimeError> | undefined> = []
const missing: Array<{
error: RuntimeErrorStateError
key: string
outputIndex: number
}> = []
for (let index = 0; index < errors.length; index++) {
const key = keys[index]
const cached = formattedErrorCache.get(key)
if (cached) {
pending[index] = cached
} else {
missing.push({ error: errors[index], key, outputIndex: index })
}
}
if (missing.length > 0) {
const batch = format(
missing.map(({ error }) => error),
isAppDirectory
)
for (let index = 0; index < missing.length; index++) {
const { key, outputIndex } = missing[index]
const formatted = batch
.then((result) => {
const error = result[index]
if (!error) {
throw new Error('Runtime error formatter returned no result')
}
return error
})
.catch((error) => {
if (formattedErrorCache.get(key) === formatted) {
formattedErrorCache.delete(key)
}
throw error
})
formattedErrorCache.set(key, formatted)
pending[outputIndex] = formatted
}
}
for (const key of formattedErrorCache.keys()) {
if (!activeKeys.has(key)) {
formattedErrorCache.delete(key)
}
}
return Promise.all(
pending.map((formatted) => {
if (!formatted) {
throw new Error('Runtime error formatter cache is incomplete')
}
return formatted
})
)
}
return {
async handle(update: unknown): Promise<void> {
if (disposed || !isRuntimeErrorStateUpdate(update)) {
return
}
const currentGeneration = ++generation
const errors = await formatWithCache(
update.errorState.errors,
update.errorState.routerType === 'app'
)
if (disposed || currentGeneration !== generation) {
return
}
const message: RuntimeErrorStateMessage = {
type: HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS,
clientId,
pathname: update.pathname,
errors,
}
sendHmrMessage(message)
lastPublishedMessage = message
},
dispose(): void {
if (disposed) {
return
}
const clearMessage: RuntimeErrorStateMessage | null =
lastPublishedMessage && lastPublishedMessage.errors.length > 0
? { ...lastPublishedMessage, errors: [] }
: null
disposed = true
generation++
formattedErrorCache.clear()
lastPublishedMessage = null
if (clearMessage) {
sendHmrMessage(clearMessage)
}
},
}
}
......@@ -24,7 +24,7 @@ export function setStackFrameResolver(fn: StackFrameResolver) {
stackFrameResolver = fn
}
async function resolveStackFrames(
export async function resolveStackFrames(
request: OriginalStackFramesRequest
): Promise<OriginalStackFramesResponse> {
if (!stackFrameResolver) {
......
'use client'
import { catchError } from 'next/error'
import { useState } from 'react'
const CustomBoundary = catchError(function CustomFallback() {
return <p id="fallback">Catch fallback</p>
})
function Broken() {
const [failed, setFailed] = useState(false)
if (failed) {
throw new Error('catch failed')
}
return (
<button id="throw" onClick={() => setFailed(true)}>
Throw
</button>
)
}
export default function Page() {
return (
<CustomBoundary>
<Broken />
</CustomBoundary>
)
}
'use client'
import { Component, useState, type ReactNode } from 'react'
class CustomBoundary extends Component<
{ children: ReactNode },
{ failed: boolean }
> {
state = { failed: false }
static getDerivedStateFromError() {
return { failed: true }
}
render() {
return this.state.failed ? (
<p id="fallback">Class fallback</p>
) : (
this.props.children
)
}
}
function Broken() {
const [failed, setFailed] = useState(false)
if (failed) {
throw new Error('class failed')
}
return (
<button id="throw" onClick={() => setFailed(true)}>
Throw
</button>
)
}
export default function Page() {
return (
<CustomBoundary>
<Broken />
</CustomBoundary>
)
}
'use client'
export default function Page() {
return (
<>
<p id="content">Usable preview</p>
<button
id="event"
onClick={() => {
throw new Error('event failed')
}}
>
Event
</button>
<button
id="rejection"
onClick={() => {
void Promise.reject(new Error('rejection failed'))
}}
>
Rejection
</button>
</>
)
}
'use client'
export default function CustomGlobalError() {
return <html><body><p id="fallback">Custom global fallback</p></body></html>
}
'use client'
export default function Page() {
return (
<p id="content">
{typeof window === 'undefined' ? 'server text' : 'client text'}
</p>
)
}
export default function Page() {
throw new Error('initial render failed')
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p id="content">Navigation complete</p>
}
'use client'
import Link from 'next/link'
export default function Page() {
return (
<>
<button
id="log"
onClick={() => console.error(new Error('navigation error'))}
>
Log
</button>
<Link
id="navigate"
href="/navigation/next?secret=value#fragment"
prefetch={false}
>
Next
</Link>
</>
)
}
'use client'
export default function Page() {
// eslint-disable-next-line no-throw-literal -- Exercise normalization of user-thrown values.
throw 'non-Error render failed'
}
export default function Page() {
return <p>hello world</p>
}
'use client'
import { useState } from 'react'
const error = new Error('promoted error')
export default function Page() {
const [failed, setFailed] = useState(false)
if (failed) {
throw error
}
return (
<>
<button id="log" onClick={() => console.error(error)}>
Log
</button>
<button id="throw" onClick={() => setFailed(true)}>
Throw
</button>
</>
)
}
'use client'
import { useState } from 'react'
export default function Page() {
const [failed, setFailed] = useState(false)
if (failed) {
throw new Error('render failed')
}
return (
<button id="throw" onClick={() => setFailed(true)}>
Throw
</button>
)
}
'use client'
import { Component, useState, type ReactNode } from 'react'
const error = new Error('reused error')
class Boundary extends Component<{ children: ReactNode }, { failed: boolean }> {
state = { failed: false }
static getDerivedStateFromError() {
return { failed: true }
}
render() {
return this.state.failed ? <p id="fallback">Caught</p> : this.props.children
}
}
function Thrower({ failed }: { failed: boolean }) {
if (failed) {
throw error
}
return null
}
export default function Page() {
const [failed, setFailed] = useState(false)
return (
<>
<button id="log" onClick={() => console.error(error)}>
Log
</button>
<button id="throw" onClick={() => setFailed(true)}>
Throw
</button>
<Boundary>
<Thrower failed={failed} />
</Boundary>
</>
)
}
'use client'
export default function SegmentError() {
return <p id="fallback">Segment fallback</p>
}
export default function Page() {
throw new Error('segment failed')
}
export default function Page() {
console.error(new Error('server console failed'))
return <p id="content">Before edit</p>
}
'use client'
import { useEffect } from 'react'
export default function Page() {
if (typeof window !== 'undefined') {
console.error(new Error('strict render failed'))
}
useEffect(() => {
// This report includes all captures from the preceding Strict Mode renders.
console.error(new Error('strict render complete'))
}, [])
return <p>Strict Mode</p>
}
'use client'
import { createRoot } from 'react-dom/client'
import { onUncaughtError } from 'next/dist/client/react-client-callbacks/error-boundary-callbacks'
function Thrower() {
throw new Error('uncaught root failed')
}
export default function Page() {
return (
<>
<p id="content">Main app still mounted</p>
<button
id="throw"
onClick={() => {
const container = document.createElement('div')
document.body.appendChild(container)
// Exercise Next's root callback without an intervening error boundary.
createRoot(container, { onUncaughtError }).render(<Thrower />)
}}
>
Throw in another root
</button>
</>
)
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { useState } from 'react'
export default function Page() {
const [count, setCount] = useState(0)
return (
<>
<button
id="throw"
onClick={() => {
throw new Error('production event failed')
}}
>
Throw
</button>
<button id="increment" onClick={() => setCount(count + 1)}>
Increment
</button>
<p id="count">{count}</p>
</>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { exposeRuntimeErrorsToHMR: true },
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('runtime-error-events-disabled', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('does not open an HMR socket in production even when reporting is enabled', async () => {
const sockets: string[] = []
const browser = await next.browser('/', {
beforePageLoad(page) {
page.on('websocket', (socket) => sockets.push(socket.url()))
},
})
await browser.elementByCss('#throw').click()
await browser.elementByCss('#increment').click()
expect(await browser.elementByCss('#count').text()).toBe('1')
expect(sockets.filter((url) => url.includes('/_next/hmr'))).toEqual([])
expect((await next.fetch('/_next/hmr')).status).toBe(404)
})
})
This diff is collapsed.
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