Hydration error on direct navigation to non-root routes in SPA mode
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
- 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
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.
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
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
-
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.ts -
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. -
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 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-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.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.tsx |
Used 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[]=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 [email protected]'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.
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.