Skip to content

fix(react-router): avoid Suspense above root documents - #8055

Open
Sheraff wants to merge 4 commits into
mainfrom
fix/issue-8053-root-document-suspense
Open

fix(react-router): avoid Suspense above root documents#8055
Sheraff wants to merge 4 commits into
mainfrom
fix/issue-8053-root-document-suspense

Conversation

@Sheraff

@Sheraff Sheraff commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Fixes #8053

Summary

  • avoid implicitly wrapping document-owning root routes in Suspense
  • keep root Suspense behavior for roots with shellComponent, explicit wrapInSuspense, and selective SSR (ssr: false or ssr: data-only)
  • retain the existing SSR document while a hydrated document-owning root is pending instead of replacing <html> with its pending UI
  • preserve normal pending UI behavior for pure client-rendered roots and nested routes

Regression origin: #7805

Before #7805, MatchView deliberately prevented a root route from getting an implicit route-level Suspense boundary merely because it defined a pendingComponent:

(!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) &&
  (route.options.wrapInSuspense ??
    PendingComponent ??
    ((route.options.errorComponent as any)?.preload || resolvedNoSsr))

For a normal SSR root, route.isRoot was true, wrapInSuspense was not enabled, and resolvedNoSsr was false. The first condition therefore selected SafeFragment, leaving a document-owning root shaped like this during hydration:

<RootComponent>
  <html>
    <head />
    <body>...</body>
  </html>
</RootComponent>

This was an intentional exception, documented by the adjacent comment about only allowing the root to be forcefully wrapped. The separate boundary in Matches.tsx was also disabled during SSR and hydration, while the first child route could still suspend safely through the boundary rendered by Outlet inside the root document.

The Match.tsx rewrite in #7805 removed the root-route condition and reduced the selection to:

route.options.wrapInSuspense ??
  pendingElement ??
  ((route.options.errorComponent as any)?.preload || resolvedNoSsr)

Changing PendingComponent to pendingElement was not itself the problem: both are truthy when a pending component exists. The regression came from dropping the !route.isRoot || ... gate. After that change, adding even pendingComponent: () => null implicitly produced this tree:

<Suspense fallback={pendingElement}>
  <RootComponent>
    <html>
      <head />
      <body>...</body>
    </html>
  </RootComponent>
</Suspense>

React treats <html>, <head>, and <body> as document singletons and hoists them into the server-rendered document preamble. The Suspense markers are emitted lower in <body>, but the client fiber says that Suspense is above <html>. React cannot associate that marker with the client boundary, reports a hydration mismatch, clears the boundary, and client-renders the entire SSR document. The page can still look correct afterward, which makes the lost SSR DOM identity easy to miss.

The lane-loader architecture did not inherently require removing this rule; the guard was lost during the broad renderer simplification. The current fix restores the document-ownership invariant while accounting for the newer architecture:

  • nested routes can still receive implicit boundaries
  • a root with shellComponent is safe because the shell owns <html>/<head>/<body> and the boundary is placed inside it
  • explicit wrapInSuspense remains a force opt-in
  • selective-SSR roots retain the boundary required for client rendering
  • an SSR root that directly owns the document is not implicitly wrapped by pendingComponent

The fix also handles the modern lane renderer's pending branch. When an unwrappable hydrated root becomes pending, it keeps rendering its retained SSR content rather than replacing <html> with pending UI. Pure CSR roots continue to render their pending component normally. Before #7805, the older loading/presentation flow did not expose this direct pending-root replacement path, so restoring only the old boundary expression would not cover all behavior under the new architecture.

Reproduction

The hydration issue is now reproduced directly in e2e/react-start/dev-ssr-styles using React 19.2.3; upgrading to React 19.2.8 is not required.

The Playwright regression:

  • captures an SSR DOM node during HTML parsing, before hydration begins
  • installs a MutationObserver before application code runs
  • waits for client hydration to complete
  • asserts that the captured SSR node was neither removed nor replaced
  • collects browser console and page errors related to hydration

This uses DOM removal and node identity as the behavioral oracle rather than React internal stream comment markers.

Main versus this fix

