Open History to see the last commit
1---
2id: css-styling
3title: CSS Styling
4---
5β
6TanStack Start supports the CSS patterns your bundler supports, and adds SSR-aware route asset discovery on top.
7β
8Use this guide to choose how to import CSS in a React Start app, and how to configure production CSS behavior such as SSR stylesheet links, Early Hints, and CSS inlining.
9β
10## Choose a CSS Pattern
11β
12Start handles CSS differently depending on how you import it.
13β
14| Pattern | Use it when | SSR behavior | Production features |
15| ---------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | --------------------------------------------------- |
16| `import css from './app.css?url'` | You want to put a stylesheet URL in route `head()` | Rendered from `head().links` | Dynamic Early Hints |
17| `import './global.css'` | You want global CSS attached to a route chunk | Discovered from the Start manifest for matched routes | Static Early Hints, `transformAssets`, CSS inlining |
18| `import styles from './card.module.css'` | You want scoped class names attached to a route chunk | Discovered from the Start manifest for matched routes | Static Early Hints, `transformAssets`, CSS inlining |
19β
20Use `?url` when the stylesheet is part of your route head output. Use side-effect CSS imports or CSS modules when you want Start to treat the generated stylesheet as a route asset.
21β
22## Use `?url` for Explicit Stylesheet Links
23β
24Import CSS with `?url` when you want the bundler to return the emitted stylesheet URL and you want to render the `<link rel="stylesheet">` yourself.
25β
26```tsx
27// src/routes/__root.tsx
28/// <reference types="vite/client" />
29import { createRootRoute } from '@tanstack/react-router'
30import appCss from '../styles/app.css?url'
31β
32export const Route = createRootRoute({
33 head: () => ({
34 links: [{ rel: 'stylesheet', href: appCss }],
35 }),
36})
37```
38β
39This pattern is useful for explicit global stylesheets, especially when you already want the stylesheet to be part of route `head()` output. The CSS file is emitted by the bundler, and `HeadContent` places the stylesheet link in the final document.
40β
41`?url` stylesheet links are route head output, not Start manifest-managed stylesheet assets. Because of that:
42β
43- They are discovered when route `head()` runs.
44- They can appear in the `dynamic` Early Hints phase as route `head().links` entries.
45- They are not rewritten by Start's runtime [`transformAssets`](./cdn-asset-urls) option.
46- They are not inlined by Start CSS inlining.
47β
48Use this pattern when explicit control of the route head is more important than Start's manifest-managed CSS features.
49β
50## Use Side-Effect Imports for Global Route CSS
51β
52Import CSS without assigning it when you want global selectors, global class names, or CSS custom properties to be bundled with a route or component module.
53β
54```tsx
55// src/routes/index.tsx
56import { createFileRoute } from '@tanstack/react-router'
57import '../styles/global.css'
58β
59export const Route = createFileRoute('/')({
60 component: Home,
61})
62β
63function Home() {
64 return <div className="global-container">Global CSS</div>
65}
66```
67β
68The class names remain global. Start discovers the generated CSS asset from the client build and attaches it to the matching route manifest entry. During SSR, `HeadContent` renders stylesheet links for the matched route tree, so the page is styled before hydration.
69β
70Where you import the CSS controls when it is loaded:
71β
72- Import in the root route or app shell to apply it to every page.
73- Import in a layout route to apply it to that layout and its child routes.
74- Import in a leaf route to load it only when that route is matched.
75- Import from a component loaded with `import()` or `React.lazy` only when the CSS is not needed for the initial route render.
76β
77CSS imported from an async component loads with that async chunk. It is not part of Start's static route manifest for the initial route match, so `HeadContent` does not render it as an initial SSR stylesheet link, and it is not available for static Early Hints or CSS inlining.
78β
79Side-effect CSS imports are a good fit for app-wide CSS resets, design tokens, global utility classes, and route-level global styles.
80β
81## Use CSS Modules for Scoped Route CSS
82β
83CSS modules work like side-effect CSS imports from Start's route asset discovery perspective, but the class names are scoped by the bundler.
84β
85```tsx
86// src/routes/modules.tsx
87import { createFileRoute } from '@tanstack/react-router'
88import styles from '../styles/card.module.css'
89β
90export const Route = createFileRoute('/modules')({
91 component: Modules,
92})
93β
94function Modules() {
95 return <div className={styles.card}>Scoped CSS module</div>
96}
97```
98β
99The generated stylesheet is discovered from the route chunk graph, linked during SSR for matched routes, and loaded during client navigation when the route chunk loads.
100β
101Use CSS modules for route-local or component-local styling when you want scoped class names and Start-managed stylesheet assets.
102β
103## Know When CSS Is Discovered
104β
105The import pattern you choose controls when Start can see the stylesheet.
106β
107CSS from side-effect imports and CSS modules is discovered at build time. Start inspects the client build output, records CSS emitted for route chunks, and uses that manifest during SSR. Because Start already knows about these stylesheets before route loaders run, they can be sent in the `static` Early Hints phase as `rel=preload; as=style` links.
108β
109CSS imported with `?url` is different. Start sees that stylesheet only when route `head()` returns the link, which happens after `router.load()`. These links can still be sent as Early Hints, but only in the `dynamic` phase with other supported route `head().links` entries.
110β
111Use this rule of thumb:
112β
113- Use side-effect imports or CSS modules when you want Start to discover route CSS as early as possible.
114- Use `?url` when you want explicit route `head()` control and are comfortable with later discovery.
115- Use `allLinks` in the `dynamic` phase when you want one combined Early Hints response with both static manifest assets and dynamic head links.
116- If CSS inlining is enabled, inlined manifest-managed stylesheet assets are skipped by static Early Hints because they are embedded in the HTML.
117β
118See the [Early Hints guide](./early-hints) for the callback and response header APIs.
119β
120## Inline Route CSS in Production
121β
122> **Experimental:** CSS inlining is experimental and subject to change.
123β
124CSS inlining embeds Start manifest-managed route CSS directly into the server-rendered HTML response for production builds. This can improve the first render by avoiding blocking stylesheet requests for the CSS needed by the initial route match.
125β
126Enable it with `server.build.inlineCss` in the Start plugin options. Passing `true` is shorthand for `{ enabled: true, transformAssets: false }`.
127β
128<!-- ::start:tabs variant="bundler" -->
129β
130# Vite
131β
132```ts title="vite.config.ts"
133import { defineConfig } from 'vite'
134import { tanstackStart } from '@tanstack/react-start/plugin/vite'
135β
136export default defineConfig({
137 plugins: [
138 tanstackStart({
139 server: {
140 build: {
141 inlineCss: true,
142 },
143 },
144 }),
145 ],
146})
147```
148β
149# Rsbuild
150β
151```ts title="rsbuild.config.ts"
152import { defineConfig } from '@rsbuild/core'
153import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
154β
155export default defineConfig({
156 plugins: [
157 tanstackStart({
158 server: {
159 build: {
160 inlineCss: true,
161 },
162 },
163 }),
164 ],
165})
166```
167β
168<!-- ::end:tabs -->
169β
170This option only affects production builds. Development mode keeps using Start's normal development CSS handling.
171β
172CSS inlining applies to CSS discovered from side-effect imports and CSS modules, because those stylesheets are Start manifest assets. It does not inline CSS imported with `?url` and returned from `head().links`, because those links are dynamic route head output rather than manifest-managed stylesheet assets.
173β
174When CSS inlining is enabled, Start still emits CSS files in the client build. It only changes the SSR document: stylesheet links managed by the Start manifest are replaced with a single inline `<style>` tag for the matched routes. The inline style is preserved during hydration to avoid duplicate stylesheet links and hydration mismatches.
175β
176### Control Inlining at Runtime
177β
178You can control inlining per request in your server entry. This only affects builds created with `server.build.inlineCss` enabled.
179β
180```tsx
181// src/server.ts
182import {
183 createStartHandler,
184 defaultStreamHandler,
185} from '@tanstack/react-start/server'
186import { createServerEntry } from '@tanstack/react-start/server-entry'
187β
188const handler = createStartHandler({
189 handler: defaultStreamHandler,
190 inlineCss: ({ request }) => request.headers.get('x-inline-css') !== 'false',
191})
192β
193export default createServerEntry({ fetch: handler })
194```
195β
196For custom runtime wrappers, `handler(request, { inlineCss })` overrides the handler-level `inlineCss` setting for that request.
197β
198```tsx
199export default createServerEntry({
200 fetch(request) {
201 return handler(request, {
202 inlineCss: request.headers.get('x-inline-css') !== 'false',
203 })
204 },
205})
206```
207β
208### URL Rebasing
209β
210If an inlined stylesheet contains relative `url(...)` or `@import` references, Start rebases them relative to the emitted CSS asset URL before embedding the CSS.
211β
212For example, when the generated stylesheet is served from `/_build/assets/dashboard.css`:
213β
214```css
215.card {
216 background-image: url('./dot.svg');
217}
218```
219β
220Start embeds it as:
221β
222```css
223.card {
224 background-image: url(/_build/assets/dot.svg);
225}
226```
227β
228Root-relative URLs are left unchanged at build time. Absolute URLs, protocol-relative URLs, data URLs, and hash references are also left unchanged.
229β
230If you need to rewrite CSS-internal URLs at runtime, such as prepending a CDN origin to fonts or background images, opt into CSS URL templates with `server.build.inlineCss: { enabled: true, transformAssets: true }`. See [Transform URLs Inside Inlined CSS](./cdn-asset-urls#transform-urls-inside-inlined-css) for the detailed `transformAssets` behavior.
231β
232### Tradeoffs
233β
234CSS inlining is useful when the matched route CSS is small enough that putting it in the HTML is cheaper than an extra stylesheet request. It can be less effective when your initial route loads a large global stylesheet that would otherwise be cached as a separate file.
235β
236Consider these tradeoffs before enabling it:
237β
238- The HTML response becomes larger.
239- First-load CSS can no longer be cached independently from the HTML response.
240- Strict Content Security Policy setups must allow the inline style. Configure `ssr.nonce` on the router so `HeadContent` can apply the nonce to rendered `<style>` tags, including inlined CSS.
241- CSS files are still emitted for client navigation and browser caching after the initial response.
242β
243Use CSS inlining when the reduced request overhead is worth the larger HTML response for your deployment and route structure.
244β
245## Configure Production CSS Behavior
246β
247Use these options together based on what you need in production.
248β
249| Need | Use |
250| ----------------------------------------- | ---------------------------------------------------- |
251| Explicit stylesheet links in route head | `?url` imports returned from `head().links` |
252| SSR links for route CSS | Side-effect imports or CSS modules |
253| Earliest CSS Early Hints | Side-effect imports or CSS modules with static hints |
254| Redirect-safe stylesheet Early Hints | `?url` imports with dynamic hints |
255| Fewer blocking CSS requests on first load | `server.build.inlineCss` |
256| Runtime CDN rewriting for Start assets | [`transformAssets`](./cdn-asset-urls) |