Code-Splitting a Prerendered React App Without Breaking Hydration
How ToolRunner cut its entry script from 6.8 MB to 383 KB by loading each page on demand, and the three traps of lazy pages in a prerendered React 19 app.
by OneTwoCoding
For most of its life, ToolRunner shipped one JavaScript file. Every page of the site, from the JSON Viewer to the Mermaid Viewer to the PDF tools, was imported eagerly by the route table, so the first visit to any page downloaded the code for all of them. The pages themselves were prerendered to static HTML at build time, so content showed up quickly. But the page wasn't usable until the browser had fetched, parsed, and run one very large script. Splitting by route takes about ten lines with React.lazy in a client-rendered app. In a prerendered app with a strict Content Security Policy and analytics tied to the server-rendered markup, it took a lot more. This article covers the measurements, the three traps I hit, and the one number that didn't move.
The problem: one script for forty pages
ToolRunner is a Vite + React Router single-page app. At build time a Node script renders every route to its own index.html, and in the browser React hydrates that markup instead of rendering from scratch. Before this change, the route table looked roughly like this:
import JsonViewer from '../pages/JsonViewer';
import MermaidViewer from '../pages/MermaidViewer';
import PdfConverter from '../pages/PdfConverter';
// ...and the rest, about forty in all
Static imports put every page, and every library each page imports at the top level, into the entry chunk. Some of those libraries are large. The Mermaid Viewer imports mermaid directly, and the SQL tools carry a full SQL parser and formatter. Someone opening the cron generator to check a schedule paid for all of it.
The measurements
I measured the built entry script before and after the change:
| Entry script | Gzipped | |
|---|---|---|
| Before (every page eager) | 6,842,971 bytes | 1,742,362 bytes |
| After (pages on demand) | 383,226 bytes | 120,378 bytes |
That's about 94% less JavaScript in the file every page needs. What remains in the entry is the layout (header, sidebar, search), the home page, the not-found page, React, the router, and shared helpers. Each other page is its own chunk, fetched when its route first renders.
There's a cost on the other side. A tool page now needs its own chunk plus the shared chunks it imports, and Vite splits shared code finely. The prerendered /json-viewer/ page now carries about 20 modulepreload links, many of them tiny chunks that each hold a single icon component. That works, and HTTP/2 multiplexes the requests, but it isn't tidy. I come back to it in the last section.
The shape of a lazy page
The obvious tool is React.lazy wrapped in a <Suspense> boundary around the router's <Outlet />. I started there and backed out, for reasons covered in the second trap below. What the route table uses now is a small helper called lazyPage. Each page gets one line:
const JsonViewer = lazyPage('src/pages/JsonViewer.tsx', () => import('../pages/JsonViewer'));
The first argument is the module's key in the Vite manifest, which the prerender script needs later. The second is the dynamic import. The component it returns differs from React.lazy in one way that matters: once the module has loaded, the page renders synchronously. Only a page that hasn't loaded yet suspends, using React 19's use():
const Page = (props) => createElement(loaded ?? use(loadForRender()), props);
It also exposes preload(), so code outside the render can start the import early. Around those two lines, the helper tracks whether the module has loaded or a load is in flight, and remembers a failed load so React sees the same rejection on every retry instead of starting a fresh import each time. Most of the work went into those states.
Trap one: the CSP blocks React's streaming script
The prerender used to call renderToString. Once pages could suspend, that stopped being enough. renderToString doesn't wait for suspended content; it renders the fallback. The prerender needs to wait until every lazy page on the route has resolved, and React's tool for that is prerender from react-dom/static, which resolves only after all Suspense boundaries are ready.
Switching renderers exposed a behavior I hadn't known about. When React 19.2 server-renders a finished Suspense boundary of more than 500 bytes that would push the HTML written so far past about 12.8 KB, it doesn't always write the content in place. It can outline the boundary, emitting a placeholder first, then the content inside a hidden <template>, then a small inline <script> that moves the content into position. That's a sensible design for streaming servers. On ToolRunner it fails, because the site's CSP script-src allows 'self' and a few named hosts, but not 'unsafe-inline', so the browser refuses to run that script. The page would ship with its real content stuck inside a template the user never sees.
The fix is one option and two guards:
const { prelude } = await prerender(app, {
progressiveChunkSize: Number.POSITIVE_INFINITY,
signal: controller.signal,
onError: (error) => {
errors.push(error);
},
});
progressiveChunkSize: Infinity tells React that no boundary is too large to inline, so size never moves content out of place. onError collects errors, and the render throws the first one after the stream is read. Without that, React's default answer to a render error in a boundary is to switch that boundary to client rendering, which would quietly ship a fallback where the page should be. A timeout aborts a render that never finishes. Then the build's HTML check scans every prerendered page for anything that shouldn't be there: an unfinished boundary marker, a client-rendered boundary marker, outlined <template id="B:..."> content, or inline scripts. Any of those fails the build, so a future change in React's outlining behavior should show up at build time rather than as a blank page in production.
The CSP explainer covers the policy itself. The lesson here: a strict CSP is part of your rendering contract, and a renderer change can break it without a single build error.
Trap two: Suspense, hydration order, and the 404 page
This one took the longest to see, because nothing visibly broke.
ToolRunner reports pageviews from an effect in the layout component. When a URL has no page, Cloudflare Pages serves the prerendered 404.html, and React hydrates it. The not-found page has to be reported as /404/, not as whatever path the visitor typed, or the analytics fill up with junk URLs that look like real traffic. The mechanism is simple. The not-found page writes the current path into a shared ref from its own effect, and the layout's route effect reads that ref. It works because React runs a child's effects before its parent's effects in the same commit, so by the time the layout reports the pageview, the not-found page has already marked it.
Now put a <Suspense> boundary around <Outlet />. During hydration, React treats a Suspense boundary as a separate unit: it can hydrate the content inside it in a later pass, after the surrounding tree has committed. The layout's effects then run first, before the not-found page has written its ref, and the landing pageview of a 404 gets reported under the real path. No error, no warning, just quietly wrong data.
So there's no Suspense boundary around the routed page. That's the reason lazyPage exists instead of React.lazy. Two pieces make it work without one:
-
The landing page loads before hydration. The client entry matches the current URL against the route table, preloads that page's chunk, and only then calls
hydrateRoot:preloadRoute(window.location.pathname).catch(() => {}).then(start)By the time React hydrates, the page module is loaded,
lazyPagerenders it synchronously, and the whole tree, layout and page together, hydrates in one pass. If the preload fails, the page tries again during render and reports the failure there. -
Later navigations are transitions. React Router's
BrowserRouterwraps navigations instartTransition. When a page suspends inside a transition, React keeps the old page on screen until the new one is ready, then commits the new page together with the layout. The effect order holds there too.
The not-found page itself stays in the entry chunk, as does the home page, which gets the most visits. A blog URL with an unknown slug is the awkward case: the lazy blog article page renders the not-found page itself. It still commits with the layout, because of the two rules above. A hydration test renders the real 404.html markup for both a missing tool and a missing blog slug, hydrates it, and asserts that exactly one pageview was sent, for /404/.
Transitions bring one UX problem: on a slow connection, a click that leaves the old page in place looks ignored. A thin progress bar covers that. It counts only page loads a render is waiting on, not preloads, and appears after 150 ms, so fast loads show nothing.
Trap three: chunks that vanish after a deploy
Every chunk name carries a content hash, and each deploy replaces the set. A tab opened yesterday still runs yesterday's entry script, which refers to yesterday's chunk URLs. When that user clicks a page they haven't visited yet, the import asks for a file that no longer exists.
When a page's chunk fails to load during render, the app reloads the document once. The reload fetches fresh HTML, which points at the new chunk names. To prevent a loop, it remembers the attempt in sessionStorage, and a repeated failure shows an error instead of reloading again. It also skips the reload when a reload can't help, for example when the browser reports it's offline. While the reload is under way, the page waits on a promise that never settles, so React doesn't flash an error first.
When reloading isn't the answer, an error boundary around the routed page shows a short message and a Reload button, and the header and sidebar keep working. The boundary renders no wrapper markup, so the prerendered HTML is unchanged, and it resets when the route changes. Only loads that a render is waiting on take this path. A failed preload() simply gets retried at render time, and imports a page makes internally, like the PDF libraries the PDF Watermark page loads after hydration, don't trigger a reload: if one fails, the error boundary shows its message.
Preloads: fetching the page's chunks with the entry
Splitting adds a waterfall. The browser downloads the entry script, runs it, finds out which page it's on, and only then requests that page's chunk. For the first page a visitor lands on, the prerender script removes that waterfall by writing <link rel="modulepreload"> tags for the page's chunks into the HTML head, so the browser fetches them in parallel with the entry.
The list comes from the Vite manifest. Each lazy page carries its manifest key, pageModulesFor(url) returns the keys for a route, and the prerender script walks the manifest's static imports from those keys, leaving out anything the entry already loads. It also links the page's own CSS as a stylesheet, so the prerendered content is styled before its chunk runs. crossorigin on each link matches the entry script tag, so the browser reuses the preloaded responses instead of fetching twice.
One manifest detail needed care. Usually a page's manifest entry is keyed by its source path, like src/pages/JsonViewer.tsx. But when other chunks import shared code from a page's chunk, Rollup can't make the page module that chunk's facade, and Vite keys the chunk by its file name instead. The lookup falls back to searching the entry's dynamic imports by chunk name, and fails the build unless exactly one matches. Picking "the first match" would have been easy and wrong. A build that might preload the wrong chunk should not deploy.
The manifest lists every chunk in the build, and nothing in the browser needs it, so the prerender script deletes it before deploy. The HTML check fails the build if it's still there.
Proving the HTML didn't change
The risk I worried about most was a change that alters the prerendered HTML in some way nobody notices: a missing paragraph, a fallback where content should be, a reordered head tag. So before touching anything, I saved all 67 prerendered pages from the old build. Then I made the change in two steps and diffed every file after each one.
- Swap the renderer.
renderToStringbecamereact-dom/static'sprerender, with no lazy pages yet. Diff: zero bytes across all 67 files. - Make the pages lazy. Diff: zero changes, apart from the added
modulepreloadand stylesheet links in each head.
Golden-file diffing is blunt, and that's why it works: it doesn't need to know what could go wrong, only to check "this refactor doesn't change output" against every page.
Caching: making the split pay off on repeat visits
Splitting shrinks the first download. Caching decides whether the second visit downloads anything. Because every file in /assets is named after its content hash, a given URL always holds the same bytes, so the site sends:
/assets/*
Cache-Control: public, max-age=31536000, immutable
HTML stays at max-age=0, so a deploy reaches visitors right away, and the new HTML points at new chunk names. Once a returning visitor's browser has cached a chunk, it never revalidates it. Not as many survive a deploy as you might hope. Rollup's hash for a chunk covers the chunks it imports, and the entry dynamically imports every page. So a deploy that only touches the JSON Viewer renames the entry, and with it every chunk that imports from the entry: about 160 of the 200 chunks in the current build. What keeps its name is the large third-party code that imports nothing from the app, such as the HEIC decoder, the spreadsheet parser, and the diagram and PDF libraries. That is about 5.6 MB of the 18.4 MB of JavaScript in the build, and it now stays cached across deploys. Under a single 6.8 MB bundle it didn't.
A one-year immutable header is only safe if every file under that path really is content-hashed. Vite hashes what it bundles, but a copy plugin or a hand-placed file could land there with a fixed name. So the build check lists /assets and fails if any file name lacks a content hash. A file whose bytes change under a fixed name would stay stale in browsers for a year, and there would be no way to recall it.
An aside on compression
I also looked at compression, expecting easy wins. Cloudflare already serves Brotli, but at a low on-the-fly level. Before the split, the main script came out at 1.76 MB in Brotli versus 1.30 MB with brotli -q 11 locally, and the edge's Brotli was even slightly larger than its own gzip (1.73 MB). Pages doesn't serve precompressed .br files you upload, though, so that gap wasn't something I could close from the build. Shipping less JavaScript, and not re-downloading it, mattered far more than the compression level.
What didn't improve: build memory
I had a side hope that splitting would also ease the build, because the client build needs a lot of memory. It didn't. The client build still needs more than a 2 GB Node heap: under a 2 GB limit its peak RSS was about 2.5 GB, and with 4 GB available it peaked around 3.0 GB, much as before.
In hindsight, that makes sense. Rollup's memory goes mostly to the module graph: every parsed module, its AST, its bindings, the tree-shaking analysis. Code-splitting changes how the output is grouped into chunks, not how many modules get parsed. The heavy libraries are still in the graph; they just end up in different files. If build memory is the problem, the levers are fewer or lighter dependencies and different bundler settings, not code-splitting. The CI fix stayed what it was before: give the build a larger heap.
What I'd do next
- Group the tiny chunks. About 20 preloads for one page, many of them single-icon chunks, is overhead for no benefit. A
manualChunksrule that groups the icon modules into one shared chunk would cut most of those requests. The catch is that any page using one icon then fetches all of them, so it's a trade to measure, not assume. - Preload on intent. Every lazy page already has
preload(). Calling it when a nav link is hovered or focused would start the fetch a few hundred milliseconds before the click, and the progress bar would rarely appear. - Keep page edits from renaming everything. Because the entry imports every page, any page change renames the entry and every chunk that imports from it. Moving React and the shared helpers out of the entry into their own chunk, so page chunks stop importing the entry, would let a page edit rename only that page's chunk and the entry.
- Watch the entry stay small. 383 KB is where the entry landed, not a limit anything enforces. A build check that fails when the entry grows past a budget would catch the next eager import of a large library before it ships.
The general lesson is that in a prerendered app, code-splitting is less about the bundler than about everything that assumed one synchronous render: the CSP, the order of effects during hydration, the analytics that depend on that order, and the cache headers that decide whether old chunk URLs still exist. Each of those needed an explicit decision and a check that fails the build when the assumption breaks. The splitting itself was the easy part. If you want to see the result, open the network panel on the JSON Viewer and watch its chunks arrive in parallel with the entry script.