next.js icon indicating copy to clipboard operation
next.js copied to clipboard

notFound() serves an empty `__next_error__` document instead of not-found.tsx

Open franknoel opened this issue 2 months ago • 13 comments

Link to the code that reproduces this issue

https://github.com/franknoel/next-notfound-ssr

To Reproduce

  1. Clone the reproduction and run npm install.
  2. Run npm run build && npm run start (npm run dev shows the same thing).
  3. Run ./check.sh, or fetch the pages by hand:
curl -s http://localhost:3000/missing        # page that calls notFound()
curl -s http://localhost:3000/no/such/route  # URL that matches no route

The app has three files: a root layout with <html lang="en">, an app/not-found.tsx that renders NOT FOUND BOUNDARY, and app/[slug]/page.tsx, which calls notFound() unless the slug is known.

Current vs. Expected behavior

Current: /missing answers 404, but its HTML is <html id="__next_error__"><head></head><body> plus scripts. The root layout does not render, so there is no lang and none of the not-found.tsx markup. That markup exists only in the RSC payload, so the page is blank until it hydrates, and stays blank without JavaScript.

An unmatched URL (/no/such/route) is fine: it renders not-found.tsx inside the root layout.

check.sh output, the same on 16.3.6 and 16.4.0-canary.48, in next dev and in next build && next start:

/known           200  <html lang="en">             boundary/page text in HTML: yes
/missing         404  <html id="__next_error__">   boundary/page text in HTML: no
/no/such/route   404  <html lang="en">             boundary/page text in HTML: yes

Expected: /missing renders like /no/such/route: the root layout with NOT FOUND BOUNDARY in the server HTML, and the same 404 status.

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 25.6.0: Tue Aug 18 17:49:13 PDT 2026; root:xnu-12377.161.15.700.19~2/RELEASE_ARM64_T6000
  Available memory (MB): 32768
  Available CPU cores: 10
Binaries:
  Node: 24.21.0
  npm: 11.19.0
  Yarn: 1.22.22
  pnpm: 9.15.9
Relevant Packages:
  next: 16.3.6 // Latest available version is detected (16.3.6).
  eslint-config-next: N/A
  react: 19.2.8
  react-dom: 19.2.8
  typescript: 5.9.3
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Not Found, Error Handling

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local), next start (local), Vercel (Deployed)

Additional context

Also reproduces on [email protected], dev and prod.

Same bug as #98295 and #98954, which were closed automatically for lacking a reproduction link.

Where it seems to happen: HTTPAccessFallbackBoundary is a client error boundary, and React does not run error boundaries during server rendering, so the notFound() throw escapes the Fizz shell. The catch in app-render (renderToStream, and prerenderToStream for ISR) sets the 404 status and renders getErrorRSCPayload, whose seed is the hardcoded __next_error__ document. Because the status and the empty document come from the same catch, an app cannot get a 404 with real HTML from notFound().

We hit it on a site with locale-prefixed routes: every unknown page and event URL is served without lang or any text.

franknoel avatar Sep 26 '26 19:09 franknoel

Confirming on 16.3.6 in production with a different layout: the root layout is app/[locale]/layout.tsx (a dynamic segment, no app/layout.tsx), with app/[locale]/not-found.tsx beside it.

  • A page under [locale] that calls notFound(), such as app/[locale]/care/[id]/page.tsx, gets a 404 whose HTML is the empty <html id="__next_error__"> shell. There is no lang and no <main>, and the not-found markup exists only in the RSC payload. With JavaScript it hydrates into the right page; without it the page stays blank.
  • We also had app/[locale]/[...rest]/page.tsx calling notFound() to route unmatched paths into the locale segment, so every mistyped URL took the same path.

What helped, for unmatched URLs only: removing the catch-all and adding app/global-not-found.tsx (experimental.globalNotFound). Unmatched URLs are then served as a complete server-rendered document. That doesn't help page-thrown notFound(), which is this issue.

One detail for anyone testing this: a check that greps the response body for the not-found copy passes on the broken page, because the copy is in the RSC payload. We had to strip <script> elements and require <html lang> to detect it.