The production test was also run in an isolated worktree based on origin/main at 38485038c5, with only the E2E fixture commit cherry-picked and all workspace artifacts rebuilt from that checkout.

  • main: fails with captured: true, removed: true, and replaced: true
  • this branch: passes with the same test and command; the SSR node remains attached and retains its identity

The destructive hydration recovery reproduces in both Vite development and a built production application, so the issue is not dev-only. In development React also reports the hydration mismatch; in production the DOM identity check directly detects the destructive recovery.

Coverage

Tests

  • CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:unit --outputStyle=stream --skipRemoteCache (1,010 passed, 1 skipped)
  • CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:types --outputStyle=stream --skipRemoteCache (TypeScript 5.6 through 7.0)
  • CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:eslint --outputStyle=stream --skipRemoteCache (0 errors)
  • CI=1 pnpm run test:e2e in e2e/react-start/dev-ssr-styles (six dev configurations plus production)
  • CI=1 pnpm run test:e2e:prod in e2e/react-start/dev-ssr-styles
  • git diff --check

Summary by CodeRabbit

  • Bug Fixes

    • Improved SSR and hydration behavior for root routes, preserving document content during hydration.
    • Prevented unnecessary pending-state fallbacks from replacing server-rendered content.
    • Ensured pending UI appears only when appropriate, including after configured delay periods.
    • Reduced the risk of hydration errors and unwanted DOM replacement during navigation.
  • Tests

    • Added coverage for root document hydration and SSR content preservation.

@nx-cloud

nx-cloud Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

View your CI Pipeline Execution ↗ for commit e7fcb00

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded 16m 53s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 12s View ↗

☁️ Nx Cloud last updated this comment at 2026-08-12 20:08:58 UTC

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Changeset Version Preview

3 package(s) bumped directly, 10 bumped as dependents.

🟩 Patch bumps

Package Version Reason
@tanstack/react-router 1.170.27 → 1.170.28 Changeset
@tanstack/solid-router 1.170.25 → 1.170.26 Changeset
@tanstack/vue-router 1.170.24 → 1.170.25 Changeset
@tanstack/react-start 1.168.44 → 1.168.45 Dependent
@tanstack/react-start-client 1.168.25 → 1.168.26 Dependent
@tanstack/react-start-rsc 0.1.43 → 0.1.44 Dependent
@tanstack/react-start-server 1.167.32 → 1.167.33 Dependent
@tanstack/solid-start 1.168.42 → 1.168.43 Dependent
@tanstack/solid-start-client 1.168.24 → 1.168.25 Dependent
@tanstack/solid-start-server 1.167.31 → 1.167.32 Dependent
@tanstack/vue-start 1.168.41 → 1.168.42 Dependent
@tanstack/vue-start-client 1.167.27 → 1.167.28 Dependent
@tanstack/vue-start-server 1.167.31 → 1.167.32 Dependent

@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4e476529-cdd0-4cad-8afd-7c5d274a4660

📥 Commits

Reviewing files that changed from the base of the PR and between 794368e and e7fcb00.

📒 Files selected for processing (1)
  • packages/react-router/src/Match.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/react-router/src/Match.tsx

📝 Walkthrough

Walkthrough

Root route rendering no longer wraps document-level SSR or hydrated output in unsafe Suspense boundaries. Pending-state tests and a production Playwright test verify content retention, document preservation, and hydration without errors.

Changes

Root Suspense handling

Layer / File(s) Summary
Root route Suspense guard
packages/react-router/src/Match.tsx, .changeset/fresh-ducks-hydrate.md
canWrapRouteInSuspense restricts root Suspense wrapping based on route position, shell configuration, explicit opt-in, and SSR resolution. The patch changeset documents the behavior.
Pending match rendering
packages/react-router/src/Match.tsx
SSR and hydrated root matches retain rendered content when Suspense wrapping is disallowed. Pure CSR roots render pending UI directly.
Pending-state and hydration validation
packages/react-router/tests/root-pending-min.test.tsx, packages/react-router/tests/issue-7986-retained-pending.test.tsx
Tests verify retained content, minimum pending durations, document-level SSR markup, hydration lifecycle, and shell-based Suspense rendering.
Production hydration regression coverage
e2e/react-start/dev-ssr-styles/src/routes/__root.tsx, e2e/react-start/dev-ssr-styles/tests/issue-8053-root-document-hydration.spec.ts, e2e/react-start/dev-ssr-styles/package.json
The E2E app marks hydration and exposes an SSR node. The Playwright test verifies that hydration does not remove or replace the node and reports no hydration errors. The production test runs in the aggregate workflow.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MatchView
  participant SuspenseGuard as canWrapRouteInSuspense
  participant MatchInner
  participant SSRDocument as SSR document
  MatchView->>SuspenseGuard: Check root route and SSR state
  SuspenseGuard-->>MatchView: Allow or disallow Suspense wrapping
  MatchView->>MatchInner: Render pending match
  MatchInner->>SSRDocument: Retain document output for SSR or hydration
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes restore root-route Suspense safeguards and add tests that verify SSR document retention during hydration for issue #8053.
Out of Scope Changes check ✅ Passed The changeset, implementation, unit tests, and E2E coverage directly support the linked issue and stated objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: preventing Suspense boundaries above root document routes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/issue-8053-root-document-suspense

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Bundle Size Benchmarks

  • Commit: 4c9fe477af35
  • Measured at: 2026-08-12T19:53:18.357Z
  • Baseline source: history:38485038c52f
  • Dashboard: bundle-size history

The following scenarios have bundle-size changes compared with the baseline:

Scenario Current (gzip) Delta vs baseline Initial gzip Raw Brotli Trend
react-router.minimal 83.88 KiB +41 B (+0.05%) 83.75 KiB 262.63 KiB 72.92 KiB ▆██████▁▁▁▁▅
react-router.full 87.38 KiB +35 B (+0.04%) 87.25 KiB 274.34 KiB 75.98 KiB ▅█████▇▁▁▁▁▄
react-start.minimal 96.71 KiB +47 B (+0.05%) 96.57 KiB 304.84 KiB 83.75 KiB ▄█████▇▁▁▁▁▄
react-start.deferred-hydration 97.43 KiB +52 B (+0.05%) 96.59 KiB 306.20 KiB 84.56 KiB ▅█████▇▁▁▁▁▄
react-start.full 99.87 KiB +41 B (+0.04%) 99.74 KiB 314.56 KiB 86.59 KiB ▄██████▁▁▁▁▄
react-start.rsbuild.minimal 100.02 KiB +53 B (+0.05%) 99.85 KiB 315.26 KiB 86.26 KiB ▆██████▁▁▁▁▅
react-start.rsbuild.minimal-iife 100.42 KiB +55 B (+0.05%) 100.26 KiB 316.19 KiB 86.68 KiB ▆██████▁▁▁▁▅
react-start.rsbuild.full 103.34 KiB +54 B (+0.05%) 103.17 KiB 325.35 KiB 88.97 KiB ▆██████▁▁▁▁▄

Current gzip tracks all emitted client JS chunks. Initial gzip tracks only the entry/import graph. Trend sparkline is historical current gzip ending with this PR measurement; lower is better.

@pkg-pr-new

pkg-pr-new Bot commented Aug 12, 2026

Copy link
Copy Markdown
More templates

@tanstack/arktype-adapter

npm i https://pkg.pr.new/@tanstack/arktype-adapter@8055

@tanstack/eslint-plugin-router

npm i https://pkg.pr.new/@tanstack/eslint-plugin-router@8055

@tanstack/eslint-plugin-start

npm i https://pkg.pr.new/@tanstack/eslint-plugin-start@8055

@tanstack/history

npm i https://pkg.pr.new/@tanstack/history@8055

@tanstack/nitro-v2-vite-plugin

npm i https://pkg.pr.new/@tanstack/nitro-v2-vite-plugin@8055

@tanstack/react-router

npm i https://pkg.pr.new/@tanstack/react-router@8055

@tanstack/react-router-devtools

npm i https://pkg.pr.new/@tanstack/react-router-devtools@8055

@tanstack/react-router-ssr-query

npm i https://pkg.pr.new/@tanstack/react-router-ssr-query@8055

@tanstack/react-start

npm i https://pkg.pr.new/@tanstack/react-start@8055

@tanstack/react-start-client

npm i https://pkg.pr.new/@tanstack/react-start-client@8055

@tanstack/react-start-rsc

npm i https://pkg.pr.new/@tanstack/react-start-rsc@8055

@tanstack/react-start-server

