Optimizing the sh*t out of TanStack Start
A practical TanStack Start performance guide: how cutting downloads and fixing fonts and images took my home page from 73 to 100 on mobile Lighthouse.

A few days after I moved this site to TanStack Start, the home page scored 73 on mobile PageSpeed Insights. Its largest contentful element was a paragraph, with a reported paint time of 5.2 seconds.
That’s a long wait for a paragraph.
I worked through the site with Claude Code and Codex, tracing what the browser downloaded and what kept it from painting. A card component was sending the whole image catalog to every page. Closed dialogs loaded their code anyway. Phones downloaded images for navigation they couldn’t see.
Most of the useful fixes came from removing work I’d accidentally given the browser.
By October 30, the home page scored 100, with LCP down to 0.9 seconds. I also built a critical CSS pipeline and delayed hydration. Those took much more work, and I still can’t tell you how much they contributed to the score.
These are individual lab runs on the live home page, with several changes between them. They show where I started and ended, not what each fix contributed. The later run was captured on October 30 at 10:43 PM IST.
Updated November 11, 2026. I later removed Tailwind from this site. The new Post covers the component-owned CSS system, the MDX and navigation stylesheet loader, and the bundle measurements across all 76 pages. The screenshots above preserve the October PageSpeed Insights results described in this Post.
If you’re working on a similar app, I’d start with unnecessary JavaScript, fonts, and hidden images. The CSS and hydration experiments are further down, along with what broke.
Find out what the paragraph is waiting for
The document arrived in about 110 ms and already contained the paragraph. There was no client-side data fetch to wait for. That narrowed the investigation to what happened in the browser.
Find your LCP element before optimizing anything. Mine was text already in the document, so I started with fonts, blocking CSS, and downloads competing with them.
The Performance score comes from measured timings. This is where I’d start for each slow metric.
Check the response before React changes it
Open the document request in DevTools and search its Response tab for your heading and main text. The DOM after hydration doesn’t tell you what the server sent.
If the content is missing, fetch it in a route loader. Start’s execution model allows loaders to run on the server and in the browser, so server-only code still needs a server boundary. Moving an import into a loader doesn’t keep it out of the client bundle.
For public pages that can be generated at build time, static prerendering puts the content in the document. This configuration prerenders two routes.
tanstackStart({
prerender: {
enabled: true,
autoStaticPathsDiscovery: false,
crawlLinks: false,
},
pages: [
{ path: '/', prerender: { enabled: true } },
{ path: '/about', prerender: { enabled: true } },
],
});Personalized pages still need request-time rendering. Check the deployed Content-Encoding and Cache-Control headers too. Content-hashed assets can have a long cache lifetime. HTML needs one that fits how often it changes.
Make sure the measurements are comparable
Use a production build. Development mode includes work visitors never receive. Repeat the audit with the same settings, compare medians, and confirm on the deployed site.
On October 25, the same build scored 91, 95, and 92 within a few minutes. PageSpeed also reused cached audits under new report links, so I had to check capture times before counting a run as new.
My local preview caused a different distraction. It served 165 KiB of uncompressed HTML and scored 94 to 95. Brotli took the same document to about 28 KiB and the score to 99, much closer to production. I could have spent a while trying to fix the app for that one.
Once the HTML and the test setup were accounted for, the Network panel showed what else the page was asking for.
Stop loading the rest of the site
A card component imported the full image manifest. That made every page download metadata for 117 images, about 35 KiB compressed, even when it displayed a handful. The images had their own downloads. These were their descriptions and rendition URLs, shipped as JavaScript.
Each route now carries the image data it renders. Navigation fetches newly needed data. I also removed tooling-only excerpts and unused recommendation scores from the shared content index.
The home page’s module-preloaded JavaScript fell from roughly 234 to 196 KiB. Its HTML grew from about 42 to 49 KiB because it now contained the selected image data. I was happy with that trade. The unrelated catalog stopped going to every reader.
Check both the loader response and the emitted bundles. Returning a smaller object won’t help much if an import still puts the full dataset in the browser’s startup code.
Filter Network to JS, sort by size, and trace the larger files back to their imports. Compare a simple route with a complex one. Shared downloads often lead back to the root route, a layout, or a component both pages use.
A closed dialog can still download
TanStack Router’s route code splitting separates routes. Within a route, search, the mobile menu, image enlargement, a portrait viewer, and a leave-form confirmation were all adding to my initial load.
A lazy component is a start. Declare it at module scope.
import { lazy } from 'react';
const SearchDialog = lazy(() => import('./SearchDialog'));SearchDialog is a default export here. React requests the module when you first try to render it. Rendering it with open={false} can therefore start the download while the dialog is closed.
I kept the triggers available and mounted the dialogs on first open. They need Suspense, an error boundary, and enough time to finish closing and return focus before unmounting. Initially, I warmed their chunks after page load so the first interaction wouldn’t wait for a download.
That cut the initial JavaScript.
But the warm-up still charged every reader for features most wouldn’t use. Base UI’s dialog engine alone added about 14 KiB gzip after load on every page. I later changed the triggers to load on hover, focus, or press. The first tap on a phone can wait briefly for the chunk. I accepted that.
Verify the requests in the browser. A separate chunk hasn’t saved a download if the page immediately preloads it.
Smaller fonts made the text jump
The normal Inter file was about 342 KiB. Fontsource’s WOFF2 subsets let the browser request only the character ranges a page uses. Removing the optical-size axis then took the normal Latin file from 71.2 to 47.1 KiB, about a third smaller. I kept small symbol supplements for characters the interface still needed.
I also cut three font preloads to one, the normal Latin Instrument Serif face used by the heading. Other faces load when text needs them.
Check the family, weight, style, and character range of each request. A preload should earn its place by fixing measured late discovery in the initial view. Its URL, type, and crossorigin mode must match the font request, or you can download it twice. Google’s font-loading guide explains the details.
The smaller downloads exposed another problem. Text appeared sooner, then moved when the web font arrived. Newsletter Issue 1 recorded CLS around 0.21 during those changes because the heading changed size and pushed everything below it.
A faster font swap still needs a stable fallback. I adjusted the fallback’s metrics to bring its dimensions closer to Instrument Serif.
@font-face {
font-family: 'Instrument Serif Fallback';
src:
local('Times New Roman'), local('TimesNewRomanPSMT'),
local('Liberation Serif'), local('Noto Serif');
size-adjust: 83.75%;
ascent-override: 118.2%;
descent-override: 37.01%;
line-gap-override: 0%;
}Put the fallback after the web font in the font-family stack. These percentages belong to my pairing, so measure yours. Google’s CLS guidance covers the overrides. A cold-load recording with the filmstrip visible will show whether the text appears early and stays put.
A later desktop regression came from the font chosen before these fallbacks. The deferred Noto Color Emoji name matched an installed system font, which rendered ordinary spaces and digits until Inter arrived. Giving that webfont a private family name (Portfolio Color Emoji) fixed the shifts.
Phones were downloading the desktop navigation
My desktop navigation was hidden on phones. Its eager images still appeared in the preload list. Nine requests for navigation the reader couldn’t see.
Marking the images lazy removed the preloads. The sidebar now waits for hydration and a desktop-sized viewport before decoding its images, so phones never request them. Desktop navigation appears slightly later as a result.
Video posters had the same problem. I’d deferred the enhanced player with an IntersectionObserver but left the poster eager. The player could wait for scrolling while its poster downloaded immediately. Both needed deferral.
Give the visible image the priority it needs
On a page with an image LCP, make that image discoverable in the initial HTML, eager, and eligible for high fetch priority. Google’s LCP guidance separates time to first byte, resource discovery, transfer, and render delay. The Performance panel shows where the time went.
For an image in a container capped at 960 pixels, with 16-pixel gutters on smaller screens, the markup looks like this.
<img
src="/images/article-1280.webp"
srcSet="/images/article-640.webp 640w, /images/article-960.webp 960w, /images/article-1280.webp 1280w"
sizes="(max-width: 992px) calc(100vw - 32px), 960px"
width={1280}
height={720}
alt="An editor displaying a published article"
loading="eager"
fetchPriority="high"
/>Those paths assume generated 16:9 renditions. The sizes hint describes the layout. On my site, which uses different renditions, correcting it let a phone choose a 640-pixel file where it had previously chosen a 1080-pixel one.
Images further down can load lazily. Reserve their space with dimensions so they don’t move the page when they arrive.
Give deferred work a reason to start
I had an idle home-page animation updating SVG geometry about 30 times a second. Delaying its start still left that work running. It needed to stop when it had nothing to do.
Choose a trigger for each piece of work, then check what it does after that trigger.
For decorative work, this helper waits for load and an idle slot. It also works if load has already fired.
export function afterPageLoad(callback: () => void) {
let idle = 0;
let timer = 0;
const schedule = () => {
if (typeof requestIdleCallback === 'function') {
idle = requestIdleCallback(callback, { timeout: 2000 });
} else {
timer = window.setTimeout(callback, 200);
}
};
if (document.readyState === 'complete') schedule();
else window.addEventListener('load', schedule, { once: true });
return () => {
window.removeEventListener('load', schedule);
if (idle) cancelIdleCallback(idle);
window.clearTimeout(timer);
};
}Call it from client-side setup and cancel the pending callback during cleanup. Any loop or subscription it starts needs its own cleanup too.
Deferral changes behavior. My analytics loads on first interaction or a few seconds after load, so it can miss a very short visit. Form verification starts on focus, giving it time to load before submission. Test with someone who starts using the page as soon as it appears.
React Compiler cost bytes I chose to keep
I’d already adopted the native React Compiler. Across five alternating baseline and compiled pairs on three routes, timings stayed roughly unchanged while compressed JavaScript grew by 9.5 to 14.1 KiB per route.
I kept it because it replaced hand-written memoization. That maintenance benefit was worth the measured byte cost to me. It couldn’t decide whether a closed dialog belonged in the first load, though. Loading changes needed their own measurements.
Critical CSS gave me less blocking CSS and more upkeep
After the unnecessary downloads, I worked on how the stylesheet arrived. This was where the fixes became harder to justify.
I first moved feature styles out of the global stylesheet and into their owning routes or components. Start tracks side-effect CSS imports and CSS modules in its route manifest. Explicit ?url links returned from head().links sit outside that manifest, which matters for its built-in delivery features. The CSS styling guide covers both.
I tried all three delivery strategies.
Start’s experimental, production-only option inlines route CSS from its manifest.
tanstackStart({
server: {
build: { inlineCss: true },
},
});Inlining repeated the full route stylesheet in every document. Moving feature styles out and switching back to external files roughly halved the home page’s HTML. PageSpeed couldn’t separate the results convincingly. The inlined version scored 91 to 95 across three runs. The first two external-CSS runs scored 92 and 97.
Then I used Beasties to extract rules matching each prerendered document. Those rules went inline. The complete stylesheets loaded through the media="print" and onload pattern, with a <noscript> fallback. Beasties matches against the document, so its output can include content below the fold.
The static HTML didn’t represent every state the page could be in.
- Dark mode was missing from the build-time HTML.
- Font families selected through CSS variables lost their declarations.
- Selected form controls lost their selectors.
- Preload headers would have raised the deferred stylesheets’ priority again.
Fixing those meant maintaining a selector allowlist and handling fonts separately. I compared all 71 prerendered pages with critical CSS alone against full styles, at phone and desktop widths, in both themes. I also tested navigation and the no-JavaScript fallback. Request-time pages kept their blocking stylesheets, and the prerendered pages’ Early Hints kept only the heading font.
Render-blocking CSS fell from 20.6–29.7 KiB to 7.0–14.9 KiB per page. That saving is measurable. Its contribution to the final score is unclear, and the extraction rules need checking whenever the site changes. I’d want a clear stylesheet bottleneck in the trace before taking this on in another app.
Delayed hydration broke early scrolling
Start’s experimental Hydrate boundary keeps a section’s server HTML while delaying hydration. By default, it also splits that section’s code into a separate chunk. Related articles can wait for this. A checkout form probably shouldn’t.
import { Hydrate } from '@tanstack/react-start';
import { visible } from '@tanstack/react-start/hydration';
import { Reviews } from './Reviews';
export function DeferredReviews() {
return (
<Hydrate when={visible({ rootMargin: '600px' })}>
<Reviews />
</Hydrate>
);
}Check your installed Start version before using it. The boundary controls initial hydration. Later client-side mounts work differently, updates can hydrate the section early, and its server HTML still needs CSS.
I went further. A build step rewrites Start’s preload links and entry script so the whole app starts after the browser paints the prerendered HTML. It fails the build if Start emits markup it doesn’t recognize.
An existing video test caught the consequence. A reader could scroll 2,000 pixels down, then hydration would hand control to the router and send them back to the top. I had to preserve that early scroll without breaking restoration on later navigation.
The score still didn’t settle the question. A critical-CSS preview scored 100 with 0.9-second FCP and LCP without delayed startup. Production with delayed startup returned 92. A later October 26 deploy containing both techniques and unrelated work scored 100, even though both techniques had scored 92 on production that day.
Lighthouse’s simulated throttling models slower conditions from an observed load. Differences in that load can move the result. I can’t credit delayed startup for the 100, or rule out its contribution.
For another app, I’d try a Hydrate boundary around a section that can wait before delaying every React-controlled interaction.
The score stayed up while the JavaScript grew back
By October 29, three days of feature work had brought the median page’s initial JavaScript back to 200 KiB gzip. My 250,000-byte budget still passed.
The budget was passing while the bundle grew. I needed to look at what was growing.
Vite 8 uses Rolldown, whose bundle analyzer can write Markdown or JSON. This adds the Markdown report to the client build.
import { bundleAnalyzerPlugin } from 'rolldown/experimental';
export default defineConfig({
environments: {
client: {
build: {
rolldownOptions: {
plugins: [
bundleAnalyzerPlugin({ format: 'md', fileName: 'analyze-data.md' }),
],
},
},
},
},
});Move the report out of the client output before deploying. It lists large modules and each entry’s chunks. Match a page’s script URLs to those chunks to find its modules. The reported module sizes are before compression, so use them to find candidates, then measure gzip.
The report found an icon map that included every icon, and a /blog/$ route that shipped both listing and post code. Named icon imports fixed the first. Lazy branches, with the loader preloading the one it rendered, fixed the second.
The larger surprises came from code shared by every page.
Two search params brought in classic Zod
One route used Zod in validateSearch. TanStack Router keeps search validation in the eager route configuration, so that import added about 23 KiB gzip to every page.
Classic Zod’s method-based API limits what a bundler can remove. I compared it with Zod Mini and other options using the same two-field check in Rolldown.
These are sizes for that check and build setup. My first attempt used esbuild, which retained more Zod code and overstated its cost in this site.
I kept small client checks hand-written, with unit tests. Larger checks and schemas shared with the server use zod/mini. It comes from the same package and supports the same inferred types and error shapes. Valibot was smaller, but I didn’t want a second validation API alongside the server’s Zod schemas.
Compiling the schema didn’t help the download. Zod’s built-in z.compile() speeds up parsing and added about 7 KiB. The build-time zod-compiler package retained classic Zod and the source schema, taking the check to 25.3 KiB.
Start’s import protection now rejects classic Zod in client code, with an import trace when the build fails.
tanstackStart({
importProtection: {
behavior: 'error',
client: {
specifiers: [/^zod(?:\/v4(?:\/classic)?)?$/],
},
},
});The analyzer sometimes lost the connection to my code through a package’s re-export file. A source search for the package name found the importer faster. Check constants too. My client code imported a topics list from the content schema file, which gave the schema library another route into the browser.
The button brought a class-merge engine to every page
My button passed its variants through cn, a replacement for clsx plus tailwind-merge. The merge engine cost about 10 KiB gzip. It was doing useful work. Forty of 51 button call sites relied on conflicting classes being resolved, including hidden overriding the base inline-flex.
I tried trimming its merge tables at build time. Keeping 125 of 384 class groups matched the full engine at all 51 call sites, but saved only about 1.9 KiB. Most of the cost was the engine itself.
So I removed the conflicts. Base classes stopped setting properties owned by variants. Each size took responsibility for its radius, text size, wrapping, border width, and disabled opacity. Callers got explicit options where they’d previously overridden classes, including a fit option and two sizes. hidden sm:inline-flex became max-sm:hidden.
Plain cva output could then be the final class list. A unit test checked every option combination and the call sites against the full merge engine, failing if it would drop a class.
That removed the engine from first load everywhere at that stage. Inputs, selects, and dialogs still downloaded it later where they rendered. The button was worth fixing first because every page used it. The subsequent native-CSS migration removed CVA and class merging from the site’s client code altogether.
Form serialization could wait for a form submit
Start’s client registered a server-function adapter that imported the RPC fetcher and seroval. That added roughly 11 KiB gzip to every page, although my server functions only ran on form submission. The initial hydration payload was already a self-contained script.
At the time of this work, TanStack/router#8302 proposed an opt-in serverFns: { transport: 'lazy' }. I used a version-pinned pnpm patch to make the fetcher import dynamic. Seroval now arrives in a roughly 10 KiB chunk on the first submit. That’s another patch to revisit when Start changes.
Chunk groups can pull lazy code back in
Each page had 22 to 37 preloads, most under 2 KiB. React DOM also shared a file with the site’s shell, so editing the shell made returning visitors download React again.
This Rolldown group put the shared dependencies together.
build: {
rolldownOptions: {
output: {
codeSplitting: {
groups: [
{
name: 'vendor',
test: /node_modules\/(react|react-dom|scheduler|@tanstack\/(react-router|router-core|history|react-store|store)|cookie-es|use-sync-external-store)\/(?!dist\/esm\/ssr\/)/,
priority: 20,
},
],
},
},
},
},The exact package names matter. My first, looser pattern also matched @base-ui/react and lucide-react, adding 50 KiB to every page. Groups can claim modules reachable only through lazy imports too. Without the ssr/ exclusion, router-core’s serializers pulled seroval straight back into the vendor chunk.
The other experiments weren’t worth keeping. Terser saved 0.3% over Oxc. Inlining every imported constant saved about 0.1 KiB. Inlining small shared chunks reduced preloads but added roughly 2 KiB because the required execution-order wrappers cost bytes. Merging everything into the entry was smallest, but every new post would then invalidate a chunk containing React DOM.
Across the October 29–30 bundle work, the results were easier to account for than the Lighthouse score.
The final step, combining the vendor chunk, codec patch, and intent-loaded dialogs, also reduced what the browser downloaded after load. The home page went from about 221 to 184 KiB, and a long post from 234 to 196 KiB. Those totals include later downloads, so they’re different from the initial JavaScript in the table.
How I used Claude Code and Codex
I often handed one agent’s work to the other. They made changes, built variants, and measured them. I decided what to keep.
Claude Code took the first 73 report and traced the paragraph LCP, font preloads, animations, and image manifest. It also ran Unlighthouse across 17 representative pages. Codex handled the next CSS round and collected PageSpeed batches when I asked for live results. That’s how it caught reused audits under new report links.
They disagreed about critical CSS. Claude Code initially advised against it because Lighthouse estimated no FCP or LCP savings from the blocking stylesheet. When the score dipped again, I asked it to build and test the pipeline anyway. It compared all 71 pages across widths and themes, tried Cloudflare previews, and found the scroll bug. When production stayed at 92, I had it save the work on a branch and roll back. Codex later reworked the transforms as Vite plugins and redeployed them.
Claude Code handled the October 29–30 bundle work, measuring each variant. I also asked it to file an issue about seroval unless one already existed. It found the pull request and filed nothing.
A preview, a 71-page comparison, or a rollback took minutes. Deciding whether 92 and 97 meant anything stayed my job. So did deciding how much build machinery I wanted to maintain for a smaller stylesheet.
Keep the bytes from coming back
My size budgets fail the build when a page crosses these limits.
They catch large regressions. The room I’d left for growth also let almost 30 KiB accumulate in three days. I now want the bundle report alongside the pass or fail, so I can see what the budget still allows.
Count deferred downloads too. My JavaScript budget includes the entry and preloads delayed until after paint. Deferred stylesheets count toward total CSS. Moving a request later shouldn’t make its bytes disappear from the check.
Browser tests cover the behaviors these changes put at risk. Main content must exist before hydration, fonts must settle without reflow, hidden assets must stay unloaded, dialogs must return focus, and hydration must preserve an early scroll.
The home page isn’t the whole site, either. On October 26, the Blog listing scored 100 and Newsletter Issue 1 scored 99. The image-heavy posts on fixing exams and building the interactive SVG avatar were still at 89 and 88, both with 3.5-second LCP and zero blocking time.
The November follow-up covers the native-CSS migration and its route-by-route bundle measurements, so the measurements here can stay attached to the changes that produced them.