rldyourmnd avatar Sep 27 '26 16:09 rldyourmnd

Another consequence of the empty __next_error__ shell: in production, the client render of the not-found UI can hang for exactly ~60 s.

Setup: 16.3.4 and 16.3.6 (bundled react-dom 19.3.0-canary-cbb046ab-20260731), next build && next start, a global CSS import in the root layout, a page that calls notFound(). Chromium via Playwright, 120 loads, 12 in parallel, a fresh context (cold cache) for each.

  • 8–11 of 120 loads on 16.3.4 and 9–10 of 120 on 16.3.6 show no not-found text after 15 s.
  • With a 75 s wait, every stuck load renders at 60.3–60.5 s.
  • An unmatched URL rendered through the root not-found.tsx never hangs, because it is server-rendered.

What we traced: the not-found tree is rendered on the client with createRoot(document). During commit, clearContainerSparingly removes the <link rel="preload" as="style"> for the page CSS, and the load is aborted. The suspensey commit (suspendResource) still waits for that stylesheet's load event, until React's built-in 60 s timeout.

experimental.inlineCss: true avoids it: 0 hangs in 160 loads. So for users on a slow or cold connection, this bug can mean a blank 404 for a full minute, not only missing SSR markup.

mityalyalin avatar Sep 28 '26 19:09 mityalyalin

Investigated the root cause of the broken 404 SSR behavior:

Context & backport: Server-side rendering of the not-found boundary in the prerender recovery path was introduced in #92231 (April, canary) and backported to 16.2 via #93470. Because of this, our 404s render complete HTML on 16.2.12, as expected.

Revert & current state: It was subsequently reverted in #94037, which explicitly noted: "it also means the page is not going to statically prerender the notFound UI. This will be handled in a followup". That follow-up
hasn't landed yet, so 16.3.x and 16.4-canary simply return an empty __next_error__ document.

Impact on our setup (cacheComponents: true, app/[locale] + notFound() for missing posts): Ran a bisect comparing 16.2.6/16.2.12 against 16.3.6. On newer versions, the 404 response is stripped of lang, <title>,
and page content. We are staying pinned to 16.2.12 for now.

Does anyone know if there is an active tracking issue or PR for the promised follow-up?

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

umtale avatar Sep 29 '26 10:09 umtale

server-side not-found rendering from #92231 (backported to 16.2 in #93470) was reverted in #94037, whose follow-up hasn't landed. Could it be unhidden?

umtale avatar Sep 29 '26 10:09 umtale

Still reproduces on [email protected] (the 30/09 security release), next build && next start, React 19.2.8.

Minimal app, 4 files:

// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (<html lang="en"><body><header>Site header</header>{children}</body></html>);
}
// app/page.tsx
export default function Home() { return <h1>Home</h1>; }
// app/not-found.tsx
export default function NotFound() { return <h1>Custom not found</h1>; }
// app/[slug]/page.tsx
import { notFound } from 'next/navigation';
export async function generateStaticParams() { return [{ slug: 'known' }]; }
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  if (slug !== 'known') notFound();
  return <h1>Known item</h1>;
}
/known      200  <html lang="en">           text in server HTML: yes
/unknown-1  404  <html id="__next_error__">  text in server HTML: no (body = hidden div + scripts)
/a/b        404  <html lang="en">           text in server HTML: yes

Workaround we run in production (Next 16.3.8 on Vercel), in case it helps others: the proxy checks the content id against a cached index of public ids and, for a missing one, returns NextResponse.rewrite(new URL('/<locale>/not-found-page/<type>', request.url), { status: 404 }) to a static page. That gives a real 404 with the full layout, lang/dir and no-JS content, and existing pages keep their ISR cache.

Approaches we measured that did not work: loading.tsx (soft 200), rendering the not-found UI inside the page (200), notFound() in generateMetadata (same empty shell), dynamicParams = false (new content stays 404 until the next deploy, since generateStaticParams is not re-run during ISR).

asaralyon avatar Oct 04 '26 15:10 asaralyon

