We build OnScene, a live shopping app for Pakistan. Its marketing site, blog and policy pages are a Vite + React single-page app hosted on Firebase Hosting. For a long time every URL on it returned the same empty index.html. This post is about how we fixed that without migrating to Next.js: a build-time prerender step, a few build gates, and some Firebase Hosting configuration. It also covers the two bundling mistakes that bit us along the way.

The problem: one shell for every URL

A client-rendered SPA serves one HTML file for every route. That file has one <title>, one description, no <h1> and no body text. Googlebot renders JavaScript eventually, but plenty of consumers do not: Bing's indexing was inconsistent for us, most AI crawlers fetch raw HTML, and WhatsApp, X and LinkedIn link previews never run your JS. For all of them, our 30-odd public pages looked like one page repeated.

The usual answer is "move to Next.js or Astro". We didn't want to rewrite a working app, and the pages we cared about were static in nature (marketing, blog, policies). So we kept the SPA and added a step after vite build that turns each public route into a real static HTML file.

"build": "vite build && npm run prerender", "build:spa": "vite build", "prerender": "node scripts/sitemap-lastmod.mjs && node scripts/prerender.mjs" 

Prerendering with Playwright

The script is about 570 lines, but the idea is small:

  1. Save the untouched shell as dist/app.html with <meta name="robots" content="noindex">. Private and dynamic routes will be served from this later.
  2. Start a tiny static server over dist/. Anything extension-less returns the original shell, like a real SPA host.
  3. Read every <loc> in dist/sitemap.xml. Open each in headless Chromium and wait until the page has an <h1>, the title is no longer the shell's title, and no Suspense spinner is showing.
  4. Capture the rendered #root HTML plus the head tags, and write dist/<route>.html.

Two details made this safe to run on every build. First, all third-party requests are aborted, so the prerender can't fire analytics or touch Firebase:

await context.route("**/*", (r) => r.request().url().startsWith(origin) ? r.continue() : r.abort() ); await context.addInitScript(() => { window.__PRERENDER__ = true; }); 

Second, we capture head tags explicitly instead of trusting that "the DOM looks right". Our pages set title, meta, canonical, hreflang and JSON-LD from a useSEO hook, so after rendering we read those elements back, delete the template's copies from the shell, and write the rendered set. The hook updates elements in place on the client, so there are no duplicates after hydration. JSON-LD hoisted into <head> gets a data-prerender-head marker and is removed in main.tsx before React mounts, because the page re-creates it itself.

One pragmatic escape hatch: pages whose body depends on App Check and live Firestore data can't be meaningfully prerendered. Our auctions list is one. It's declared in a HEAD_ONLY_ROUTES map and gets its own title, description and self-canonical around the normal empty root. That's less than a full prerender, but it is honest and indexable.

Build gates that fail the build

The part that has paid for itself is the validation. A prerender that silently produces bad pages is worse than none. After rendering, every route is checked and the script exits non-zero on any failure:

function validate(route, data, shellTitle, seenTitles) { const problems = []; if (data.h1Count < 1) problems.push("no <h1>"); if (!data.title || data.title === shellTitle) problems.push("title not set by page"); if (seenTitles.has(data.title)) problems.push("duplicate title"); const expected = route === "/" ? `${SITE}/` : `${SITE}${route}`; if (data.canonicalResolved !== expected) problems.push("canonical mismatch"); if (/noindex/i.test(data.robots)) problems.push("noindexed but in the sitemap"); if (data.words < MIN_WORDS) problems.push(`only ${data.words} words`); return problems; } 

There's also a client-side redirect check (a sitemap URL that ends up on another path should be a 301 or removed from the sitemap) and a hreflang pass for our English/Urdu pairs. Google ignores one-way hreflang, so the script requires that every alternate is itself a prerendered page, that each page lists itself, and that targets link back. Title and description length only produce warnings. Everything else blocks the deploy. When someone adds a page and forgets the <h1> or copies another page's title, CI tells them before search engines do.

The script also reads public routes straight from App.tsx, so a page added to the router but missing from sitemap.xml is still prerendered (otherwise it would 404 on Firebase) and prints a warning.

A related small script, sitemap-lastmod.mjs, rewrites each <lastmod> in dist/sitemap.xml from the date the route's page file last changed in git. It keeps existing values on shallow clones, so CI checks out with fetch-depth: 0.

Avoiding the spinner flash on hydration

Prerendered HTML solves crawling but creates a UX trap. React's createRoot().render() replaces the static HTML. If the route component is a React.lazy import, the first render suspends and the user sees the full-screen Suspense fallback until the chunk arrives. The page appears, vanishes, and returns.

We swapped lazy for a thin wrapper that records which route components rendered. During prerender the ids are saved on the root element as data-lazy; on the client, the entry preloads exactly those chunks before the first render.

