Commit c8e36f61 authored by Luke Sandberg's avatar Luke Sandberg

Fix dev error page bootstrapping for App Router

The in-memory __next_error__ HTML shell now correctly bootstraps the
turbopack runtime by loading all rootMainFiles as <script async> tags
(mirroring React's renderToReadableStream behavior) instead of <script
defer> in the head. The last rootMainFile is the turbopack runtime
bootstrap which processes all buffered chunk registrations and executes
the app entry point.

On the client side, when the __next_error__ shell is detected, we skip
the full App Router machinery (which would crash without valid RSC
payload/router state) and instead replay any embedded error via
handleClientError so the dev overlay shows it immediately.

Also improved App Router route detection in mixed projects by using
getOriginalAppPaths() for auto-detection instead of requiring explicit
request tagging.
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 5b0497df
......@@ -359,6 +359,38 @@ export async function hydrate(
staticIndicatorState = { pathname: null, appIsrManifest: null }
webSocket = createWebSocket(assetPrefix, staticIndicatorState)
if (document.documentElement.id === '__next_error__') {
// Dev error page served from the in-memory __next_error__ shell.
// No real RSC payload exists and the full App Router machinery
// (ServerRoot, AppRouter, etc.) would crash without valid router
// state. Instead, we skip mounting the React tree entirely.
// The WebSocket is already connected so HMR can deliver
// build/runtime errors. The overlay itself is mounted independently
// by renderAppDevOverlay() in the bootstrap's finally block.
//
// Replay any error embedded in the <template> tag so the overlay
// shows the initial SSR/compilation error immediately.
const ssrErrorTemplate = document.querySelector(
'template[data-next-error-message]'
)
if (ssrErrorTemplate) {
const { handleClientError } =
require('../next-devtools/userspace/app/errors/use-error-handler') as typeof import('../next-devtools/userspace/app/errors/use-error-handler')
const message = ssrErrorTemplate.getAttribute(
'data-next-error-message'
)!
const stack = ssrErrorTemplate.getAttribute('data-next-error-stack')
const digest = ssrErrorTemplate.getAttribute('data-next-error-digest')
const error = new Error(message)
if (digest) {
;(error as any).digest = digest
}
error.stack = stack || ''
handleClientError(error)
}
return
}
}
const initialRSCPayload = await initialServerResponse
......
......@@ -2814,12 +2814,14 @@ export default abstract class Server<
// in-memory __next_error__ HTML shell instead of going through the Pages
// Router _error/_app/_document rendering pipeline.
if (this.dev && this.enabledDirectories.app) {
const isAppOnly = !this.enabledDirectories.pages
const isAppRouteError = getRequestMeta(ctx.req, 'isAppRouteError')
// For app-only projects we always use the in-memory shell.
// For mixed projects we use it when the request was tagged as an
// app route error.
if (isAppOnly || isAppRouteError) {
// For mixed projects we auto-detect whether the failing route is an
// App Router route, so callers don't need to explicitly tag requests.
const isAppRoute =
!this.enabledDirectories.pages ||
getRequestMeta(ctx.req, 'isAppRouteError') ||
this.getOriginalAppPaths(ctx.pathname) != null
if (isAppRoute) {
const { buildAppRouterDevErrorHtml } =
require('./dev/build-dev-error-html') as typeof import('./dev/build-dev-error-html')
return {
......
......@@ -4,6 +4,8 @@ import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
import RenderResult from '../render-result'
import { tryLoadManifestWithRetries } from '../load-components'
import type { BuildManifest } from '../get-page-files'
import { randomUUID } from 'crypto'
import { encodeURIPath } from '../../shared/lib/encode-uri-path'
/**
* Escapes HTML attribute special characters.
......@@ -23,6 +25,13 @@ function escapeHtmlAttr(str: string): string {
* `document.documentElement.id === '__next_error__'` and does CSR with
* the dev overlay instead of hydrating. Error details are embedded in a
* `<template>` tag for the overlay to pick up.
*
* The script loading mirrors what React's renderToReadableStream does:
* all rootMainFiles are loaded as `<script async>` tags. The last
* rootMainFile is the turbopack runtime bootstrap which contains the
* chunk loader, module system, and entry module IDs. When it executes,
* it processes all buffered chunk registrations and starts the app
* entry point (app-next-turbopack), which mounts the dev overlay.
*/
export async function buildAppRouterDevErrorHtml(
distDir: string,
......@@ -35,14 +44,6 @@ export async function buildAppRouterDevErrorHtml(
const rootMainFiles: readonly string[] = buildManifest?.rootMainFiles ?? []
// Build <script> tags for bootstrap entry chunks
const scriptTags = rootMainFiles
.map(
(file) =>
`<script src="${escapeHtmlAttr(`${assetPrefix}/_next/${file}`)}" defer></script>`
)
.join('\n ')
// Build error template (dev only — passes error details to the overlay)
let errorTemplate = ''
if (err) {
......@@ -55,14 +56,30 @@ export async function buildAppRouterDevErrorHtml(
`</template>`
}
const requestId = randomUUID()
// Load all rootMainFiles as async scripts, mirroring React's behavior.
// Each chunk pushes module registrations onto the TURBOPACK global array.
// The last chunk is the turbopack runtime bootstrap which processes all
// registrations and executes the entry module (app-next-turbopack).
const scriptTags = rootMainFiles
.map(
(file) =>
`<script src="${escapeHtmlAttr(`${assetPrefix}/_next/${encodeURIPath(file)}`)}" async=""></script>`
)
.join('\n')
const html = `<!DOCTYPE html>
<html id="__next_error__">
<head>
<meta charset="utf-8">
${scriptTags}
</head>
<body>
${errorTemplate}
<script>self.__next_r=${JSON.stringify(requestId)}</script>
<script>(self.__next_f=self.__next_f||[]).push([0])</script>
<script>self.__next_f.push([1,"0:null\\n"])</script>
${scriptTags}
</body>
</html>`
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment