Skip to content
Source
Sign inSign up
TanStack/router

Hydration error on direct navigation to non-root routes in SPA mode #6455

Send to my agent
Openbbertold(GitHub profile, opens in a new tab) opened this issue 5 comments

Which project does this relate to?

Start

Describe the bug

When deploying a TanStack Start application with spa mode enabled to Cloudflare, directly navigating to a non-root route (e.g., /example) results in a React hydration error. The same route works correctly when accessed via client-side navigation (e.g., clicking a <Link> from /).

On direct navigation to a non-root route, React throws a hydration mismatch error and the page visibly flashes:

Hydration failed because the server rendered HTML didn't match the client. 
As a result this tree will be regenerated on the client.

Error reference: https://react.dev/errors/418?args[]=HTML&args[]=

This issue appears to be directly related to Cloudflare's SPA handling configuration:

"not_found_handling": "single-page-application"

Your Example Website or App

https://github.com/bbertold/tanstack-start-spa

Steps to Reproduce the Bug or Issue

  1. Clone the reproduction repository
  2. Build the application: pnpm build
  3. Preview the build: pnpm preview
  4. Open browser and navigate directly to /example in the URL bar
  5. Press Enter
  6. Observe the hydration error in console and visible flash of content

Expected behavior

The page should load without hydration errors.

Screenshots or Videos

No response

Platform

  • Router / Start Version: 1.154.8
  • OS: macOS
  • Browser: Chrome (144.0.7559.59)
  • Bundler: Vite (7.1.7)
  • Wrangler version: 4.60.0

Additional context