// src/lib/lazy-page.ts (trimmed) export function lazy(factory) { const id = hash(factory.toString()); let loaded = null, promise; const load = () => (promise ??= factory().then((m) => (loaded = m.default, m))); const Lazy = reactLazy(load); registry.set(id, { load }); return function LazyPage(props) { markRendered(id); // pushes to window.__LAZY_RENDERED__ const [Impl] = useState(() => loaded ?? Lazy); return createElement(Impl, props); }; } 
// src/main.tsx (trimmed) const ids = (container.dataset.lazy || "").split(",").filter(Boolean); if (ids.length) preloadLazy(ids).then(() => root.render(<App />)); else root.render(<App />); 

Because ids are a hash of the factory's source and the prerender runs against the same production bundle, they match on both sides. We chose the implementation once per mount with useState so the element type never changes under a mounted page. In our own testing, React mounted without a spinner on the pages we checked, and a deliberate negative control (preloading disabled) did show the flash.

Firebase Hosting: URLs, 404s, redirects and the app shell

With static files in dist/, the hosting config does the rest:

{ "hosting": { "cleanUrls": true, "trailingSlash": false, "redirects": [ { "source": "/privacy-policy", "destination": "/privacy", "type": 301 } ], "rewrites": [ { "source": "/auction/**", "destination": "/app.html" }, { "source": "/profile/**", "destination": "/app.html" } ] } } 
  • cleanUrls serves blog/x.html at /blog/x and redirects /x.html to /x; trailingSlash: false normalises /x/.
  • The classic SPA rule, a catch-all ** -> /index.html rewrite, is gone. It is what turns every typo into a "200 OK" soft 404. Without it, unknown URLs fall through to a 404.html that the prerender also generates (from a probe route that renders our not-found page, checked to have an <h1> and noindex), and Firebase serves it with a real 404 status.
  • Dynamic and private routes (auctions, profiles, streams) are rewritten to app.html, the noindex shell. They still work as an app; they just don't ask to be indexed.
  • Legacy URLs are 301s in redirects, evaluated server-side, not React Router Navigate components.
  • HTML paths are served with max-age=0, must-revalidate, so a deploy never serves a page pointing at a JS chunk that no longer exists. JS, CSS, images and fonts get max-age=31536000, immutable, which matters for the last section.

The manualChunks cycle bug

Earlier performance work had us hand-tuning manualChunks to keep heavy libraries (three.js, recharts) off ordinary pages. Our first version used the object form, listing packages per chunk. That pulled shared helpers (React's createRoot, Vite's preload helper, clsx, the JSX runtime) into the heavy chunks, so every page downloaded roughly 1.3 MB it didn't need. Separately, forcing Firebase's wrapper package into one manual chunk created an import cycle between chunks. Cycles across chunks are how you get "Cannot access 'x' before initialization" style temporal-dead-zone errors at load time, and for us the symptom was a blank page. We reverted to simpler splitting once, then redid it properly.

The version that works uses the function form, assigns only big self-contained libraries, and leaves Firebase to Rollup's automatic splitting:

manualChunks(id) { if (id.includes("vite/preload-helper") || id.includes("commonjsHelpers")) return "react-vendor"; if (!id.includes("node_modules")) return undefined; const pkg = /* last node_modules/<pkg> segment of id */; if (["react", "react-dom", "scheduler", "clsx", "@babel/runtime"].includes(pkg)) return "react-vendor"; if (pkg === "three" || pkg === "three-stdlib" || pkg.startsWith("@react-three/")) return "three-vendor"; if (["recharts", "recharts-scale", "victory-vendor"].includes(pkg)) return "recharts-vendor"; return undefined; } 

The @babel/runtime line is a real follow-up fix: one of its helpers landed in recharts-vendor, which made the homepage's three.js chunk import recharts. If a heavy chunk appears on a page that shouldn't need it, check which tiny shared module Rollup tucked into it. Always load-test a production build (vite preview) after touching this; the dev server hides these problems.

Font subsetting behind a versioned path

We subset our self-hosted fonts to Latin plus symbols, which cut Inter from about 110 KB to about 26 KB per weight. Preloading the three faces used above the fold, plus inlined @font-face, fixed a layout shift on blog pages caused by late font loading.

The catch: those files were served with a one-year immutable cache, and a CDN in front of the origin kept serving the old, large files at the same URLs. You cannot purge your way out of immutable in users' browsers either. The fix is boring and reliable: change the URL. The subset files moved from /fonts/ to /fonts/v2/, and fonts.css and the preload tags point there. Treat the path as the cache key.

What we would tell you before you start

  • Prerendering a SPA is viable when pages are mostly static. If your content is per-user or live, serve a head-only page or leave it as an app route.
  • The build gates matter more than the renderer. Make the build fail on missing H1s, duplicate titles, wrong canonicals and noindex-in-sitemap.
  • Keep crawler-facing 404s honest at the hosting layer, not in React.
  • Verify with raw HTML (curl), not just a browser. If it isn't in the response body, many crawlers will never see it.

None of this needs a framework migration, only a script, a config file and some discipline. If you are curious about the product behind the pages, we are building OnScene for live shopping in Pakistan.