Hydration error on direct navigation to non-root routes in SPA mode #6455
Send to my agentWhich 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#
- Clone the reproduction repository
- Build the application:
pnpm build - Preview the build:
pnpm preview - Open browser and navigate directly to
/examplein the URL bar - Press Enter
- 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
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
bbertold(GitHub profile, opens in a new tab) changed the title
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
basepathto 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
basepathmust be set in two places, not one. Setting it only inrouter.tsxis not enough -- thetanstackStart()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#
Confirmed CloudFront was serving the correct
_shell.htmland JS bundles (viacurl).Confirmed the main JS bundle contained the demo route definitions (grep for
/demo/storybook).Confirmed the lazy-loaded route chunks were accessible via CloudFront (200 responses).
Confirmed CloudFront cache invalidations had completed.
Compared
vite preview(full SSR, 44KB per page, works) vs CloudFront (static shell, 19KB, broken).User reported no console errors -- ruling out chunk load failures or hydration crashes.
Traced the client-side initialization path through TanStack Start source:
default-entry/client.tsx → StartClient.tsx → hydrateStart.ts → ssr-client.tsFound 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.Traced where
TSS_ROUTER_BASEPATHgets 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-- thetanstackStart()plugin options, not fromrouter.tsx.Since the plugin config had no
router.basepath, the env var wasundefined, and the router's basepath was reset from'/myapp'toundefinedduring 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 devworked#The dev server runs full SSR for every request. Each page is rendered server-side with the correct route match. The basepath override in
hydrateStartstill 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
basepathin thetanstackStart()plugin config:// vite.config.ts tanstackStart({ router: { basepath: '/myapp', // <-- THIS is what sets TSS_ROUTER_BASEPATH }, spa: { enabled: true, }, })The basepath in
router.tsxis 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
basepathis only set inrouter.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-routeshows "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#
Config Purpose vite.config.tsbase: '/myapp/'Prefixes all asset URLs ( /myapp/assets/main.js)vite:config:plugin:tanstackStart({ router: { basepath: '/myapp' } })Sets TSS_ROUTER_BASEPATHenv var used during client hydrationcreateRouter({ basepath: '/myapp' })inrouter.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.
We hit React #418 with the same
args[]=HTMLfingerprint from a different trigger, on a plain SSR deployment — no SPA mode, no static-host fallback, Nitronode-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: falsewhosebeforeLoadthrowsredirect(), 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'srouter.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 fromrouter-core@1.171.13'sdist/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 loadPromiseOn the non-SPA
ssr: falsepath,loadPromiseis created and then nothing references it —hydrate()returnsrouteChunkPromise,hydrateStart()awaits only that, andStartClientrenders<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
_displayPendingisn'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 owntitle,metaandmodulepreloadlinks, so any route-level divergence at hydration time is an element mismatch. That's why it's #418args[]=HTMLand not #425args[]=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
beforeLoadthrowsredirect(); routes without a redirect never produced it, including our onlyssr: trueroute. Moving two such redirects out ofbeforeLoadinto 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
beforeLoaddoes remove the mismatch, but holding the route load open across that await means a superseded or invalidated load rejects into an unhandled continuation — uncaughtCancelledErrorwent 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-router1.170.16 ·@tanstack/router-core1.171.13 ·@tanstack/react-start1.168.32 ·@tanstack/start-client-core1.170.14 ·react/react-dom19.2.5 · Vite 8.0.16 · Nitronode-serverpreset.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 showargs[]=HTML. Since SPA mode already has the_displayPendingcoupling 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.
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.