No response

  1. I'm facing the same error, with caddy as a server. Only happens, as @bbertold says, wen navigating directly to a child route, not on client side navigation.

  2. Hi @bbertold and @pablor21!

    I've been looking into this issue and recently submitted a PR (#6481) that I hope might help resolve this.

    From my analysis, it seems the root cause is that in SPA mode, servers (like Cloudflare or Caddy) serve the root index.html (the shell) for all direct navigations to child routes. React then tries to hydrate this root HTML as if it were the specific child route's content, which causes the mismatch error and the visible flash.

    In the PR, I've proposed a small fix that:

    Injects a marker (window.TSS_SPA_SHELL) into the SPA shell during build. Note: I adopted the window.TSS_* naming convention already used in the codebase (e.g., window.__TSS_START_OPTIONS) to ensure consistency with the existing architecture. Allows the client to detect this marker and safely skip hydration if the path doesn't match, performing a fresh client-side render instead. This approach should be server-agnostic, addressing the issues reported for both Cloudflare and Caddy setups.

    Thank you

  3. bbertold(GitHub profile, opens in a new tab) changed the title

  4. ran into something similar with s3 hosting and working with the local dev server


    TanStack Start SPA: Basepath Silently Overridden During Hydration

    Summary

    When deploying a TanStack Start SPA with a non-root basepath to static hosting (S3 + CloudFront), all sub-routes show "Not Found" despite:

    • No JavaScript errors in the browser console
    • The root page (/) rendering correctly
    • All assets loading successfully (200 responses)
    • The route tree containing the correct route definitions

    The root cause is that basepath must be set in two places, not one. Setting it only in router.tsx is not enough -- the tanstackStart() plugin config must also declare it, because the client hydration code overwrites the router's basepath with a build-time environment variable.

    How It Was Discovered

    Debugging timeline

    1. Confirmed CloudFront was serving the correct _shell.html and JS bundles (via curl).

    2. Confirmed the main JS bundle contained the demo route definitions (grep for /demo/storybook).

    3. Confirmed the lazy-loaded route chunks were accessible via CloudFront (200 responses).

    4. Confirmed CloudFront cache invalidations had completed.

    5. Compared vite preview (full SSR, 44KB per page, works) vs CloudFront (static shell, 19KB, broken).

    6. User reported no console errors -- ruling out chunk load failures or hydration crashes.

    7. Traced the client-side initialization path through TanStack Start source:

      default-entry/client.tsx → StartClient.tsx → hydrateStart.ts → ssr-client.ts
    8. Found the critical line in hydrateStart.ts (in @tanstack/start-client-core):

      // node_modules/@tanstack/start-client-core/src/client/hydrateStart.ts, line 34
      router.update({
        basepath: process.env.TSS_ROUTER_BASEPATH,
        ...{ serializationAdapters },
      })

      This unconditionally overwrites the router's basepath with the build-time env var TSS_ROUTER_BASEPATH.

    9. Traced where TSS_ROUTER_BASEPATH gets its value:

      // node_modules/@tanstack/start-plugin-core/src/plugin.ts, line 302
      ...defineReplaceEnv('TSS_ROUTER_BASEPATH', startConfig.router.basepath),

      It comes from startConfig.router.basepath -- the tanstackStart() plugin options, not from router.tsx.

    10. Since the plugin config had no router.basepath, the env var was undefined, and the router's basepath was reset from '/myapp' to undefined during hydration. With no basepath, the router couldn't match any URL under /myapp/*.

    Why the root page still worked

    The SPA shell is prerendered at the maskPath (/). When loaded at /myapp/, the router tries to match. Without a basepath, it sees the full pathname /myapp/ and matches no route -- but the prerendered HTML already shows the dashboard layout, so the page appears to work. Only when navigating to a sub-route (where the prerendered HTML doesn't match) does the "Not Found" become visible.

    Why vite dev worked

    The dev server runs full SSR for every request. Each page is rendered server-side with the correct route match. The basepath override in hydrateStart still happens, but since the SSR-rendered HTML already contains the correct route content, the mismatch isn't visible -- the page looks correct even if client-side routing silently breaks.

    The Fix

    Set basepath in the tanstackStart() plugin config:

    // vite.config.ts
    tanstackStart({
      router: {
        basepath: '/myapp',   // <-- THIS is what sets TSS_ROUTER_BASEPATH
      },
      spa: {
        enabled: true,
      },
    })

    The basepath in router.tsx is still needed for type-safe route definitions and dev-time behavior:

    // src/router.tsx
    export function getRouter() {
      const router = createTanStackRouter({
        routeTree,
        basepath: '/myapp',   // <-- still needed for route generation & types
        // ...
      })
      return router
    }

    Minimal Reproducible Example

    A TanStack Start SPA deployed to a subpath will silently break sub-route navigation if basepath is only set in router.tsx.

    Broken configuration

    // vite.config.ts -- BROKEN: basepath missing from plugin config
    export default defineConfig({
      base: '/myapp/',
      plugins: [
        tanstackStart({
          spa: { enabled: true },
          // router.basepath is NOT set here
        }),
      ],
    })
    
    // src/router.tsx
    export function getRouter() {
      return createRouter({
        routeTree,
        basepath: '/myapp',  // set here, but overwritten during hydration
      })
    }

    Result: After building and deploying to static hosting at /myapp/:

    • /myapp/ renders the prerendered shell (appears to work)
    • /myapp/any-route shows "Not Found" (basepath was reset to undefined)
    • No JavaScript errors in console

    Working configuration

    // vite.config.ts -- FIXED: basepath in both places
    export default defineConfig({
      base: '/myapp/',
      plugins: [
        tanstackStart({
          router: {
            basepath: '/myapp',  // sets TSS_ROUTER_BASEPATH at build time
          },
          spa: { enabled: true },
        }),
      ],
    })
    
    // src/router.tsx
    export function getRouter() {
      return createRouter({
        routeTree,
        basepath: '/myapp',  // still needed for route generation
      })
    }

    Three places basepath must be configured

    ConfigPurpose
    vite.config.ts base: '/myapp/'Prefixes all asset URLs (/myapp/assets/main.js)
    vite:config:plugin:tanstackStart({ router: { basepath: '/myapp' } })Sets TSS_ROUTER_BASEPATH env var used during client hydration
    createRouter({ basepath: '/myapp' }) in router.tsxUsed by the route generator and during SSR/dev

    If any one of these is missing, the app will partially break in ways that are difficult to diagnose because the symptoms differ between dev, preview, and static hosting.

  5. We hit React #418 with the same args[]=HTML fingerprint from a different trigger, on a plain SSR deployment — no SPA mode, no static-host fallback, Nitro node-server. Posting the analysis here rather than opening a second issue because I think it points at a common denominator that's relevant to how #6481 gets designed. Happy to split it out with a proper reproducer if you'd rather track it separately.

    The other way to get here

    A route with ssr: false whose beforeLoad throws redirect(), loaded directly (not via <Link>). The server renders that route's HTML correctly — this isn't a case of the wrong document being served — but the client's router.load() resolves the redirect and moves to the destination route before React commits hydration. React then hydrates the destination route's tree against the origin route's server HTML.

    In hydrate() (packages/router-core/src/ssr/ssr-client.ts, read from router-core@1.171.13's dist/esm/ssr/ssr-client.js):

    const isSpaMode = matches[matches.length - 1].id !== lastMatchId;
    if (!matches.some((m) => m.ssr === false) && !isSpaMode) {
      return routeChunkPromise;                                   // clean path
    }
    const loadPromise = Promise.resolve().then(() => router.load()).catch(...);
    if (isSpaMode) {
      setMatchForcePending(match);
      match._displayPending = true;
      match._nonReactive.displayPendingPromise = loadPromise;      // coupled — SPA only
      loadPromise.then(() => { /* clears it */ });
    }
    return routeChunkPromise;                                      // not loadPromise

    On the non-SPA ssr: false path, loadPromise is created and then nothing references it — hydrate() returns routeChunkPromise, hydrateStart() awaits only that, and StartClient renders <Await promise={hydrationPromise}>. So React starts hydrating while a redirect may still be in flight.

    The bit that seems to matter for #6481

    My first instinct was "give the non-SPA path the coupling SPA mode already has." Reading this issue talked me out of it — SPA mode has that coupling and still reports #418, which is fairly strong evidence _displayPending isn't what prevents the mismatch.

    What both cases have in common is the <head>. Bodies often agree — both routes fall back to the same pending element — but every route contributes its own title, meta and modulepreload links, so any route-level divergence at hydration time is an element mismatch. That's why it's #418 args[]=HTML and not #425 args[]=text, in both reports. Measured on ours, anonymous visitor, / → /login: 25 head tags vs 29 (an extra <meta name="robots">, a different description, 4 modulepreloads against 1).

    Concretely for #6481: keying on window.__TSS_SPA_SHELL__ fixes "the server served the shell", but wouldn't apply to our case — the server served the correct route, so no marker would be present. If the goal is one mechanism for both, the invariant looks less like "did the server serve the shell" and more like "is the route the client is about to render the same one the server rendered", checked before hydrating.

    Data, in case it's useful

    Across 12 retained Playwright traces containing #418, every one was a hard load of a route whose beforeLoad throws redirect(); routes without a redirect never produced it, including our only ssr: true route. Moving two such redirects out of beforeLoad into post-mount effects took the suite from 48 occurrences to 0 with no other change.

    It's timing-dependent, which is why we have no minimal reproducer: on an idle dev machine the redirect lands at ~751ms and React commits at ~429ms, so it never fires. On a GitHub runner with 3 Playwright workers it inverts — redirect ~1153ms, commit ~1597ms — and becomes fully deterministic, failing on chromium, firefox, webkit and mobile WebKit on both the initial attempt and the retry.

    One workaround worth warning about: awaiting a "hydration committed" promise at the top of beforeLoad does remove the mismatch, but holding the route load open across that await means a superseded or invalidated load rejects into an unhandled continuation — uncaught CancelledError went from 0 to 284 in our suite, taking the run from 2 failures to 33. That escaping rather than being swallowed may be worth a look on its own.

    Environment

    @tanstack/react-router 1.170.16 · @tanstack/router-core 1.171.13 · @tanstack/react-start 1.168.32 · @tanstack/start-client-core 1.170.14 · react/react-dom 19.2.5 · Vite 8.0.16 · Nitro node-server preset.

  6. Followed up on the above with a minimal reproducer and filed it separately as #7947, since the trigger is different enough (no SPA fallback — the server renders the correct route and the client leaves it before hydration commits) that it probably wants its own thread.

    Repro: https://github.com/timothytn/tanstack-start-beforeload-redirect-hydration — two routes, no delays or throttling, with the direct load of the destination as a control.

    One result from building it that bears on this issue: the reproduction fires with byte-identical bodies. Both routes render nothing on the server, so the <head> alone is enough — 4 tags against 6. That is why both reports show args[]=HTML. Since SPA mode already has the _displayPending coupling and still produces #418 here, a fix that only controls which fallback renders may not be sufficient for either case.

Sign in to join this conversation.