Relevant source files
The following files were used as context for generating this wiki page:
- packages/next/src/server/patch-error-inspect.ts
- packages/next/src/next-devtools/dev-overlay/container/errors.tsx
- packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx
- packages/next/src/server/dev/middleware-webpack.ts
- packages/next/src/server/dev/browser-logs/source-map.ts
- packages/next/src/server/dev/middleware-turbopack.ts
- packages/next/src/server/dev/hot-reloader-webpack.ts
- packages/next/src/next-devtools/userspace/app/app-dev-overlay-setup.ts
- packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts
- packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx
- packages/next/src/next-devtools/userspace/app/app-dev-overlay-error-boundary.tsx
- packages/next/src/next-devtools/dev-overlay/components/code-frame/code-frame.tsx
- packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts
- packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx
- packages/next/src/next-devtools/dev-overlay/utils/get-error-by-type.ts
- packages/next/src/next-devtools/userspace/app/client-entry.tsx
- packages/next/src/server/mcp/tools/get-errors.ts
- packages/next/src/next-devtools/dev-overlay/container/runtime-error/index.tsx
- packages/next/src/client/dev/hot-reloader/runtime-error-state.ts
- packages/next/src/client/dev/hot-reloader/pages/hot-reloader-pages.ts
- packages/next/src/next-devtools/dev-overlay.browser.tsx
- packages/next/src/server/dynamic-rendering-utils.ts
- packages/next/src/server/mcp/tools/utils/format-errors.ts
- packages/next/src/next-devtools/userspace/app/errors/stitched-error.ts
- packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts
- packages/next/src/next-devtools/dev-overlay/container/build-error.tsx
- packages/next/src/server/dev/node-stack-frames.ts
- packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts
- packages/next/src/next-devtools/dev-overlay/components/overlay/index.tsx
- packages/next/src/server/dev/browser-logs/receive-logs.ts
Overview
The developer overlay is an interactive debugging interface built into Next.js development servers packages/next/src/server/mcp/tools/get-errors.ts:36-42. It acts as a bridge between the running browser application and the server-side compilation and logging pipelines packages/next/src/server/mcp/tools/get-errors.ts:4-14. The overlay intercepts client and server runtime errors, hydration mismatches, unhandled promise rejections, and compilation build failures packages/next/src/server/mcp/tools/get-errors.ts:39-41. By transforming stack traces through Turbopack and Webpack source map middleware, it maps obfuscated bundle frames back to original source files packages/next/src/server/dev/browser-logs/source-map.ts:32-77, formats code frames with ANSI highlighting, and provides integrated developer diagnostics packages/next/src/next-devtools/dev-overlay/container/build-error.tsx:40-63. Additionally, it exposes structured error payloads to external toolchains via the Model Context Protocol (MCP) and forwards browser logs to the terminal packages/next/src/server/mcp/tools/get-errors.ts:36-43.
Sources: packages/next/src/server/mcp/tools/get-errors.ts:4-43, packages/next/src/server/dev/browser-logs/source-map.ts:32-77, packages/next/src/next-devtools/dev-overlay/container/build-error.tsx:40-63
Client Error Interception and Boundaries
Global Error Registration and Interception
The Pages and App routers initialize global error handling by attaching window-level event listeners for unhandled errors and promise rejections packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx:112-126, packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:160-170. Both routers increase Error.stackTraceLimit to 50 to capture deep stack traces packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx:119-119, packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:164-164. In the App router, global errors pass through onUnhandledError and onUnhandledRejection packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:108-158, where isNextRouterError checks filter out internal navigation control flows packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:110-110, packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:138-138. Non-router errors are coerced into standard Error objects via coerceError and enriched with React owner stacks using setOwnerStackIfAvailable if React.captureOwnerStack exists packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:117-118, packages/next/src/next-devtools/userspace/app/errors/stitched-error.ts:13-28.
export function setOwnerStackIfAvailable(error: Error): void {
// React 18 and prod does not have `captureOwnerStack`
if ('captureOwnerStack' in React) {
const ownerStack = React.captureOwnerStack()
// Only set if we captured a valid owner stack, or if none exists yet.
// This prevents overwriting a valid owner stack captured earlier
// (e.g., in onRecoverableError) with null captured later.
if (ownerStack || !ownerStacks.has(error)) {
setOwnerStack(error, ownerStack)
}
}
}Sources: packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx:112-126, packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:108-170, packages/next/src/next-devtools/userspace/app/errors/stitched-error.ts:13-28
React Error Boundaries and Queueing
The AppDevOverlayErrorBoundary component traps rendering errors within the App router tree packages/next/src/next-devtools/userspace/app/app-dev-overlay-error-boundary.tsx:42-61. When getDerivedStateFromError catches a thrown value, it sets RuntimeErrorHandler.hadRuntimeError = true and stores the thrown value in component state packages/next/src/next-devtools/userspace/app/app-dev-overlay-error-boundary.tsx:53-61. Its componentDidCatch lifecycle method triggers dispatcher.openErrorOverlay(), bypassing simulated error messages from segment explorer nodes packages/next/src/next-devtools/userspace/app/app-dev-overlay-error-boundary.tsx:63-72. Errors managed by useErrorHandler populate errorQueue or rejectionQueue and are flushed to listeners via microtasks using queueMicroTask to prevent synchronous state updates during React renders packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:13-53.
Note
ModuleBuildError and ModuleNotFoundError instances are explicitly filtered out in the Pages router error handler (handleError) to prevent duplicate compilation warnings from flashing on the client packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx:67-74.
Sources: packages/next/src/next-devtools/userspace/app/app-dev-overlay-error-boundary.tsx:42-72, packages/next/src/next-devtools/userspace/app/errors/use-error-handler.ts:13-53, packages/next/src/next-devtools/userspace/pages/pages-dev-overlay-setup.tsx:67-74
Hydration Error Detection and State
Storing and Parsing Hydration Errors
The developer overlay captures React hydration mismatches by tracking error states via hydrationErrorState and caching details inside squashedHydrationErrorDetails using a WeakMap<Error, HydrationErrorState> packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:15-17. When console arguments arrive through storeHydrationErrorStateFromConsoleArgs, the system checks whether the message represents a React 18 warning using isReact18HydrationWarning or a React 19 warning using isReact19HydrationWarning packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:58-86. If an argument length of 3 is encountered, secondContent defaults to an empty string to account for warnings lacking explicit content parameters packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:65-67, packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:91-93.
let hydrationErrorState: HydrationErrorState = {}
const squashedHydrationErrorDetails = new WeakMap<Error, HydrationErrorState>()
export function getSquashedHydrationErrorDetails(
error: Error
): HydrationErrorState | null {
return squashedHydrationErrorDetails.has(error)
? squashedHydrationErrorDetails.get(error)!
: null
}Sources: packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:15-25, packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:58-86
Component Stack Diff Generation
For React 18 hydration warnings, generateHydrationDiffReact18 parses component stack traces from the last console argument when direct diffs are missing from the message string packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:108-132. Lines matching at (\w+)( \((.*)\))? are evaluated to separate user-land stack frames from React component nodes packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:143-156. Depending on the hydrationWarningType derived via getHydrationWarningType, the output visualizes mismatch tags or text differences packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:135-135, packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:176-184.
Warning
React 18 hydration warnings occasionally provide component stacks via error arguments instead of direct diff strings, requiring generateHydrationDiffReact18 to reconstruct tag hierarchies by splitting on newline characters packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:108-132, packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:138-139.
Sources: packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:108-132, packages/next/src/next-devtools/userspace/pages/hydration-error-state.ts:135-185
Overlay State Dispatch and Rendering
Dev Overlay Root Lifecycle and Shadow DOM Containment
The development overlay root lifecycle initializes within the browser through DevOverlay, encapsulating its style sheets, scale updates, and error boundary states inside a ShadowPortal component packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx:43-57. Within this boundary, RenderError evaluates the incoming overlay state to bifurcate between build-time errors and runtime errors packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:36-45. The component tracks local indices via selectedIndex and manages panel visibility through PanelRouterContext, which defaults to 'instant-navs' if state.instantNavs is enabled packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx:44-49.
export function DevOverlay() {
const [selectedIndex, setSelectedIndex] = useState(-1)
const { state, dispatch, getSquashedHydrationErrorDetails } =
useDevOverlayContext()
const [panel, setPanel] = useState<null | PanelStateKind>(() =>
state.instantNavs ? 'instant-navs' : null
)
useClearInstantErrorsOnNav(state.page, dispatch)
Sources: packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx:43-52
Navigation changes trigger useClearInstantErrorsOnNav, which tracks the baseline page reference on initial load and dispatches ACTION_INSTANT_ERRORS_CLEAR whenever the route changes to a new non-empty value packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx:26-41. Concurrently, RenderErrorContext aggregates error counts—including normal, instant, and total error metrics alongside vulnerability insights—to supply the tree with context for the ErrorOverlay, PanelRouter, and DevToolsIndicator components packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx:14-19, packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx:70-101.
<RenderErrorContext
value={{
runtimeErrors,
totalErrorCount:
totalErrorCount +
(state.hasVulnerabilityInsight ? 1 : 0),
normalErrorCount,
instantErrorCount:
instantErrorCount +
(state.hasVulnerabilityInsight ? 1 : 0),
}}
>
<PanelRouterContext
value={{
panel,
setPanel,
triggerRef,
selectedIndex,
setSelectedIndex,
}}
>
<ErrorOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={
getSquashedHydrationErrorDetails
}
runtimeErrors={runtimeErrors}
errorCount={totalErrorCount}
/>
<PanelRouter />
<DevToolsIndicator />
</PanelRouterContext>
</RenderErrorContext>Sources: packages/next/src/next-devtools/dev-overlay/dev-overlay.tsx:70-103
Runtime Error State Machine and Deduplication
The runtime error resolution handler maintains a lookups state map that associates individual event IDs with either resolved runtime errors or deferred lookup structures containing both the raw RuntimeErrorEvent and its resolved form packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:47-57. During memoized error collection, errors are iterated in occurrence order to preserve sequence packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:59-67. If an event reference updates while retaining the same ID, deduplication promotion replaces the event while preserving the ID and keeping the overlay mounted during frame resolution packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:75-86.
Note
Deduplication promotion in RenderRuntimeError updates event payloads while maintaining existing IDs, preventing UI unmounting during asynchronous stack frame resolution packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:75-86.
Sources: packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:59-98
Unresolved runtime errors trigger an effect that invokes getErrorByType based on application directory configurations, caching the resulting lookup values packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:100-114. Build errors bypass runtime queue loops and return fixed metrics where totalErrorCount and normalErrorCount are set to 1 with zero instant errors packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:131-140.
const RenderBuildError = ({ children }: Props) => {
return children({
runtimeErrors: [],
// Build errors and missing root layout tags persist until fixed,
// so we can set a fixed error count of 1
totalErrorCount: 1,
normalErrorCount: 1,
instantErrorCount: 0,
})
}Sources: packages/next/src/next-devtools/dev-overlay/container/runtime-error/render-error.tsx:131-140
Server and Browser Stack Demangling
Stack Trace Preprocessing and Parsing
Before call stacks can be resolved against source maps, raw stack traces from the browser or server are preprocessed and parsed into structured frames. The preprocessing step converts chunk URLs under _next/static/chunks/... into absolute file URLs (file://) relative to the specified distribution directory (distDir) packages/next/src/server/dev/browser-logs/source-map.ts:81-105. Once normalized, parseStack breaks the text trace into an array of StackFrame objects containing files, line numbers, columns, and method names packages/next/src/server/dev/browser-logs/source-map.ts:117-118.
function preprocessStackTrace(stackTrace: string, distDir?: string): string {
return stackTrace
.split('\n')
.map((line) => {
const match = line.match(/^(\s*at\s+.*?)\s+\(([^)]+)\)$/)
if (match) {
const [, prefix, location] = match
if (location.startsWith('_next/static/') && distDir) {
const normalizedDistDir = distDir
.replace(/\\/g, '/')
.replace(/\/$/, '')
const absolutePath =
normalizedDistDir + '/' + location.slice('_next/'.length)
const fileUrl = `file://${path.resolve(absolutePath)}`
return `${prefix} (${fileUrl})`
}
}
return line
})
.join('\n')
}Sources: packages/next/src/server/dev/browser-logs/source-map.ts:81-105
Bundler Mapping Contexts
Demangling relies on bundler-specific middleware implementations for Webpack and Turbopack. The MappingContext type union distinguishes between these backends, specifying the compilation stats functions for Webpack or the native Project reference for Turbopack packages/next/src/server/dev/browser-logs/source-map.ts:9-29.
| Bundler Property | Type / Signature | Purpose |
|---|---|---|
bundler | 'webpack' | 'turbopack' | Discriminator for the mapping backend handler. |
isServer | boolean | Indicates whether the error originated from the server runtime. |
isEdgeServer | boolean | Indicates whether the error originated from an Edge runtime route. |
isAppDirectory | boolean | Distinguishes App Router (app/) behavior from Pages Router (pages/). |
clientStats | () => any | (Webpack) Accessor for client compilation stats. |
serverStats | () => any | (Webpack) Accessor for server compilation stats. |
edgeServerStats | () => any | (Webpack) Accessor for edge server compilation stats. |
project | Project | (Turbopack) Native Turbopack project instance reference. |
projectPath | string | (Turbopack) Absolute filesystem path to the project root. |
Sources: packages/next/src/server/dev/browser-logs/source-map.ts:9-29
Webpack and Turbopack Source Resolution
When mapping frames via Webpack, getOriginalStackFrames queries client, server, and edge compilation assets depending on flags like isAppDirectory and isServer packages/next/src/server/dev/middleware-webpack.ts:476-518. For Turbopack, nativeTraceSource loads source map payloads via findSourceMap, instantiates a SourceMapConsumer, and retrieves original positions using zero-based column corrections packages/next/src/server/dev/middleware-turbopack.ts:190-224.
Note
Turbopack source mapping converts 1-based stack frame columns into 0-based columns when querying originalPositionFor, then converts resolved columns back to 1-based values for output packages/next/src/server/dev/middleware-turbopack.ts:219-223, packages/next/src/server/dev/middleware-turbopack.ts:278-279.
Sources: packages/next/src/server/dev/middleware-turbopack.ts:190-293
LRU Caching and Processing Results
Source-mapped stack frames are cached using an LRUCache instance with a fixed capacity of 25 items packages/next/src/server/dev/browser-logs/source-map.ts:107-109. The cache key combines the raw stack trace string, bundler type, App Router status, server flags, distribution directory, and ignore settings packages/next/src/server/dev/browser-logs/source-map.ts:220-226. Processed frames are classified into distinct kinds: success, ignored, rejected, or fallback stack outputs when all frames fail or get filtered out packages/next/src/server/dev/browser-logs/source-map.ts:129-210.
const cache = new LRUCache<
Awaited<ReturnType<typeof getSourceMappedStackFramesInternal>>
>(25)
async function getSourceMappedStackFramesInternal(
stackTrace: string,
ctx: MappingContext,
distDir: string,
ignore = true
) {Sources: packages/next/src/server/dev/browser-logs/source-map.ts:107-115
Code Frame Formatting and Navigation
Parsing ANSI Escape Sequences and Grouping Code Frame Lines
The Code component processes incoming raw code frame strings containing ANSI escape codes packages/next/src/next-devtools/dev-overlay/components/code-frame/code-frame.tsx:18-28. formatCodeFrame splits the input string by carriage returns and newlines, strips ANSI formatting using stripAnsi, and evaluates leading indentation after pipe characters to calculate miniLeadingSpacesLength packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:6-33. When this leading space length exceeds 1, excess spaces are trimmed to preserve proper alignment packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:20-31. groupCodeFrameLines invokes Anser.ansiToJson with use_classes: true and remove_empty: true, subsequently breaking token streams into discrete line arrays whenever a token content string contains a newline character (\n) packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:35-73.
Note
groupCodeFrameLines handles multi-line tokens by splitting on \n and pushing completed segments into separate line arrays while maintaining token styling metadata across boundary breaks packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:49-67.
Sources: packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:35-73
Line Number Parsing and Editor Launch Navigation
parseLineNumberFromCodeFrameLine iterates through initial whitespace or > prefix tokens using isLineNumberPrefixToken, strips pipe characters, and validates whether the remaining trimmed string contains a numeric value packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:75-98. It returns an object specifying the lineNumber and an isErroredLine boolean flag indicating whether lineNumber matches stackFrame.line1 packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:93-97. The CodeFrame component uses useOpenInEditor initialized with the stack frame's file path, line number (stackFrame.line1 ?? 1), and column number (stackFrame.column1 ?? 1) to power click-to-open editor functionality in the shell header packages/next/src/next-devtools/dev-overlay/components/code-frame/code-frame.tsx:30-51.
| Helper Function / Utility | File | Purpose / Operation |
|---|---|---|
formatCodeFile / formatCodeFrame | packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts | Normalizes code frame strings by stripping excessive indentation based on pipe-aligned leading spaces. |
groupCodeFrameLines | packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts | Transforms ANSI-encoded strings via Anser.ansiToJson and segments tokens into line arrays. |
parseLineNumberFromCodeFrameLine | packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts | Extracts numeric line identifiers from token prefixes and marks errored lines. |
useOpenInEditor | packages/next/src/next-devtools/dev-overlay/utils/use-open-in-editor.ts | Binds local editor launching actions to the code frame header link. |
Sources: packages/next/src/next-devtools/dev-overlay/components/code-frame/code-frame.tsx:30-51, packages/next/src/next-devtools/dev-overlay/components/code-frame/parse-code-frame.ts:6-98
Build Error Capture and Diagnostics
Compilation Error Handling and Module Resolution
getNotFoundError validates whether an input error corresponds to a ModuleNotFoundError or a ModuleBuildError containing a missing resolution path matching /Error: Can't resolve '.+' in / packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts:140-154. It resolves the source frame using getSourceFrame, strips extraneous path phrasing from error messages, and constructs an import trace by walking module issuers via getModuleTrace while filtering out internal loader patterns such as next-app, next-middleware, next-client-pages, next-route, next-flight-client, next-flight-server, next-flight-client-entry, and css-loader packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts:35-49,156-183.
Warning
getSourceFrame wraps its inner bundle resolution logic in a try...catch block that suppresses errors on sourcemap resolution failure, returning an empty frame object instead of rejecting the compilation pipeline packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts:57-114.
Sources: packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts:35-183
Terminal Rendering and Error Info Generation
BuildError renders compilation failure outputs inside the developer overlay by wrapping a Terminal component with ErrorOverlayLayout packages/next/src/next-devtools/dev-overlay/container/build-error.tsx:29-77. getErrorTextFromBuildErrorMessage splits multi-line build messages, strips ANSI escape codes via stripAnsi, and extracts the primary error text from the second line of the output packages/next/src/next-devtools/dev-overlay/container/build-error.tsx:11-27.
const generateErrorInfo = useCallback(async () => {
const parts: string[] = []
// 1. Error Type
parts.push(`## Error Type\nBuild Error`)
// 2. Error Message
if (formattedMessage) {
parts.push(`## Error Message\n${formattedMessage}`)
}
// 3. Build Output (decoded stderr)
if (message) {
const decodedOutput = stripAnsi(message)
parts.push(`## Build Output\n${decodedOutput}`)
}
// Format as AI prompt
const errorInfo = `${parts.join('\n\n')}
Next.js version: ${props.versionInfo.installed} (${process.env.__NEXT_BUNDLER})\n`
return errorInfo
}, [message, formattedMessage, props.versionInfo])Sources: packages/next/src/next-devtools/dev-overlay/container/build-error.tsx:40-63
| Helper Function / Utility | File | Purpose / Operation |
|---|---|---|
getNotFoundError | packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts | Intercepts ModuleNotFoundError and ModuleBuildError cases to inject source frames and import traces. |
getImageError | packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts | Formats InvalidImageFormatError instances by tracing module issuers and finding import source lines. |
getErrorTextFromBuildErrorMessage | packages/next/src/next-devtools/dev-overlay/container/build-error.tsx | Extracts clean error strings from multi-line ANSI terminal output strings. |
BuildError | packages/next/src/next-devtools/dev-overlay/container/build-error.tsx | Main overlay container rendering terminal compilation errors and generating AI diagnostics. |
Sources: packages/next/src/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts:140-236, packages/next/src/next-devtools/dev-overlay/container/build-error.tsx:11-77
External Error Reporting and MCP
Browser Log Ingestion and Forwarding
The development server captures console output and error events from client browser sessions via Hot Module Replacement (HMR) messages, utilizing both Webpack and Turbopack handlers packages/next/src/server/dev/browser-logs/receive-logs.ts:700-765. The receiveLogs implementation filters, source-maps, and dispatches log entries according to configured BrowserLogConfig thresholds (error, warn, or verbose) packages/next/src/server/dev/browser-logs/receive-logs.ts:442-496.
When browser logs or unhandled rejections arrive, handleLog inspects individual ServerLogEntry items, categorizing them into standard console calls, logged errors, and formatted errors packages/next/src/server/dev/browser-logs/receive-logs.ts:506-595. Stack traces embedded within these entries are passed through getSourceMappedStackFrames with a MappingContext containing bundler configurations, root directory paths, and stats functions packages/next/src/server/dev/browser-logs/receive-logs.ts:726-735,755-762. Format specifiers such as %s, %d, %o, and %c are managed by stripFormatSpecifiers and processConsoleFormatStrings to prevent ANSI color clashes with custom terminal output formatting packages/next/src/server/dev/browser-logs/receive-logs.ts:121-146,152-206.
Warning
If source map resolution fails during log reception, the server catches the exception and falls back to a best-effort, un-mapped log write for file loggers and terminal outputs rather than crashing the request handling thread packages/next/src/server/dev/browser-logs/receive-logs.ts:643-695.
Sources: packages/next/src/server/dev/browser-logs/receive-logs.ts:442-765
Model Context Protocol (MCP) Error Tooling
The Next.js dev server exposes error states to external tooling using the Model Context Protocol via the get_errors tool registration packages/next/src/server/mcp/tools/get-errors.ts:31-42. This subsystem communicates with active browser client connections by transmitting an HMR request message (HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE) and awaiting responses packages/next/src/server/mcp/tools/get-errors.ts:63-68.
const connectionCount = getActiveConnectionCount()
if (connectionCount === 0) {
return {
content: [
{
type: 'text',
text: JSON.stringify({
error:
'No browser sessions connected. Please open your application in a browser to retrieve error state.',
}),
},
],
}
}
const responses = await createBrowserRequest<OverlayState>(
HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE,
sendHmrMessage,
getActiveConnectionCount,
DEFAULT_BROWSER_REQUEST_TIMEOUT_MS
)
// The error state for each route
// key is the route path, value is the error state
const routesErrorState = new Map<string, OverlayState>()
for (const response of responses) {
if (response.data) {
routesErrorState.set(response.url, response.data)
}
}
const hasRouteErrors = Array.from(routesErrorState.values()).some(
(state) => state.errors.length > 0 || !!state.buildError
)
const hasInstanceErrors = NextInstanceErrorState.nextConfig.length > 0
Sources: packages/next/src/server/mcp/tools/get-errors.ts:48-83
Browser clients report runtime error states through createRuntimeErrorStateReporter, which serializes the window location pathname and SerializedRuntimeErrorState whenever subscriptions trigger updates packages/next/src/client/dev/hot-reloader/runtime-error-state.ts:17-40. Once collected, the server merges route-specific OverlayState maps with NextInstanceErrorState (such as next.config.js validation failures) and passes them to formatErrors packages/next/src/server/mcp/tools/get-errors.ts:72-101. formatErrors resolves original stack frames using the registered StackFrameResolver dependency injection, filters out ignored frames, and structures configuration and session errors into a formatted JSON output for MCP clients packages/next/src/server/mcp/tools/utils/format-errors.ts:20-36,80-119,152-205.
| Log Level / Method | Priority | Target Method Mapping | Purpose / Behavior |
|---|---|---|---|
error | 0 | error, assert | Critical runtime exceptions and failed assertions treated as high priority errors. |
warn | 1 | warn | Warning messages highlighted with distinct coloring. |
verbose | 2 | log, info, debug, table, trace, dir, dirxml, group, groupCollapsed, groupEnd | Informational diagnostics, console tables, traces, and object inspection dumps. |
Sources: packages/next/src/server/dev/browser-logs/receive-logs.ts:448-469
Related
On This Page
OverviewClient Error Interception and BoundariesGlobal Error Registration and InterceptionReact Error Boundaries and QueueingHydration Error Detection and StateStoring and Parsing Hydration ErrorsComponent Stack Diff GenerationOverlay State Dispatch and RenderingDev Overlay Root Lifecycle and Shadow DOM ContainmentRuntime Error State Machine and DeduplicationServer and Browser Stack DemanglingStack Trace Preprocessing and ParsingBundler Mapping ContextsWebpack and Turbopack Source ResolutionLRU Caching and Processing ResultsCode Frame Formatting and NavigationParsing ANSI Escape Sequences and Grouping Code Frame LinesLine Number Parsing and Editor Launch NavigationBuild Error Capture and DiagnosticsCompilation Error Handling and Module ResolutionTerminal Rendering and Error Info GenerationExternal Error Reporting and MCPBrowser Log Ingestion and ForwardingModel Context Protocol (MCP) Error ToolingRelated