Skip to content
Source
Sign inSign up
TanStack/router

perf(router-core): hydrate without awaiting code-split component chunks #8577

OpenTarekkharsa(GitHub profile, opens in a new tab)wants to merge 6 commits intomain fromrefs/pull/8577/headopened

🎯 Changes

Supersedes #8484 (moved from my work account).

hydrate() awaits loadRouteChunk() for every committed match before setMatches. RouterClient and StartClient render <Await> on that promise, so the root commits nothing until the whole component closure of the matched routes has downloaded. That includes chrome whose code already sits in the entry chunk, such as a header in the root route. A click on a header <Link> in that window is a native document navigation.

We measured the cost on a production React Start app on @tanstack/router-core@1.171.32. The table shows the root commit time, median of 3 runs, at 4x CPU slowdown with 150 ms RTT and 1.6 Mbps:

PageAwaiting chunksWithout the wait
Home4484 ms3375 ms
Search results4969 ms3825 ms
Detail page6237 ms3890 ms
Login3991 ms3372 ms

The route body still waits for its own chunk. The bytes loaded before the commit do not change.

This makes the header interactive while the route's Suspense boundary is still dehydrated. That is the window behind #8198, which #8576 closes, so this PR lands best after #8576.

What changes. hydrate() still starts every chunk load, but now it awaits only the lazy route options that have not merged yet (loadRouteChunk(route, false)). A code-split component is a lazyRouteComponent. If its chunk has not arrived when the adapter renders it, it suspends, and the server HTML stays in place until the chunk arrives:

  • React keeps the server HTML of a dehydrated Suspense boundary. The root Outlet always puts the child match inside one.
  • Solid: lazy() keeps the server DOM during hydration and hydrates it when the module arrives. The pending branch of lazyRouteComponent rendered <Loadable />, which added one component level and shifted the hydration keys. It now calls Loadable(props).
  • Vue hydrates an unresolved defineAsyncComponent only once its loader settles (since 3.3). The pending branch of lazyRouteComponent rendered an empty <div>; it now renders an async component. A missing module still reloads once. After that reload, the error now reaches the route's error boundary instead of leaving an empty <div>.

All three adapters behave the same, so _hydrateWithoutComponentChunks is gone. A ssr: 'data-only' route keeps the pending UI it already shows until its chunk arrives, with no mismatch and no new flash.

Lazy route options. A route with a lazyFn (.lazy(), createLazyFileRoute) has no component until its options merge, and would render <Outlet /> in its place. Hydration still waits for those options, but only for the options module. It no longer waits for every component chunk in the lane. Scoping the wait to that route's subtree would need each adapter's Match to suspend on route._lazy; I left that for a follow-up.

Failure path. lazyRouteComponent.preload never rejects in React or Solid. It records the error and throws it on render: a module-not-found error reloads the document once (guarded in sessionStorage), and any other error goes to the route's error boundary. So for code-split components the failure path does not change. A rejected lazyFn is still awaited and still retries from that match. The one change is for a hand-written component with a custom preload: it is no longer awaited before the first render, so a component that depends on it must suspend or handle the pending state in render, and a rejecting preload no longer triggers retryFrom. No adapter's lazyRouteComponent.preload rejects, so a rejecting lazyFn is the only real chunk failure left during hydration. The four public-hydration-contract tests that used a rejecting component preload therefore now use a rejecting lazyFn, with the same assertions.

Commits are ordered so that the tail can be dropped: core narrow lazyFn wait, React tests, Solid, Vue, then the flag removal. Dropping the last one keeps the flag; dropping the last two also leaves Vue as it is today.

Size (min+gzip, compared with main): router-core load-client +10 B (the first version of this PR was +40 B). Solid lazyRouteComponent −2 B. Vue lazyRouteComponent −50 B, but a Vue app that does not already use defineAsyncComponent now bundles it (about +0.8 kB).

Tests. Each hydration test renders on the server, hydrates real markup with a component chunk held pending, and checks that the server HTML and DOM nodes are kept, that the page is interactive once the chunk resolves, and that there are no hydration warnings.

  • packages/react-router/tests/hydration-component-chunks.test.tsx: a pending lazyRouteComponent; pending lazyFn options; options that resolve to a pending lazyRouteComponent.
  • packages/solid-router/tests/hydration/: the same cases for Solid, in a new vitest --mode hydration run. Solid hydration needs markup from Solid's server build, so globalSetup renders it with the server build and the jsdom tests hydrate it with hydratable client output. It also covers an event that ends hydration before the chunk arrives. These tests fail without the Solid fix with Hydration Mismatch.
  • packages/vue-router/tests/hydration-component-chunks.test.tsx: the same cases for Vue, plus a missing chunk during hydration. The hydration tests also pass against Vue 3.3.4. lazyRouteComponent-module-not-found.test.tsx covers the one-time reload and the error boundary after it.
  • packages/router-core/tests/hydration-component-chunks.test.ts: chunk loads start but are not awaited, lazy options are awaited, and a rejecting preload causes no unhandled rejection.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested code changes locally with the relevant test commands, or tests do not apply to this pull request.
  • I fully understand the code in this pull request, including any code generated with AI assistance.

Local runs on top of main at 57e126e99d, all exit 0: build, test:unit (for Solid: client, --mode server and --mode hydration), test:eslint, test:types and test:build for @tanstack/router-core, @tanstack/react-router, @tanstack/solid-router, @tanstack/vue-router and @tanstack/react-start-client.

E2E in Chromium against production builds (Start always enables auto code splitting): solid-start/basic 84 passed, vue-start/basic 81 passed, solid-start/deferred-hydration 15 passed, solid-start/selective-ssr all 11 passed, vue-start/selective-ssr 8 passed. In both selective-ssr suites, Playwright then timed out waiting for the web server teardown after the tests had passed. I did not check whether that also happens on main. I did not run the React Start e2e suites.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • New Features
    • Hydration can complete while route component code is still loading, preserving server-rendered content until the component is ready.
    • Lazy route options are still loaded before route matches are committed, while component preloads no longer delay the first render.
    • Routes remain interactive when hydration finishes before their component code arrives.
  • Bug Fixes
    • Improved handling of component-loading failures during hydration, including module-not-found errors.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: Repository: TanStack/router/.coderabbit.yaml

      Review profile: CHILL

      Plan: Advanced

      Run ID: 720aaec3-8147-492d-97dd-e003ef34cf73

      📥 Commits

      Reviewing files that changed from the base of the PR and between 2b3b27ccae6a23ee2289122e18c181dbacff8b57 and db2548ea5d98c86b571661ad61f4d61915b6f9a6.

      📒 Files selected for processing (14)
      • .changeset/hydrate-without-component-chunks.md
      • packages/react-router/tests/hydration-component-chunks.test.tsx
      • packages/router-core/src/load-client.ts
      • packages/router-core/tests/hydration-component-chunks.test.ts
      • packages/router-core/tests/public-hydration-contract.test.ts
      • packages/solid-router/package.json
      • packages/solid-router/src/lazyRouteComponent.tsx
      • packages/solid-router/tests/hydration/hydration-component-chunks.test.tsx
      • packages/solid-router/tests/hydration/render-on-server.tsx
      • packages/solid-router/tests/hydration/routes.tsx
      • packages/solid-router/vite.config.ts
      • packages/vue-router/src/lazyRouteComponent.tsx
      • packages/vue-router/tests/hydration-component-chunks.test.tsx
      • packages/vue-router/tests/lazyRouteComponent-module-not-found.test.tsx
      🚧 Files skipped from review as they are similar to previous changes (1)
      • .changeset/hydrate-without-component-chunks.md

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


      📝 Walkthrough

      Walkthrough

      Hydration no longer waits for route component chunks, but it still waits for unresolved lazy route options. The changes include Router Core loading behavior, React and Solid hydration tests, and Vue lazy-component loading changes and tests.

      Changes

      Hydration without component chunks

      Layer / File(s)Summary
      Core hydration loading and contracts
      packages/router-core/src/load-client.ts, packages/router-core/tests/*hydration*, packages/router-core/tests/public-hydration-contract.test.ts, .changeset/hydrate-without-component-chunks.md
      Router Core retains the component-chunk load promise while waiting for lazy route options. Tests cover pending and rejected loads and route-lazy-loader behavior. The changeset records the package releases and framework behavior.
      React hydration coverage
      packages/react-router/tests/hydration-component-chunks.test.tsx
      Tests cover hydration with pending component chunks, unresolved lazy route options, and chunks referenced by resolved options.
      Solid component loading and hydration coverage
      packages/solid-router/src/lazyRouteComponent.tsx, packages/solid-router/tests/hydration/*, packages/solid-router/vite.config.ts, packages/solid-router/package.json
      Solid calls Loadable directly. Hydration tests cover pending chunks, lazy route options, and interaction before a chunk resolves. Test setup renders server state and adds a hydration test mode.
      Vue async components and hydration coverage
      packages/vue-router/src/lazyRouteComponent.tsx, packages/vue-router/tests/hydration-component-chunks.test.tsx, packages/vue-router/tests/lazyRouteComponent-module-not-found.test.tsx
      Vue uses defineAsyncComponent for lazy route components and sets a session-storage reload marker for module-not-found errors. Tests cover hydration with pending chunks and repeated module-load failures.

      Priority: ➖ Normal

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

      Change: Bug fix

      Sequence Diagram(s)

      sequenceDiagram
        participant ClientRouter
        participant RouterCore
        participant RouteLazyLoader
        participant ComponentChunk
        ClientRouter->>RouterCore: Hydrate from server matches
        RouterCore->>RouteLazyLoader: Load unresolved route options
        RouterCore->>ComponentChunk: Start component chunk load
        RouteLazyLoader-->>RouterCore: Return route options
        RouterCore-->>ClientRouter: Commit route matches
        ComponentChunk-->>ClientRouter: Resolve component chunk

      Merge Risk: ⚪ Minimal · up to db254

      Hydration can complete before component chunks arrive while still waiting for lazy route options. No actionable merge-blocking issue remains; merge after normal checks pass.

      Security Architecture Review

      Security architecture risk: 🔵 Low · up to db254

      No new privilege or data-access expansion was demonstrated. Navigation ownership checks remain in place, but failed-download and reload recovery are not fully verified end to end.

      Retained concerns No architecture-level concerns identified.

      Security review details

      Security Blast Radius

      • inferred — The examined recovery path affects the active browser document and its session-scoped reload marker. Evidence does not establish attacker control of application importers or error messages, or downstream tenant, backend, or credential exposure.

      Trust Boundaries and Controls

      • observed — Normal execution waits for lazy option merging before match publication, and ownership checks prevent a superseded hydration from publishing. Vue retains ClientOnly rendering for SSR-disabled components and restricts reload recovery to recognized dynamic-import error messages.

      Resilience and Maintainability Implications

      • observed — After an earlier lazy-option failure, hydration can stop awaiting descendants and publish candidates for client recovery. The same short-circuit and publication logic exists in the PR base, so it is not retained as an introduced control bypass. Renderer behavior with unresolved descendant options remains incompletely covered.

      Hardening Proposals

      • proposed — Validate missing-module recovery across successful reload, blocked reload, and navigation supersession, including whether a late failure from an abandoned route can reload the replacement document. This is a recovery-verification proposal, not an observed vulnerability.
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 3.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 14 files. (2 skipped: …Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Description check✅ PassedThe description follows the required template. It explains the changes and motivation, completes the checklist, documents testing and known limitations, and includes a changeset declaration.
      Title check✅ PassedThe title clearly and concisely describes the primary change: router hydration no longer awaits code-split component chunks.
      Full details: Docstring Coverage

      Explanation

      Docstring coverage is 3.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 14 files. (2 skipped: 2 unsupported.)

      • Fix all pre-merge checks with AI
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR
      • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Autopilot is currently an internal CodeRabbit preview.


      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.
    2. (copied from previous PR)

      1. Could you give me a human-readable TL;DR of this change? If i understand correctly we don't await the chunks during hydration (unless they are explicitly lazy) because they are not required for the hydration (they will simply load later, in render, and cause a suspense)

      2. The failure path you are describing, if i understand correctly, is that we're not catching a failed lazy chunk load during hydration anymore, is that right?

      3. Could you enumerate the setups that are impacted and those that aren't? (stuff like auto code splitting, manual code splitting, custom preload, explicit .lazy...)

      4. it'd be interesting to see if we can apply the same logic to Vue and/or Solid. We don't like to advance 1 adapter and leave the other 2 behind (if there isn't a good reason to). And as a bonus if we can apply this to all 3, we can remove _hydrateWithoutComponentChunks completely.

      5. also this is interesting

        The wait could later be scoped to that route's subtree

        does that make the code much more complex? we're trying not to add too many bytes, but i could see that being quite nice for some apps

    3. Sorry I missed these on #8484. Answers below, and I updated the PR.

      1. Close. hydrate() still starts every chunk load, but it no longer waits for them before it commits the matches. A component whose chunk hasn't arrived suspends, and the server HTML stays on screen until the chunk lands. The only thing hydration still waits for is a .lazy() route whose options haven't loaded, because without them that route would render <Outlet />. One side effect to know about: the header becomes interactive while the route boundary is still dehydrated. That is the #8198 window that #8576 closes, so #8576 should land first.

      2. Not really. The built-in lazyRouteComponent.preload never rejects. It stores the error and throws it on render, where a missing module reloads the page once and any other error goes to the route's error boundary. So hydrate() never caught those failures before either. What does change is the guarantee for a hand-written component: its preload is no longer awaited before the first render, so if it depends on that, it must suspend or handle the pending state in render. A failed .lazy() import still triggers a retry.

      3. Here is the breakdown:

      SetupBeforeNow
      Auto code splittingwaitsdoesn't wait
      Manual lazyRouteComponentwaitsdoesn't wait
      .lazy() / createLazyFileRoutewaits for all chunkswaits for its options only
      Custom preloadwaits, retries on rejectstarts it, doesn't wait
      ssr: 'data-only'waitspending UI stays until the chunk arrives (no mismatch)
      Root route, non-split, ssr: falseno changeno change
      1. Yes, both work now, so I removed _hydrateWithoutComponentChunks. Each one is covered by an SSR-then-hydrate test with a held chunk. Solid's lazy() already keeps the server DOM; our wrapper added an extra component level that broke the hydration keys, and that was a one-line fix. Vue's wrapper rendered an empty <div>, so it now uses defineAsyncComponent, which Vue hydrates only after the chunk loads. The Vue hydration test passes on Vue 3.3.4 and 3.5. The cost is about 0.8 kB gzipped for Vue apps that don't already use defineAsyncComponent.

      2. I did a cheap version: hydration now waits only for the lazy options module, not for every chunk in the lane. load-client ends up +10 B over main instead of +40 B. Scoping the wait to the route's subtree would need every adapter's Match to suspend on the lazy options, and Vue can't suspend on a thrown promise, so I'd leave that for a follow-up.

      I pushed:

      • Core: hydration waits only for unmerged lazy options.
      • Solid and Vue: lazyRouteComponent keeps the server HTML while its chunk loads.
      • SSR-then-hydrate tests for React, Solid and Vue.
      • _hydrateWithoutComponentChunks removed.
      • The commits are ordered core, React, Solid, Vue, flag removal, so the Vue part or the flag removal can be dropped if needed.

      The workflows need approval to run, since this is my first PR from this account.

    4. This still merges cleanly into main. I also checked it together with #8576, which I just rebased: I merged this branch into #8576 at 768bca8b1. With both changes, @tanstack/router-core and @tanstack/react-router test:unit exit 0 (3642 and 1244 tests). The #8198 reproducer also exits 0, with 0/6 navigations logging errors and the boundary still dehydrated at every click. On main alone, the reproducer fails 3/6.

      @Sheraff could you approve the workflow runs here too? CI has not run on either PR yet.

Sign in to join this conversation.