npm i https://pkg.pr.new/@tanstack/react-start-server@8055

@tanstack/router-cli

npm i https://pkg.pr.new/@tanstack/router-cli@8055

@tanstack/router-core

npm i https://pkg.pr.new/@tanstack/router-core@8055

@tanstack/router-devtools

npm i https://pkg.pr.new/@tanstack/router-devtools@8055

@tanstack/router-devtools-core

npm i https://pkg.pr.new/@tanstack/router-devtools-core@8055

@tanstack/router-generator

npm i https://pkg.pr.new/@tanstack/router-generator@8055

@tanstack/router-plugin

npm i https://pkg.pr.new/@tanstack/router-plugin@8055

@tanstack/router-ssr-query-core

npm i https://pkg.pr.new/@tanstack/router-ssr-query-core@8055

@tanstack/router-utils

npm i https://pkg.pr.new/@tanstack/router-utils@8055

@tanstack/router-vite-plugin

npm i https://pkg.pr.new/@tanstack/router-vite-plugin@8055

@tanstack/solid-router

npm i https://pkg.pr.new/@tanstack/solid-router@8055

@tanstack/solid-router-devtools

npm i https://pkg.pr.new/@tanstack/solid-router-devtools@8055

@tanstack/solid-router-ssr-query

npm i https://pkg.pr.new/@tanstack/solid-router-ssr-query@8055

@tanstack/solid-start

npm i https://pkg.pr.new/@tanstack/solid-start@8055

@tanstack/solid-start-client

npm i https://pkg.pr.new/@tanstack/solid-start-client@8055

@tanstack/solid-start-server

npm i https://pkg.pr.new/@tanstack/solid-start-server@8055

@tanstack/start-client-core

npm i https://pkg.pr.new/@tanstack/start-client-core@8055

@tanstack/start-fn-stubs

npm i https://pkg.pr.new/@tanstack/start-fn-stubs@8055

@tanstack/start-plugin-core

npm i https://pkg.pr.new/@tanstack/start-plugin-core@8055

@tanstack/start-server-core

npm i https://pkg.pr.new/@tanstack/start-server-core@8055

@tanstack/start-static-server-functions

npm i https://pkg.pr.new/@tanstack/start-static-server-functions@8055

@tanstack/start-storage-context

npm i https://pkg.pr.new/@tanstack/start-storage-context@8055

@tanstack/valibot-adapter

npm i https://pkg.pr.new/@tanstack/valibot-adapter@8055

@tanstack/virtual-file-routes

npm i https://pkg.pr.new/@tanstack/virtual-file-routes@8055

@tanstack/vue-router

npm i https://pkg.pr.new/@tanstack/vue-router@8055

@tanstack/vue-router-devtools

npm i https://pkg.pr.new/@tanstack/vue-router-devtools@8055

@tanstack/vue-router-ssr-query

npm i https://pkg.pr.new/@tanstack/vue-router-ssr-query@8055

@tanstack/vue-start

npm i https://pkg.pr.new/@tanstack/vue-start@8055

@tanstack/vue-start-client

npm i https://pkg.pr.new/@tanstack/vue-start-client@8055

@tanstack/vue-start-server

npm i https://pkg.pr.new/@tanstack/vue-start-server@8055

@tanstack/zod-adapter

npm i https://pkg.pr.new/@tanstack/zod-adapter@8055

commit: e7fcb00

@codspeed-hq

codspeed-hq Bot commented Aug 12, 2026

Copy link
Copy Markdown

