Converting a React + Vite SPA to SSG on Cloudflare Pages with Playwright (Without Causing 5xx Errors)
React + Vite SPA to SSG on Cloudflare Pages with Playwright · Jason Guo · 2026-11-25 · Cloudflare Pages, React, Vite, Playwright, Technical SEO
If you deploy a React + Vite Single Page Application (SPA) to Cloudflare Pages, search crawlers and SEO audit tools often see an empty <div id="root"></div> . Even when Googlebot eventually renders JavaScript, tools like Ahrefs, Bing, and AI search crawlers frequently miss internal links and flag half your site as orphan pages. That was the exact problem on WindFlash AI . Instead of rewriting the entire portfolio in Next.js or Astro, I kept React + Vite and built a Playwright static prerender pipeline on Cloudflare Pages , paired with Pages Functions middleware for live content refreshes. The architecture worked—until a Google Search Console (GSC) audit revealed 22 server errors ( 5xx ) , a stalled sitemap, a 2.5s HTML TTFB, and a 75/100 On-Page SEO score caused by subtle prerendering bugs. This post is the complete technical walkthrough of how the React + Vite to SSG pipeline works in production, every trap I hit along the way, and the exact fixes that eliminated 5xx crawl failures and pushed the homepage On-Page SEO score from 75 (C) to 94 (A) . Why Prerender a React + Vite SPA Instead of Migrating Frameworks? Before writing a custom prerenderer, it is worth asking whether you should simply migrate to Next.js, Astro, or Remix. For a new content-heavy site, Astro or Next.js is usually the right choice. For an existing React + Vite app with heavy client-side interactivity—in my case, a custom 2D canvas wind engine, audio player, gallery darkroom mode, and React Query data layer—a full framework rewrite carries real migration risk. Build-time Playwright prerendering gives you a pragmatic middle ground: Zero framework rewrite : Keep React 19, Vite, React Router, and React Query intact. Crawler-ready HTML on first byte : Every public URL ships as its own dist/<route>/index.html file with real copy, headings, canonicals, JSON-LD, and internal links. CDN cacheability : Cloudflare Pages serves static HTML directly from the edge without cold-starting a Node.js SSR server. Keep createRoot instead of hydrateRoot : Because the client immediately re-fetches via React Query, using createRoot avoids noisy React hydration mismatches while still giving crawlers complete static HTML. Architecture Overview: Build-Time SSG + Edge Middleware Our production setup combines three layers: Vite client bundle ( vite build ) : Produces dist/index.html and hashed JS/CSS assets. Playwright prerenderer ( scripts/prerender.ts ) : Starts a local HTTP server over dist/ , proxies /api/* requests to production, visits every static and dynamic route in headless Chromium, and writes the rendered DOM to dist/<route>/index.html . Cloudflare Pages Functions ( functions/_middleware.ts & functions/articles/[slug].ts ) : Enforces canonical trailing-slash URLs ( 308 ), injects security headers/CSP, and refreshes dynamic article lists from our headless CMS (InMind CMS) without requiring a full rebuild on every post. (If you are curious how the multi-source CMS API itself is structured, I covered that in When Your Blog Has Two Brains: Merging Multiple Content Sources Into One API .) Step 1: The Playwright Prerender Script Without Hanging on networkidle The first problem every developer hits when prerendering a real site with Playwright is that page.goto(url, { waitUntil: "networkidle" }) hangs or times out. Two culprits cause this: Large media assets (multi-MB images, audio, or video hosted on Cloudflare R2) slow down or stall network settlement. Analytics beacons (Google Analytics / Tag Manager) keep persistent connections open and pollute your GA4 data with build-time bot hits. The fix is to abort image, media, and analytics requests inside page.route() before rendering routes. The HTML snapshot only needs the DOM—not pixels: await page.route("**/*", (route) => { const type = route.request().resourceType() if (type === "image" || type === "media") return route.abort() const url = route.request().url() if (/google-analytics\.com|googletagmanager\.com/.test(url)) { return route.abort() } return route.continue() }) Keeping Each Page's <head> Clean If you serve dist/index.html as the SPA fallback while overwriting dist/index.html with the rendered homepage, every subsequent route will inherit the homepage's <title> , canonical , and Open Graph tags. To prevent duplicate SEO tags: Copy the pristine Vite-built dist/index.html to dist/__fallback.html at the start of the script. Serve dist/__fallback.html for unknown routes during prerendering. Deduplicate <title> , meta[name="description"] , og:* , twitter:* , and link[rel="canonical"] keeping the last injected tag. Delete dist/__fallback.html in a finally block so it is never deployed. We also run a post-build verifier ( scripts/verify-prerender.ts ) across all 164 generated HTML files to guarantee every page has exactly one <title> , one self-referencing canonical , matching og:url , and no trailing-slash redirect leaks in internal links. Step 2: Bypassing Your Own Cloudflare Bot Protection with Service Bindings Once the site was live on Cloudflare Pages, our edge functions began intermittently failing when fetching articles from our headless CMS hosted on another Cloudflare Worker ( inmindcms.windflashai.com ). Public fetch() calls from one Cloudflare Worker to another custom domain on the same zone can hit Cloudflare's own Bot Fight Mode / WAF layer or add unnecessary public TLS hops. The clean Cloudflare-native fix is a Service Binding in wrangler.toml : [vars] INMIND_API_BASE = "https://inmindcms.windflashai.com" [[services]] binding = "INMIND_CMS" service = "inmindcms" Inside server/content.ts , prefer the service binding whenever it is present, and always send an explicit User-Agent header: const init: RequestInit = { headers: { Accept: "application/json", "User-Agent": "WindFlashAI-Content-Reader/1.0 (+https://windflashai.com/)", }, signal: AbortSignal.timeout(10000), } const res = env.INMIND_CMS ? await env.INMIND_CMS.fetch(url, init) : await fetch(url, { ...init, cf: { cacheTtl: 60, cacheEverything: true } }) Service Bindings route directly inside Cloudflare's network with zero external round-trip and never collide with public bot-protection rules. Step 3: Fixing the 22 GSC 5xx Errors with Static HTML Fallbacks Even with Service Bindings, our Google Search Console Page Indexing report still showed 22 pages failing with Server error (5xx) —almost all of them under /articles/ and /articles/:slug/ . Tracing the middleware exposed a painful design mistake. Whenever the upstream CMS returned a transient error or timed out, both server/live-content.ts (which refreshes / and /articles/ ) and functions/articles/[slug].ts threw away the already-prerendered static HTML and returned a hard HTTP 503 . Think about how backwards that is: we had spent build time prerendering 160 static HTML files into dist/ , only to serve a 503 Temporarily Unavailable error page whenever the live CMS blipped! Fix A: Graceful Static Fallback in refreshContent Before transforming the response with HTMLRewriter , clone the static response . If the CMS request fails for any reason, return the static prerendered HTML instead of 503 : export async function refreshContent( response: Response, env: ContentEnv, _path: string ) { const fallback = response.clone() try { if (!(await response.clone().text()).includes("data-content-list=")) { throw new Error("Content region missing from build") } const posts = await allPosts(env) const revision = await contentRevision(posts) // ... HTMLRewriter injection ... res.headers.set("X-Content-Revision", revision) res.headers.set("Cache-Control", "public, max-age=60") return res } catch { // Serve the prerendered static HTML instead of breaking crawling with 503 const headers = new Headers(fallback.headers) headers.set("Cache-Control", "public, max-age=60") headers.set("X-Content-Fallback", "static") return new Response(fallback.body, { status: fallback.status, statusText: fallback.statusText, headers, }) } } Fix B: Fallback to context.next() on Dynamic Article Routes Similarly, in functions/articles/[slug].ts , when getPost(env, slug) throws a non-404 error, call await next() to serve the static dist/articles/<slug>/index.html asset before ever falling back to 503 : try { article = await getPost(env, slug) } catch (error) { if (!(error instanceof ContentError) || error.status !== 404) { try { const staticRes = await next() if ( staticRes.ok && (staticRes.headers.get("content-type") ?? "").includes("text/html") ) { const headers = new Headers(staticRes.headers) headers.set("Cache-Control", "public, max-age=60") headers.set("X-Content-Fallback", "static") return new Response(staticRes.body, { status: staticRes.status, statusText: staticRes.statusText, headers, }) } } catch { // Fall through to 503 only when no static asset exists } return new Response("Content temporarily unavailable", { status: 503 }) } } A real 404 still returns a clean 404 with noindex, follow (preventing soft-404s), while transient CMS blips seamlessly serve valid 200 OK prerendered HTML. Step 4: Four Subtle On-Page SEO Bugs That Tanked Our Audit Score After fixing the 5xx path, an On-Page SEO audit still scored the homepage at only 75 / 100 (Grade C) . Every deduction came from small implementation details that are easy to overlook in React apps: Audit Issue Root Cause in Code Fix Applied Missing <html lang> across the entire site prerender.ts stripped lang via removeAttribute('lang') to stay "language-neutral", which also broke the regex replacement in [slug].ts Preserve explicit lang="en" (or lang="zh" for /zh/ routes) in prerender.ts , and inject lang if missing in [slug].ts Broken <h1> reading as W i n d F l a s h (85 chars) Per-letter animated <span> elements sat inside <h1> with aria-hidden="true" , which HTML-only SEO parsers still concatenated into textContent Keep a single clean <h1 className="sr-only">WindFlash AI — Builder · Creator · Explorer</h1> (43 chars) and move the animated display letters to a sibling <div aria-hidden="true"> Truncated Meta Description (210 chars) Homepage English description exceeded Google's ~160 character display limit Tightened to 147 characters while keeping all primary entities 11/12 images missing width / height + /admin polluting GA4 Card images omitted explicit dimensions (CLS risk), and index.html loaded gtag.js on /admin , inflating 28-day pageviews by 13% Added explicit width and height to every homepage image and gated gtag.js behind `!/^/admin(?:/ Phantom /articles/?q={search_term_string} 5xx URLs JSON-LD WebSite schema declared a SearchAction pointing to ?q= , even though /articles/ did not implement query-param search Removed the unused potentialAction block from index.html Before & After Results After deploying the fixes to Cloudflare Pages production ( --branch=main ) and re-running the exact same On-Page SEO audit on https://windflashai.com/ : Overall On-Page Score : 75 (C) → 94 (A · Excellent) (+19 points) Meta Tags : 20/25 → 25/25 (100%) Content Quality : 19/24 → 22.5/24 (H1 length 85 → 43, clean single heading) Images & Media : 6.5/8 → 8/8 (12/12 images with alt , width , height , and loading="lazy" ) Static Verification : 164 / 164 prerendered and static HTML files passed verify-prerender.ts Search Console : Resubmitted sitemap.xml (including previously omitted /stories/* routes) and initiated validation on all 22 5xx URLs. Frequently Asked Questions Should I use hydrateRoot or createRoot with Playwright prerendering? If your React app fetches live data on mount with React Query or SWR, createRoot is usually safer and simpler. hydrateRoot expects the first client render to match the prerendered DOM byte-for-byte; any timestamp, theme toggle, or updated CMS item triggers hydration warnings. createRoot still lets crawlers read the full prerendered HTML while giving real users a clean client mount. Why did Googlebot crawl /articles/?q={search_term_string} ? When a page's WebSite JSON-LD includes a SearchAction target template, Googlebot occasionally probes the literal template URL or synthetic query variations. If your site does not handle that query parameter server-side, remove potentialAction from your JSON-LD schema. How do I prevent Cloudflare Pages from serving 200 OK soft-404s for unknown routes? In functions/_middleware.ts , maintain an explicit allowlist of static public paths and dynamic route regexes (such as /articles/[^/]+/ and /music/[^/]+/ ). For any GET request to an unknown extensionless path, return a real 404 HTML response with <meta name="robots" content="noindex, follow"> instead of falling through to dist/index.html . If you are building an independent site with React, Vite, and Cloudflare Pages, you do not need to throw away your stack to get solid technical SEO—you just need deterministic prerendering, static fallbacks for every dynamic edge call, and automated verification on every build. You can browse more architecture notes on the WindFlash AI blog or read more about my projects on the About page .