Bugfix: TanStack Router Compatibility
Deep fix for replaceState and invariant errors in a hybrid AI Studio + Cloudflare architecture.
TanStack Router Compatibility Fixes for Hybrid Architecture
For the "AI Studio Dev + Cloudflare Pages Prod" hybrid architecture, to solve the replaceState error (Origin mismatch) and the invariant export error, we need to optimize for TanStack Router's compatibility.
Here is the deep fix solution for this architecture:
1. Modify src/main.tsx: Force Hash Routing
In AI Studio's blob: preview environment, the browser prohibits modifying the History Origin. We must use code logic to detect the environment and forcibly enable HashHistory in non-production environments.
typescriptimport { createRouter, createHashHistory, createBrowserHistory } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' // Detect if in AI Studio's Blob preview or local dev const isSandbox = window.location.protocol === 'blob:' || window.location.hostname.includes('usercontent.goog'); // Critical Fix: Force Hash mode in preview, Browser mode in Cloudflare production const history = isSandbox ? createHashHistory() : createBrowserHistory(); const router = createRouter({ routeTree, history, basepath: '/', })
2. Solve invariant Export Error
The invariant error usually occurs because the CDN version in importmap is inconsistent with the module version processed by the local build toolchain (Vite).
Solution A (Recommended): Completely remove Importmap from HTML
Since you have decided to adopt the "build-time cleaning" strategy and added <script type="module" src="/src/main.tsx"></script> in index.html, the importmap is completely unnecessary. Vite will automatically handle dependencies from node_modules.
Action: Completely delete the <script type="importmap"> and its content from index.html.
3. Enhanced vite.config.ts (Module Compatibility)
To ensure the production build does not include any residual preview logic and to solve possible module resolution issues:
typescript// vite.config.ts const htmlPlugin = () => { return { name: 'html-transform', transformIndexHtml(html, { command }) { if (command !== 'serve') { return html // Enhanced matching: ensure complete removal of importmap .replace(/<script type="importmap">[\s\S]*?<\/script>/g, '') // Remove preview-specific config scripts .replace(/<script>tailwind\.config[\s\S]*?<\/script>/g, ''); } return html; }, } }
4. Final Step for Production: Cloudflare Redirect
Since the production environment (Cloudflare Pages) uses BrowserHistory (pretty URLs), when you refresh a page (like /about), Cloudflare will report a 404.
Solution: Create a file named _redirects in the project root (or public) directory:
text/* /index.html 200
This ensures all paths point to index.html, to be handled by TanStack Router.