Merging this PR will degrade performance by 4.76%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 7 improved benchmarks
❌ 9 regressed benchmarks
✅ 164 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Mode Benchmark BASE HEAD Efficiency
Memory mem server error-paths not-found (vue) 467.2 KB 2,456.6 KB -80.98%
Memory mem server error-paths redirect (react) 304.4 KB 356 KB -14.5%
Memory mem server error-paths not-found (react) 402.7 KB 448.9 KB -10.3%
Memory mem server peak-large-page (solid) 1 MB 1.1 MB -8.28%
Memory mem client navigation-churn (vue) 1.5 MB 1.7 MB -7.4%
Memory mem client interrupted-navigations (vue) 435.8 KB 457.5 KB -4.73%
Memory mem server error-paths unmatched (solid) 562.7 KB 587.1 KB -4.15%
Memory mem server aborted-requests (vue) 1,012.4 KB 1,055.5 KB -4.08%
Simulation client-async-pipeline navigation loop (react) 100.3 ms 103.8 ms -3.41%
Memory mem server error-paths redirect (vue) 648.5 KB 404.3 KB +60.4%
Memory mem server error-paths not-found (solid) 911.2 KB 578.5 KB +57.5%
Memory mem server error-paths unmatched (react) 629.2 KB 418.9 KB +50.19%
Memory mem client unique-location-churn (vue) 576.1 KB 550.8 KB +4.58%
Memory mem server error-paths redirect (solid) 392.3 KB 379.4 KB +3.39%
Memory mem client loader-data-retention (solid) 162.4 KB 157.1 KB +3.36%
Memory mem server serialization-payload (vue) 4.4 MB 4.3 MB +3.09%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix/issue-8053-root-document-suspense (e7fcb00) with main (3848503)

Open in CodSpeed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@e2e/react-start/dev-ssr-styles/tests/issue-8053-root-document-hydration.spec.ts`:
- Around line 9-12: Declare __issue8053Hydration and __issue8053SsrNode on the
Window interface with their appropriate types, then update the hydration-state
assignment and MutationObserver access to use window.__issue8053Hydration and
window.__issue8053SsrNode directly. Remove both window as any casts while
preserving the existing SSR-node and hydration-state behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2822edd2-1749-4472-92b6-172274e50207

📥 Commits

Reviewing files that changed from the base of the PR and between 7edb8b3 and 794368e.

📒 Files selected for processing (3)
  • e2e/react-start/dev-ssr-styles/package.json
  • e2e/react-start/dev-ssr-styles/src/routes/__root.tsx
  • e2e/react-start/dev-ssr-styles/tests/issue-8053-root-document-hydration.spec.ts

Comment on lines +9 to +12
;(window as any).__issue8053Hydration = state

new MutationObserver((records) => {
const ssrNode = (window as any).__issue8053SsrNode as Node | undefined

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Replace any with typed Window properties.

window as any removes type checks for the SSR-node and hydration-state contract. Declare these test properties on Window and access them directly.

Proposed fix
+declare global {
+  interface Window {
+    __issue8053Hydration?: { removed: boolean }
+    __issue8053SsrNode?: Node
+  }
+}
+
-    ;(window as any).__issue8053Hydration = state
+    window.__issue8053Hydration = state
...
-      const ssrNode = (window as any).__issue8053SsrNode as Node | undefined
+      const ssrNode = window.__issue8053SsrNode
...
-      captured: !!(window as any).__issue8053SsrNode,
-      removed: (window as any).__issue8053Hydration.removed,
+      captured: !!window.__issue8053SsrNode,
+      removed: window.__issue8053Hydration!.removed,

As per coding guidelines: **/*.{ts,tsx}: Use TypeScript strict mode with extensive type safety.

Also applies to: 45-50

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@e2e/react-start/dev-ssr-styles/tests/issue-8053-root-document-hydration.spec.ts`
around lines 9 - 12, Declare __issue8053Hydration and __issue8053SsrNode on the
Window interface with their appropriate types, then update the hydration-state
assignment and MutationObserver access to use window.__issue8053Hydration and
window.__issue8053SsrNode directly. Remove both window as any casts while
preserving the existing SSR-node and hydration-state behavior.

Source: Coding guidelines


function RootComponent() {
useEffect(() => {
document.documentElement.dataset.hydrated = 'true'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are we using this particular e2e test as a regression test? this doesnt have to do anything with dev styles, right?

maybe just add a separate e2e project?

}).observe(document, { childList: true, subtree: true })
})

const hydrationErrors: Array<string> = []

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we really need to manually check errors? doesnt our custom test fixture from @tanstack/router-e2e-utils handle that already?


expect(await screen.findByTestId('pending')).toBeVisible()
expect(screen.getByTestId('content')).not.toBeVisible()
expect(screen.queryByTestId('content')).not.toBeInTheDocument()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why was this changed? same question for the other similar changes down below

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Root-route pendingComponent wraps <html> in an unhydratable Suspense since 1.170.19, discarding the whole SSR document

2 participants