fix(start): handle Cloudflare SPA fallback hydration mismatch #6481
main fromrefs/pull/6481/head·opened Problem#
When deploying a TanStack Start application to Cloudflare Pages with SPA mode enabled, directly navigating to non-root routes (e.g., /example) causes React hydration errors.
Root Cause:
- Cloudflare's SPA fallback serves
index.html(app shell) for all routes - Client expects to hydrate the deep route (e.g.,
/example) - Server HTML contains the root shell content
- Mismatch causes hydration error and visible content flash Reproduction: See Issue #6455 and <https://github.com/bbertold/tanstack-start-spa>
Solution#
Implemented a two-part fix:
1. Build-time Marker Injection (start-plugin-core)#
- Inject
window.__TSS_SPA_SHELL__ = trueinto the SPA shell during prerendering - Only applied to the shell file (identified by
spa.prerender.outputPath) - Robust injection with fallback: tries
</head>first, then<body>if not found
2. Client-side Detection (start-client-core)#
- Check for
__TSS_SPA_SHELL__marker before hydration - If marker exists AND current path ≠ basepath, skip server hydration
- Let RouterProvider mount the router freshly (client render)
This fix is server-agnostic and will resolve similar hydration issues on servers like Caddy, Nginx, or Vercel when configured for SPA fallback 😄 👍
Testing#
Unit Tests (11 new tests)#
- Normal hydration scenarios (no marker, root path)
- SPA shell fallback detection (deep links, trailing slashes)
- Custom basepath handling (3 scenarios)
- Existing matches handling (2 scenarios)
- Router configuration verification (2 tests) All tests passing ✅
Summary by CodeRabbit#
New Features
- SPA shell support: client now conditionally skips or performs hydration based on a runtime SPA-shell marker and the current URL path (respecting basepath).
- Prerender now injects a SPA-shell marker into HTML to enable the above behavior.
Tests
- Added comprehensive tests covering hydration fallback scenarios, basepath handling, existing router matches, and adapter merging.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-plugin-core
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-client-core
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/start-client-core/src/client/hydrateStart.ts`: - Around line 45-55: The pathname equality check in hydrateStart.ts can fail when routes differ only by a trailing slash; update the condition that compares window.location.pathname to router.options.basepath to use the router path normalization utilities (e.g., call removeTrailingSlash or use exactPathTest from path.ts) so "/app" and "/app/" are treated as equal, and ensure you reference window.__TSS_SPA_SHELL__, router.options.basepath and hydrate(router) when making the change; also add a unit/integration test that asserts the logic skips hydration for window.location.pathname = "/app/" when router.options.basepath = "/app" to prevent regressions.🧹 Nitpick comments (3)
packages/start-plugin-core/src/prerender.ts (1)
239-259: SPA shell marker injection logic is sound overall, but the fallback placement is outside<body>.The
</head>injection is correct. However, the fallback on lines 250-256 places the script before the<bodytag (between</head>and<body>), not "at the beginning of body" as the comment states. While browsers tolerate this, for semantic correctness the script should be injected inside the body element.Additionally, using a regex for the
<body>fallback would be more robust for matching variants like<body class="...">.♻️ Optional: Inject inside body element with regex matching
} else { - // Fallback: inject at the beginning of body if </head> not found - const bodyOpenTag = '<body' - if (html.includes(bodyOpenTag)) { - html = html.replace( - bodyOpenTag, - '<script>window.__TSS_SPA_SHELL__ = true</script>' + - bodyOpenTag, - ) - } + // Fallback: inject at the beginning of body if </head> not found + html = html.replace( + /<body[^>]*>/i, + (match) => match + '<script>window.__TSS_SPA_SHELL__ = true</script>', + ) }packages/start-client-core/tests/hydrateStart.test.ts (2)
47-59: Redundant initialization check in beforeEach.Lines 50-52 check
if (!mockGetRouter)before initializing, but the module-level mocks on lines 27-45 already use a getter with lazy initialization. This check is never true at this point since the mocks ensuremockGetRouteris initialized on first access.♻️ Remove redundant check
beforeEach(() => { - // Ensure mockGetRouter is initialized - if (!mockGetRouter) { - mockGetRouter = vi.fn(() => Promise.resolve(createMockRouter())) - } - vi.clearAllMocks() delete window.__TSS_SPA_SHELL__ delete window.__TSS_START_OPTIONS__ window.history.pushState({}, '', '/') mockGetRouter.mockResolvedValue(createMockRouter()) })
100-136: Consider adding a test for basepath trailing slash mismatch.The custom basepath tests cover exact matches and deeper paths, but don't cover the edge case where basepath and pathname differ only by a trailing slash (e.g., basepath
/appvs pathname/app/). This aligns with the potential issue in the implementation's strict equality comparison.📋 Suggested additional test case
it('should handle trailing slash mismatch between basepath and pathname', async () => { window.__TSS_SPA_SHELL__ = true window.history.pushState({}, '', '/app/') // trailing slash mockGetRouter.mockResolvedValueOnce(createMockRouter({ options: { basepath: '/app' } // no trailing slash })) await hydrateStart() // Current behavior: these don't match, so hydration is skipped // If trailing slash normalization is added, this should hydrate expect(hydrate).not.toHaveBeenCalled() })@@ -36,4 +42,14 @@3642 ...{ serializationAdapters },3743 })3844 if (!router.state.matches.length) {39- await hydrate(router)45+ if (46+ window.__TSS_SPA_SHELL__ &&47+ window.location.pathname !== (router.options.basepath || '/')48+ ) {49+ // If we are loading the SPA shell (index.html) and the path is not the root,50+ // it means we are in a fallback scenario (e.g. Cloudflare SPA fallback).51+ // The server-rendered content (Shell) will not match the client-side expected content (Deep Link).52+ // We skip hydration and let the RouterProvider mount the router freshly (Client Render).53+ } else {54+ await hydrate(router)55+ }⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Search for basepath usage in the codebase to understand normalization patterns rg -n 'basepath' packages/start-client-core/src/ packages/router-core/src/ --type ts --type tsx -C 2 | head -100Repository: TanStack/router
Length of output: 86
🏁 Script executed:
#!/bin/bash # Look for any path normalization utilities in the codebase rg -n 'normalize|trailing|slash' packages/router-core/src/ packages/start-client-core/src/ --type ts --type tsx | grep -i 'function\|const.*=.*=>\|path\|slash' | head -50Repository: TanStack/router
Length of output: 86
🏁 Script executed:
#!/bin/bash # Check how window.location.pathname is compared in the codebase rg -n 'window\.location\.pathname' packages/start-client-core/src/ packages/router-core/src/ --type ts --type tsx -C 3 | head -80Repository: TanStack/router
Length of output: 86
🏁 Script executed:
#!/bin/bash # Look at the hydration logic more broadly and SPA shell handling rg -n '__TSS_SPA_SHELL__' --type ts --type tsx -C 5Repository: TanStack/router
Length of output: 86
🏁 Script executed:
#!/bin/bash # Check if there's any basepath normalization in router initialization or options rg -n 'basepath.*||.*\/' packages/router-core/src/ packages/start-client-core/src/ --type ts --type tsx -C 1Repository: TanStack/router
Length of output: 155
🏁 Script executed:
#!/bin/bash # Search for basepath usage without tsx type filter rg -n 'basepath' packages/start-client-core/src/ packages/router-core/src/ -C 2 | head -120Repository: TanStack/router
Length of output: 8709
🏁 Script executed:
#!/bin/bash # Look for path normalization utilities rg -n 'normalize|trailingSlash|slash' packages/router-core/src/ packages/start-client-core/src/ | grep -iE '(function|const|export)' | head -50Repository: TanStack/router
Length of output: 1099
🏁 Script executed:
#!/bin/bash # Check window.location.pathname comparisons rg -n 'window\.location\.pathname' packages/start-client-core/src/ packages/router-core/src/ -C 3 | head -100Repository: TanStack/router
Length of output: 778
🏁 Script executed:
#!/bin/bash # Look at SPA shell handling rg -n '__TSS_SPA_SHELL__' -C 5Repository: TanStack/router
Length of output: 11316
🏁 Script executed:
#!/bin/bash # Check basepath usage patterns with proper escaping rg -n 'basepath.*=|basepath.*!=' packages/router-core/src/ packages/start-client-core/src/ -C 1Repository: TanStack/router
Length of output: 1096
🏁 Script executed:
#!/bin/bash # Check full path normalization in router initialization sed -n '1085,1100p' packages/router-core/src/router.tsRepository: TanStack/router
Length of output: 602
🏁 Script executed:
#!/bin/bash # Look at path.ts to understand exact trailing slash handling cat -n packages/router-core/src/path.ts | sed -n '40,75p'Repository: TanStack/router
Length of output: 1403
🏁 Script executed:
#!/bin/bash # Check if there are any tests for trailing slash with basepath rg -n 'basepath.*\/' packages/start-client-core/tests/ -A 2 -B 2Repository: TanStack/router
Length of output: 147
🏁 Script executed:
#!/bin/bash # Search for basepath tests with trailing slash variations rg -n 'basepath.*app' packages/start-client-core/tests/ -A 3 -B 1Repository: TanStack/router
Length of output: 927
🏁 Script executed:
#!/bin/bash # Check the full hydrateStart.ts file to understand the context better cat -n packages/start-client-core/src/client/hydrateStart.tsRepository: TanStack/router
Length of output: 2619
🏁 Script executed:
#!/bin/bash # Verify what router.basepath contains vs router.options.basepath rg -n 'this\.basepath\s*=' packages/router-core/src/router.ts -B 2 -A 2Repository: TanStack/router
Length of output: 459
🏁 Script executed:
#!/bin/bash # Check if exactPathTest is exported and available for use rg -n 'export.*exactPathTest' packages/router-core/src/Repository: TanStack/router
Length of output: 125
🏁 Script executed:
#!/bin/bash # Look at how the basepath value flows through the code after router.update() sed -n '40,60p' packages/start-client-core/src/client/hydrateStart.tsRepository: TanStack/router
Length of output: 755
🏁 Script executed:
#!/bin/bash # Check if there's any trimPath usage for basepath normalization rg -n 'trimPath' packages/router-core/src/path.ts -B 1 -A 3Repository: TanStack/router
Length of output: 696
🏁 Script executed:
#!/bin/bash # Check how rewriteBasepath normalizes basepath sed -n '23,60p' packages/router-core/src/rewrite.tsRepository: TanStack/router
Length of output: 1366
🏁 Script executed:
#!/bin/bash # Verify that there are NO tests for /app/ pathname vs /app basepath rg -n "pushState.*app" packages/start-client-core/tests/hydrateStart.test.tsRepository: TanStack/router
Length of output: 170
🏁 Script executed:
#!/bin/bash # Check what router.basepath actually contains after router.update() # Let me see the full router update flow sed -n '990,1100p' packages/router-core/src/router.ts | head -60Repository: TanStack/router
Length of output: 1986
🏁 Script executed:
#!/bin/bash # Verify the exact behavior difference between router.basepath and router.options.basepath rg -n 'router\.basepath|router\.options\.basepath' packages/start-client-core/src/client/hydrateStart.tsRepository: TanStack/router
Length of output: 129
Use path normalization for basepath comparison to handle trailing slash variations.
The pathname comparison at this location can fail with equivalent paths that differ only in trailing slashes. For example, if
basepathis/appbut the user navigates to/app/, the strict equality check fails and hydration proceeds incorrectly.The router codebase already provides path normalization utilities (
removeTrailingSlash,exactPathTestinpath.ts). Use one of these to ensure equivalent paths are recognized correctly:+const normalizePath = (p: string) => p.replace(/\/+$/, '') || '/' + if (!router.state.matches.length) { if ( window.__TSS_SPA_SHELL__ && - window.location.pathname !== (router.options.basepath || '/') + normalizePath(window.location.pathname) !== normalizePath(router.options.basepath || '/') ) {Additionally, add a test case for pathname
/app/againstbasepath: '/app'to prevent regression.🤖 Prompt for AI Agents
In `@packages/start-client-core/src/client/hydrateStart.ts` around lines 45 - 55, The pathname equality check in hydrateStart.ts can fail when routes differ only by a trailing slash; update the condition that compares window.location.pathname to router.options.basepath to use the router path normalization utilities (e.g., call removeTrailingSlash or use exactPathTest from path.ts) so "/app" and "/app/" are treated as equal, and ensure you reference window.__TSS_SPA_SHELL__, router.options.basepath and hydrate(router) when making the change; also add a unit/integration test that asserts the logic skips hydration for window.location.pathname = "/app/" when router.options.basepath = "/app" to prevent regressions.✅ Addressed in commit 5bfbb56
why do we need this? what exactly is mismatching here? we should already handle this correctly in router IMO
I debugged this with a minimal repro I made on the latest version v1.157.16: https://github.com/bbertold/tanstack-start-spa. The problem is that with SPA mode in Start and Cloudflare, the same HTML is served for all routes. When loading any route, the HTML contains:
matches: [ { i: "__root__/", ... }, { i: "//", ... } ],This causes
router.state.matches.lengthto be truthy all the time, so the existing check passes and hydration proceeds even when the current route is not/. This leaves the router attempting to hydrate the non-root route with root route content. This is the mismatch, you can see the visual flash of the root content before correction (especially with dev tools CPU slowdown). The issue is that the current check only verifies matches exist, not whether they match the current URL. This also explains why client-side navigation is unaffected.
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
Adds SPA-shell detection and a global
window.__TSS_SPA_SHELL__marker; hydration in the client start is now skipped when the marker is present and the current trimmed path differs from the router basepath. The prerender step injects the marker script into generated HTML when SPA shell mode is enabled.Changes#
packages/start-client-core/src/client/hydrateStart.tsWindow.__TSS_SPA_SHELL__declaration and changes hydration flow to skip SSR hydration when the SPA-shell marker is true and the current trimmed path is deeper than the router basepath.packages/start-client-core/tests/hydrateStart.test.tspackages/start-plugin-core/src/prerender.tswindow.__TSS_SPA_SHELL__ = trueinto prerendered HTML (before</head>or after<body>fallback) whenisSpaShellis enabled.Sequence Diagram#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs#
hydrateStart.ts, directly related to hydration behavior.Suggested reviewers#
Poem#
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
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