Confirming on the latest stable and canary.

  • next 16.3.8 (latest) and 16.4.0-canary.61, React 19.3.0, Node 24, Turbopack, next build && next start.
  • Minimal app, no i18n, no dynamic root segment:
    • app/layout.jsx: <html lang="fr"><body>{children}</body></html>
    • app/not-found.jsx: <h1>Page introuvable A</h1>
    • app/x/page.jsx: calls notFound() (prerendered at build)
    • app/y/[id]/page.jsx: generateStaticParams returns [], calls notFound() unless id === "ok" (rendered on demand)

Results with JavaScript disabled:

URL Status HTML
/zzz/ (no route) 404 <html lang="fr"> with <h1>Page introuvable A</h1>
/x/ 404 <html id="__next_error__">, empty body
/y/abc/ (first request MISS, then HIT) 404 <html id="__next_error__">, empty body; this empty document is what ISR caches

Same result with app/[locale]/layout as the root layout, and with experimental.globalNotFound on or off.

A possible direction: the server action path already handles this case by rendering createNotFoundLoaderTree(loaderTree) with a 404 status (the actionRequestResult.type === 'not-found' branch in app-render). Doing the same in the shell-error recovery of renderToStream / prerenderToStream when the error is an HTTP access fallback might render not-found (or global-not-found) inside the layout, as for unmatched URLs.

EloiHehocom avatar Oct 06 '26 10:10 EloiHehocom

The ~60s blank that @mityalyalin described above is a react-dom bug, and we've opened a fix upstream: react/react#37906.

Root cause: Next serves the __next_error__ shell and client-renders the not-found tree with createRoot(document). React inserts <link rel="preload" as="style"> for the page CSS during render, and the root's first commit then runs clearContainerSparingly(document). That function keeps rel="stylesheet" links but removes React's own preloads. If a preload hasn't loaded yet, the request is aborted and no load/error event fires. The stylesheet resource is still waiting on that node, so the reveal sits until React's 60s stylesheet timeout. The fix keeps links React marked as hoistable, the same check clearHead already makes.

Numbers from our production site (/companies/<missing-slug>, headless Chrome, cold context per load): 3 of 60 loads blank past 15s, each with exactly one net::ERR_ABORTED request, and 0 CSS preloads left after load. On a patched production build, 0 of 100 loads were blank and both preloads stayed in <head>.

Until a Next release bundles a fixed react-dom, you can apply the same one-line change with pnpm patch next@<version> to all eight client builds under next/dist/compiled/react-dom{,-experimental}/cjs/react-dom-{client,profiling}.*.js:

 case "LINK":
-  if ("stylesheet" === node.rel.toLowerCase()) continue;
+  if (
+    "stylesheet" === node.rel.toLowerCase() ||
+    node[internalHoistableMarker]
+  )
+    continue;

experimental.inlineCss: true also avoids it, as noted above. The underlying issue here, that notFound() doesn't server-render not-found.tsx, is separate and still needs the follow-up to #94037.

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

winkelmeyer avatar Oct 20 '26 00:10 winkelmeyer

The reproduction suggests a split between two server-rendering paths: an unmatched route renders the not-found boundary inside the root layout, while a page-level notFound() response falls back to the bare __next_error__ document and leaves the boundary only in the RSC payload.

I'd try to route page-level notFound() through the same server-rendered not-found boundary composition as an unmatched route, while preserving the 404 status and existing streaming/cache semantics. The fix should not depend on JavaScript hydration to produce the actual not-found content.

Regression coverage should include both a static root layout and a dynamic root segment such as app/[locale]/layout.tsx, with notFound() thrown by a page that is prerendered and by one rendered at request time. Assert the response status, root-layout metadata (such as lang), and the not-found markup in the raw HTML without executing JavaScript. Since the issue describes this behavior in both dev and production builds, run the test in both modes where the existing test harness supports it.

I haven't run the reproduction locally; this suggestion is based on the supplied report and the difference between the two response paths.

secheverrianogal-beep avatar Oct 21 '26 20:10 secheverrianogal-beep

