---
title: "Optimizing the sh*t out of TanStack Start"
url: "https://sarthakmishra.com/library/blog/optimizing-tanstack-start"
description: "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."
image: "https://sarthakmishra.com/og-images/blog/optimizing-tanstack-start.webp"
---

[View HTML](https://sarthakmishra.com/library/blog/optimizing-tanstack-start) · [Site index](https://sarthakmishra.com/llms.txt)

# 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.

![Colorful illustration of a central palm tree icon surrounded by charts, interface controls, and hands.](https://sarthakmishra.com/assets/optimizing-tanstack-start-hero-CJdqb0XM.jpeg)

A few days after I [moved this site to TanStack Start](https://sarthakmishra.com/library/blog/astro-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](https://sarthakmishra.com/library/blog/optimizing-tanstack-start#how-i-used-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.

| Mobile home-page metric  | [October 24, before the fixes](https://pagespeed.web.dev/analysis/https-sarthakmishra-com/adninyd8c2?form_factor=mobile) | [October 30, after this optimization round](https://pagespeed.web.dev/analysis/https-sarthakmishra-com/x5yjk1zd4x?form_factor=mobile) |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| Performance              | 73                                                                                                                       | 100                                                                                                                                   |
| First Contentful Paint   | 2.3 s                                                                                                                    | 0.9 s                                                                                                                                 |
| Largest Contentful Paint | 5.2 s                                                                                                                    | 0.9 s                                                                                                                                 |
| Total Blocking Time      | 160 ms                                                                                                                   | 0 ms                                                                                                                                  |
| Cumulative Layout Shift  | 0.002                                                                                                                    | 0.002                                                                                                                                 |
| Speed Index              | 4.5 s                                                                                                                    | 0.9 s                                                                                                                                 |

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.

![PageSpeed Insights mobile report for sarthakmishra.com: Performance, Accessibility, Best Practices and SEO all score 100. FCP is 0.9 seconds, LCP 0.9 seconds, TBT 0 milliseconds, CLS 0.002 and Speed Index 0.9 seconds. The report uses Lighthouse 13.6.0, an emulated Moto G Power and Slow 4G.](https://sarthakmishra.com/assets/pagespeed-home-mobile-2026-10-30-C9vUehQp.jpeg)

The live home page on mobile, October 30, 2026.

![PageSpeed Insights desktop report for sarthakmishra.com: Performance, Accessibility, Best Practices and SEO all score 100. FCP is 0.3 seconds, LCP 0.3 seconds, TBT 0 milliseconds, CLS 0.001 and Speed Index 0.4 seconds. The report uses Lighthouse 13.6.0 with desktop emulation.](https://sarthakmishra.com/assets/pagespeed-home-desktop-2026-10-30-AOGjNDw9.jpeg)

The desktop report captured on October 30, 2026.

**Updated November 11, 2026.** I later [removed Tailwind from this site](https://sarthakmishra.com/library/blog/tailwind-to-native-css). 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](https://sarthakmishra.com/library/blog/optimizing-tanstack-start#stop-loading-the-rest-of-the-site), [fonts](https://sarthakmishra.com/library/blog/optimizing-tanstack-start#smaller-fonts-made-the-text-jump), and [hidden images](https://sarthakmishra.com/library/blog/optimizing-tanstack-start#phones-were-downloading-the-desktop-navigation). The [CSS and hydration experiments](https://sarthakmishra.com/library/blog/optimizing-tanstack-start#critical-css-gave-me-less-blocking-css-and-more-upkeep) 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](https://developer.chrome.com/docs/lighthouse/performance/performance-scoring) comes from measured timings. This is where I’d start for each slow metric.

| What you see                                          | Where I’d look first                                                          |
| ----------------------------------------------------- | ----------------------------------------------------------------------------- |
| The document itself arrives late                      | Server response time, route loaders, sequential data requests, caching        |
| First Contentful Paint (FCP) is late                  | Render-blocking CSS, font loading, work before the first frame                |
| Largest Contentful Paint (LCP) is much later than FCP | The LCP element, when its resource is discovered, and what delays its display |
| Total Blocking Time (TBT) is high                     | Long JavaScript tasks, hydration, third-party scripts, animation loops        |
| Cumulative Layout Shift (CLS) is high                 | Font swaps, missing media dimensions, content inserted above existing content |
| Speed Index is high                                   | Filmstrip frames, late visible sections, animation during the initial load    |

Where to look once you know the LCP element · No · Yes · Image · Text · LCP element · In the HTML response? · Route loaders, prerendering, server reads · Image or text? · Discovery, priority, sizes · Fonts and render-blocking CSS · JavaScript and hidden downloads competing for bandwidth

Check the document response first. If the content is there but appears late, the cause is in the browser.

### 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.

![Chrome DevTools with the document request selected and its Response tab open. A search for the h1 tag highlights the server-rendered heading, with the introduction paragraphs visible below.](https://sarthakmishra.com/assets/devtools-html-response-D3fw9poJ.jpeg)

Select the document request, open Response, and search for your heading or main text. This is the HTML the server sent, before client rendering changes the DOM.

If the content is missing, fetch it in a route loader. Start’s [execution model](https://tanstack.com/start/latest/docs/framework/react/guide/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](https://tanstack.com/start/latest/docs/framework/react/guide/static-prerendering) puts the content in the document. This configuration prerenders two routes.

```typescript
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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Encoding) and [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/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.

![Chrome DevTools Network panel showing the document, fonts, stylesheets, and JavaScript requests, with Size, Priority, and Waterfall columns visible.](https://sarthakmishra.com/assets/devtools-network-waterfall-BJ1d4nrW.jpeg)

Right-click a Network column heading to enable Priority and Waterfall. Read across each row to see what downloads, its priority, and when it starts. The filter hides data URLs.

## 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.

![Chrome DevTools Network panel filtered to JavaScript and sorted by Size from largest to smallest, with the main entry bundle and shared chunks at the top.](https://sarthakmishra.com/assets/devtools-javascript-size-S38PTYAC.jpeg)

Choose JS and sort Size from largest to smallest to find downloads worth investigating. Transfer size tells you what to inspect; a Performance recording shows what costs CPU time.

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](https://tanstack.com/router/latest/docs/framework/react/guide/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.

```tsx
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](https://react.dev/reference/react/lazy). 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.

| Page        | Before, KiB gzip | After, KiB gzip |
| ----------- | ---------------- | --------------- |
| Home        | 196.1            | 174.4           |
| A long post | 213.0            | 190.8           |

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.

[Filtering a recorded Chrome DevTools Network log to fonts and JavaScript, then sorting JavaScript requests by size.](https://sarthakmishra.com/videos/optimizing-tanstack-start/network-filters/native.m3u8)

In a recorded Network log, choose Font, then JS. Click Size until the largest downloads appear first. This short clip has no audio.

## 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.

![Chrome DevTools Network panel filtered to Font, showing the Inter and Instrument Serif WOFF2 files with their transfer sizes, priorities, and request timing.](https://sarthakmishra.com/assets/devtools-font-requests-DwfjKxNh.jpeg)

The Font filter isolates the files this page downloaded. Compare their sizes and start times before changing font imports or preload hints.

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](https://web.dev/articles/optimize-webfont-loading) 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.

```css
@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](https://web.dev/articles/optimize-cls) 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](https://web.dev/articles/optimize-lcp) separates time to first byte, resource discovery, transfer, and render delay. The Performance panel shows where the time went.

![Chrome DevTools Performance recording with LCP breakdown expanded. It shows 540 milliseconds of time to first byte and 179 milliseconds of element render delay beside the loading timeline.](https://sarthakmishra.com/assets/devtools-performance-lcp-BRJeoNSC.jpeg)

Open LCP breakdown in a Performance recording. This page has a text LCP, so the breakdown shows time to first byte and element render delay. An image LCP can also include resource loading phases.

For an image in a container capped at 960 pixels, with 16-pixel gutters on smaller screens, the markup looks like this.

```tsx
<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.

| Work                                       | A useful starting policy                                     |
| ------------------------------------------ | ------------------------------------------------------------ |
| Main text, initial styles, LCP resource    | Available for the first render                               |
| A video player or heavy embed further down | Prepare as it approaches the viewport                        |
| Search, an editor, or a dialog             | Load on intent or first use                                  |
| Decorative animation                       | Start after load, then pause when idle or out of view        |
| Third-party scripts                        | Load when the feature needs them, accounting for measurement |

For decorative work, this helper waits for `load` and an idle slot. It also works if `load` has already fired.

```typescript
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](https://oxc.rs/blog/2026-08-18-react-compiler-support.html#vite). 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](https://tanstack.com/start/latest/docs/framework/react/guide/css-styling) covers both.

I tried all three delivery strategies.

| Strategy                                         | Benefit                         | Cost to measure                                 |
| ------------------------------------------------ | ------------------------------- | ----------------------------------------------- |
| External route CSS                               | Reusable browser cache          | A blocking request on a cold visit              |
| Inline route CSS                                 | Removes that stylesheet request | More HTML on every document load                |
| Extracted critical CSS plus deferred stylesheets | Fewer rules needed before paint | Extraction complexity and more states to verify |

Start’s experimental, production-only option inlines route CSS from its manifest.

```typescript
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](https://pagespeed.web.dev/analysis/https-sarthakmishra-com/ilmnkrz1n9?form_factor=mobile) and 97.

Then I used [Beasties](https://github.com/danielroe/beasties) to extract rules matching each prerendered document. Those rules went inline. The complete stylesheets loaded through the `media="print"` and `onload` [pattern](https://web.dev/articles/defer-non-critical-css), 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](https://tanstack.com/start/latest/docs/framework/react/guide/deferred-hydration) 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.

```tsx
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](https://github.com/GoogleChrome/lighthouse/blob/main/docs/throttling.md) 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.

```typescript
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](https://zod.dev/packages/mini) and other options using the same two-field check in Rolldown.

| Validating two search params | Gzip     |
| ---------------------------- | -------- |
| Written by hand              | 0.2 KiB  |
| valibot 1.2                  | 1.7 KiB  |
| `zod/mini`                   | 6.5 KiB  |
| Classic `zod`                | 24.3 KiB |
| arktype 2.1                  | 47.4 KiB |

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.

```typescript
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](https://github.com/shadcn-ui/cn) 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](https://github.com/lxsmnsyc/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](https://github.com/TanStack/router/pull/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.

```typescript
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.

| Initial JavaScript, gzip | October 29 | October 30 |
| ------------------------ | ---------- | ---------- |
| Median page              | 200.0 KiB  | 140.3 KiB  |
| Home page                | 202.8 KiB  | 153.4 KiB  |

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.

| Measure                    | Budget             |
| -------------------------- | ------------------ |
| Render-blocking CSS        | 17,500 bytes gzip  |
| All linked stylesheets     | 34,000 bytes gzip  |
| Initial JavaScript         | 250,000 bytes gzip |
| Module preloads            | 40                 |
| Shared content-index chunk | 15,000 bytes gzip  |

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](https://pagespeed.web.dev/analysis/https-sarthakmishra-com-blog/rw0qk89bxu?form_factor=mobile) scored 100 and [Newsletter Issue 1](https://pagespeed.web.dev/analysis/https-sarthakmishra-com-newsletter-issue-1/fzfp00vdsl?form_factor=mobile) scored 99. The image-heavy posts on [fixing exams](https://pagespeed.web.dev/analysis/https-sarthakmishra-com-blog-stop-fixing-exams/gh12w1kooy?form_factor=mobile) and [building the interactive SVG avatar](https://pagespeed.web.dev/analysis/https-sarthakmishra-com-blog-building-interactive-svg-avatar/xip0px5rg0?form_factor=mobile) 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](https://sarthakmishra.com/library/blog/tailwind-to-native-css), so the measurements here can stay attached to the changes that produced them.

## Media sources

### Where to look once you know the LCP element

```mermaid
flowchart TD
L[LCP element] --> H{In the HTML response?}
H -->|No| R[Route loaders, prerendering, server reads]
H -->|Yes| T{Image or text?}
T -->|Image| I[Discovery, priority, sizes]
T -->|Text| F[Fonts and render-blocking CSS]
I --> J[JavaScript and hidden downloads competing for bandwidth]
F --> J
class R orange
class I blue
class F blue
class J violet
```

## Structured data

```json
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "WebSite",
      "@id": "https://sarthakmishra.com/#website",
      "url": "https://sarthakmishra.com/",
      "name": "Sarthak Mishra",
      "publisher": {
        "@id": "https://sarthakmishra.com/#person"
      },
      "inLanguage": "en"
    },
    {
      "@type": "Person",
      "@id": "https://sarthakmishra.com/#person",
      "name": "Sarthak Mishra",
      "url": "https://sarthakmishra.com/about",
      "jobTitle": "Design Engineer",
      "image": "https://sarthakmishra.com/og-images/sarthak-mishra.webp",
      "sameAs": [
        "https://github.com/SarthakMishra",
        "https://www.linkedin.com/in/itssarthakmishra/",
        "https://x.com/MishraMishry"
      ]
    },
    {
      "@type": "WebPage",
      "@id": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start#webpage",
      "url": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start",
      "name": "Optimizing the sh*t out of TanStack Start - Sarthak",
      "description": "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.",
      "inLanguage": "en",
      "isPartOf": {
        "@id": "https://sarthakmishra.com/#website"
      },
      "mainEntity": {
        "@id": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start#content"
      },
      "breadcrumb": {
        "@id": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start#breadcrumb"
      }
    },
    {
      "@id": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start#content",
      "url": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start",
      "name": "Optimizing the sh*t out of TanStack Start",
      "description": "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.",
      "mainEntityOfPage": {
        "@id": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start#webpage"
      },
      "author": {
        "@id": "https://sarthakmishra.com/#person"
      },
      "datePublished": "2026-10-26T00:00:00.000Z",
      "dateModified": "2026-11-11T00:00:00.000Z",
      "inLanguage": "en",
      "keywords": [
        "tanstack",
        "react",
        "performance",
        "web-development"
      ],
      "@type": "BlogPosting",
      "headline": "Optimizing the sh*t out of TanStack Start",
      "publisher": {
        "@id": "https://sarthakmishra.com/#person"
      },
      "image": "https://sarthakmishra.com/og-images/blog/optimizing-tanstack-start.webp"
    },
    {
      "@type": "BreadcrumbList",
      "@id": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start#breadcrumb",
      "itemListElement": [
        {
          "@type": "ListItem",
          "position": 1,
          "name": "Home",
          "item": "https://sarthakmishra.com/"
        },
        {
          "@type": "ListItem",
          "position": 2,
          "name": "Blog",
          "item": "https://sarthakmishra.com/library/blog"
        },
        {
          "@type": "ListItem",
          "position": 3,
          "name": "Optimizing the sh*t out of TanStack Start",
          "item": "https://sarthakmishra.com/library/blog/optimizing-tanstack-start"
        }
      ]
    }
  ]
}
```
