Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

css-styling.md

256 lines11.8 KB

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>
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>
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');
218```
219​
220Start embeds it as:
221​
222```css
223.card {
224 background-image: url(/_build/assets/dot.svg);
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) |