We independently reproduced the empty initial 404 HTML on Next.js 16.4.0, including a reduced example without a CMS or i18n library. I added the inline reproduction and production Cache Components findings in https://github.com/vercel/next.js/issues/99793#issuecomment-6413980664 to keep the detailed evidence in one place.

The additional finding is that repairing the fallback HTML alone was insufficient in our completed static Cache Components recovery: it still inlined the original failed page's Flight data, and a plain return-home anchor remained inert after hydration. Using matching recovered HTML/Flight and cached Flight metadata resolved that in our local production checks. The comment records the exact scope and unverified cases; we have not tested current canary releases.

robfaria avatar Oct 26 '26 10:10 robfaria

Still reproduces on 16.4.3 (latest) and 16.5.0-canary.34, next build && next start, React 19.3.0, Node 24, Windows. Minimal setup (create-next-app 16.4.3, App Router):

// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="fr" dir="ltr">
      <body>
        <header>Layout header</header>
        {children}
      </body>
    </html>
  );
}

// app/not-found.tsx
export default function NotFound() {
  return <h1>Not found here</h1>;
}

// app/missing/page.tsx
import { notFound } from 'next/navigation';
export default function Page() {
  notFound();
}

// app/missing/[id]/page.tsx
import { notFound } from 'next/navigation';
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  await params;
  notFound();
}

Server HTML with <script> elements stripped:

URL Status lang not-found text __next_error__
/missing (prerendered) 404 no no yes
/missing/123 404 no no yes
/missing-dynamic/123 (same page with dynamic = "force-dynamic") 404 no no yes
/does-not-exist (no route) 404 yes yes no

Two things I haven't seen in the thread:

  1. cacheComponents soft 404. With cacheComponents: true, a page that does await connection(), sets export const instant = false and then calls notFound() answers 200 (x-nextjs-postponed: 1) with the same empty __next_error__ shell and noindex. Prerendered pages still answer 404. Same on 16.4.3 and 16.5.0-canary.34.
  2. Not limited to the #94037 revert, at least without cacheComponents. With the default config, the bare shell is also served on 14.2.35, 15.5.28, 16.0.11 and 16.2.12 (where #93470 was backported), so whatever #92231/#93470 fixed didn't cover this configuration. I didn't test 16.2.12 with cacheComponents. A nested not-found.tsx next to the page or experimental.globalNotFound doesn't change it.

Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!

mun3imoz avatar Oct 30 '26 14:10 mun3imoz

Adding a code-level finding on 16.4.3 that seems to explain why the Suspense/loading.tsx workaround turns into a soft 404. It may also explain the cacheComponents 200 reported above. It concerns only the status code, not the empty shell.

The two render paths handle a notFound() caught by a Suspense boundary differently:

  • prerenderToStream (dist/server/app-render/app-render.js ~L5260-5266): its htmlRendererErrorHandler calls setHTTPAccessFallbackOrRedirectStatus(err) before captureHTMLError. The comment there reads: "React can complete a prerender after an HTTP access fallback or redirect error is thrown inside a Suspense boundary. Update the response while preserving the prerendered content outside the boundary." A boundary-caught notFound() therefore keeps the 404 and the real HTML outside the boundary.
  • renderToStream (~L2078): its handler is createHTMLErrorHandler(...) from create-error-handler.js. That returns a digest but never touches res.statusCode. The same boundary-caught notFound() therefore answers 200, and only the shell-error recovery catch (~L2494) sets 404, and only when the shell itself errored.

The result is that one page answers 404 when it is prerendered or ISR-filled, and 200 when it is rendered at request time (dynamic, connection(), postponed resume).

This leaves apps that must serve a real 404 document with no supported option:

  • notFound() outside every boundary (e.g. from a catch-all layout) gets the correct 404 but the empty __next_error__ shell.
  • Moving the throw under a small <Suspense> puts the layout and not-found UI in the HTML, but the dynamic path then answers 200.

Suggested direction: in renderToStream, apply setHTTPAccessFallbackOrRedirectStatus from the HTML error handler while the headers are still unsent, as prerenderToStream already does. That would make the Suspense placement a working fix for this issue's empty-shell symptom on both paths.

