Commit 5b0497df authored by Luke Sandberg's avatar Luke Sandberg

Serve in-memory __next_error__ HTML for App Router errors in dev mode

For App Router routes in dev mode, render errors using an in-memory HTML
shell that bootstraps the client-side dev overlay instead of going through
the Pages Router _error/_app/_document rendering pipeline. This avoids
spawning pagesErrorEndpoint in Turbopack for app-router-only projects,
which was causing task conflicts when multiple pages tried to write the
same route.

- Add buildAppRouterDevErrorHtml() helper that constructs a minimal HTML
  shell with the __next_error__ id pattern
- Short-circuit renderErrorToResponseImpl for app router errors
- Guard ensurePage('/_error') in turbopack hot reloader for app-only projects
- Skip getFallbackErrorComponents for app-only projects
- Tag error requests with isAppRouteError meta for mixed app+pages projects
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 0090db22
...@@ -2809,6 +2809,29 @@ export default abstract class Server< ...@@ -2809,6 +2809,29 @@ export default abstract class Server<
body: RenderResult.EMPTY, body: RenderResult.EMPTY,
} }
} }
// In dev mode, for App Router requests (or app-only projects), serve an
// 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) {
const { buildAppRouterDevErrorHtml } =
require('./dev/build-dev-error-html') as typeof import('./dev/build-dev-error-html')
return {
body: await buildAppRouterDevErrorHtml(
this.distDir,
this.nextConfig.assetPrefix ?? '',
err
),
}
}
}
const { res, query } = ctx const { res, query } = ctx
try { try {
......
import { BUILD_MANIFEST } from '../../shared/lib/constants'
import { join } from 'path'
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'
/**
* Escapes HTML attribute special characters.
*/
function escapeHtmlAttr(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
/**
* Builds a minimal HTML shell for dev mode error pages in App Router apps.
*
* Reuses the `__next_error__` pattern: the client detects
* `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.
*/
export async function buildAppRouterDevErrorHtml(
distDir: string,
assetPrefix: string,
err: Error | null
): Promise<RenderResult> {
const manifestPath = join(distDir, BUILD_MANIFEST)
const buildManifest =
await tryLoadManifestWithRetries<BuildManifest>(manifestPath)
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) {
const digest = 'digest' in err ? String((err as any).digest) : ''
errorTemplate =
`<template` +
` data-next-error-message="${escapeHtmlAttr(err.message)}"` +
` data-next-error-digest="${escapeHtmlAttr(digest)}"` +
` data-next-error-stack="${escapeHtmlAttr(err.stack ?? '')}">` +
`</template>`
}
const html = `<!DOCTYPE html>
<html id="__next_error__">
<head>
<meta charset="utf-8">
${scriptTags}
</head>
<body>
${errorTemplate}
</body>
</html>`
return RenderResult.fromStatic(html, HTML_CONTENT_TYPE_HEADER)
}
...@@ -1612,6 +1612,13 @@ export async function createHotReloaderTurbopack( ...@@ -1612,6 +1612,13 @@ export async function createHotReloaderTurbopack(
const pathname = definition?.pathname ?? inputPage const pathname = definition?.pathname ?? inputPage
if (page === '/_error') { if (page === '/_error') {
// For app-router-only projects, skip building Pages Router error
// page infrastructure entirely. The dev server serves an in-memory
// __next_error__ HTML shell instead.
if (!opts.pagesDir) {
return
}
let finishBuilding = startBuilding(pathname, requestUrl, false) let finishBuilding = startBuilding(pathname, requestUrl, false)
try { try {
await handlePagesErrorRoute({ await handlePagesErrorRoute({
......
...@@ -485,6 +485,9 @@ export default class DevServer extends Server { ...@@ -485,6 +485,9 @@ export default class DevServer extends Server {
const { req, res, page } = params const { req, res, page } = params
res.statusCode = 500 res.statusCode = 500
if (params.isAppPath) {
addRequestMeta(req, 'isAppRouteError', true)
}
await this.renderError(err, req, res, page) await this.renderError(err, req, res, page)
return null return null
} }
...@@ -621,6 +624,14 @@ export default class DevServer extends Server { ...@@ -621,6 +624,14 @@ export default class DevServer extends Server {
this.logErrorWithOriginalStack(err) this.logErrorWithOriginalStack(err)
if (!res.sent) { if (!res.sent) {
res.statusCode = 500 res.statusCode = 500
// Tag the request as an App Router error so the error response
// uses the in-memory __next_error__ shell instead of Pages Router.
if (
this.enabledDirectories.app &&
Array.isArray(this.getOriginalAppPaths(pathname!))
) {
addRequestMeta(req, 'isAppRouteError', true)
}
try { try {
return await this.renderError(err, req, res, pathname!, { return await this.renderError(err, req, res, pathname!, {
__NEXT_PAGE: (isError(err) && err.page) || pathname || '', __NEXT_PAGE: (isError(err) && err.page) || pathname || '',
...@@ -1026,6 +1037,12 @@ export default class DevServer extends Server { ...@@ -1026,6 +1037,12 @@ export default class DevServer extends Server {
protected async getFallbackErrorComponents( protected async getFallbackErrorComponents(
url?: string url?: string
): Promise<LoadComponentsReturnType<ErrorModule> | null> { ): Promise<LoadComponentsReturnType<ErrorModule> | null> {
// For app-router-only projects, skip the Pages Router fallback error
// infrastructure entirely. The caller in renderErrorToResponseImpl will
// use the in-memory __next_error__ HTML shell instead.
if (this.enabledDirectories.app && !this.enabledDirectories.pages) {
return null
}
await this.bundlerService.getFallbackErrorComponents(url) await this.bundlerService.getFallbackErrorComponents(url)
return await loadDefaultErrorComponents(this.distDir) return await loadDefaultErrorComponents(this.distDir)
} }
......
...@@ -327,6 +327,13 @@ export interface RequestMeta { ...@@ -327,6 +327,13 @@ export interface RequestMeta {
location: string location: string
duration: number duration: number
} }
/**
* When true, the error being rendered originated from an App Router request.
* Used by renderErrorToResponseImpl to serve the in-memory __next_error__ HTML
* instead of going through the Pages Router _error pipeline in dev mode.
*/
isAppRouteError?: boolean
} }
/** /**
......
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