sbfs-co avatar Nov 03 '26 15:11 sbfs-co

Another reproduction on Next.js 16.3.8 / React 19.2.8 (Turbopack), next build && next start and next dev, with one extra symptom that may help prioritise it: the page can fail to hydrate at all.

Minimal variants (each a fresh app, only layout, page, not-found and a page that calls notFound()):

Variant Route calling notFound() Unmatched URL
app/[lang]/layout.tsx as root layout + generateStaticParams __next_error__ shell, 0 stylesheets, no not-found markup same (caught by [...rest])
same, without generateStaticParams same same
same, plus a second root layout (app/studio/layout.tsx) same same
regular app/layout.tsx, [lang] as a normal segment same same
simplest app: app/layout.tsx + app/not-found.tsx + app/x/page.tsx → notFound() __next_error__ shell, 0 stylesheets OK (prerendered /_not-found, 1 stylesheet)
experimental.inlineCss: true still no not-found markup in the HTML —
proxy.ts rewrite to a regular page with NextResponse.rewrite(url, { status: 404 }) — OK (404, layout, stylesheet and markup in the HTML)

Extra symptom (hydration stall): because the server HTML contains no <link rel="stylesheet">, React inserts the root layout's stylesheets on the client and suspends until they load. In our e2e suite (Playwright/Chromium against next start), 7 of 160 404 loads never finished hydrating: one of those stylesheet requests shows net::ERR_ABORTED and the root never commits (no further chunks requested). Regular pages, whose stylesheets are in the server HTML, never stalled.

Workaround we are evaluating: rewrite structurally-unknown paths in proxy.ts to a regular localized page with status: 404 (covers unknown segments and too-deep paths); notFound() from data lookups (unknown slug) remains affected.

vallartagomx-byte avatar Nov 12 '26 16:11 vallartagomx-byte

Also reproduces on 16.4.6 (React 19.3.1, Turbopack), in next dev and in production on Vercel. Adding data for the setup that next-intl documents in its error files guide, since every app following that guide gets the empty shell for every mistyped URL.

Setup (no app/layout.tsx):

  • app/[locale]/layout.tsx: root layout, generateStaticParams for the locales, dynamicParams = false, notFound() for an unknown locale
  • app/[locale]/not-found.tsx: Server Component, no "use client"
  • app/[locale]/[...rest]/page.tsx: calls notFound() and exports generateMetadata (title + robots)
  • dynamic routes such as app/[locale]/<segment>/[slug]/page.tsx: generateStaticParams + dynamicParams = false, notFound() for an unknown slug
  • app/global-not-found.tsx with experimental.globalNotFound: true
  • next-intl proxy with the matcher from its docs (/((?!api|_next|_vercel|.*\\..*).*)) and localePrefix: 'as-needed'

Production results (curl, server HTML only):

Request Handled by Status Server HTML
/unknown proxy rewrites to the default locale, [...rest] calls notFound() 404 <html id="__next_error__">, empty body
/es/unknown [...rest] calls notFound() 404 same
/<segment>/unknown-slug the page calls notFound() 404 same
/api/unknown not matched by the proxy; the root layout calls notFound() for the invalid locale 404 same, although the RSC payload carries the global-not-found tree
/unknown.html not matched by the proxy, no locale: global-not-found 404 full document with <html lang> and the 404 markup

Two details that may help:

  1. global-not-found is affected too when it is reached through a thrown notFound() (here, the root layout rejecting an invalid locale). It is server-rendered only when Next serves it directly for an unmatched URL.
  2. The empty shell's <head> carries the root layout's metadata: its default <title> and the canonical it sets for the home route. The catch-all's generateMetadata title does not reach the server HTML; the title changes only after hydration. noindex is present.

The ~60 s hang: not reproduced on this deployment. 48 cold loads in 3 fresh browser contexts (the 404 loaded in 12, 12 and 24 parallel same-origin iframes; no throttling, Fast 4G and Slow 4G): all rendered with styles applied within 8.3 s.

luisfelipemillanprado avatar Dec 02 '26 19:12 luisfelipemillanprado