Open History to see the last commit
1---
2id: execution-model
3title: Execution Model
4---
5β
6Understanding where code runs is fundamental to building TanStack Start applications. This guide explains TanStack Start's execution model and how to control where your code executes.
7β
8## Core Principle: Isomorphic by Default
9β
10**All code in TanStack Start is isomorphic by default** - it runs and is included in both server and client bundles unless explicitly constrained.
11β
12```tsx
13// β
This runs on BOTH server and client
14function formatPrice(price: number) {
15 return new Intl.NumberFormat('en-US', {
16 style: 'currency',
17 currency: 'USD',
18 }).format(price)
19}
20β
21// β
Route loaders are ISOMORPHIC
22export const Route = createFileRoute('/products')({
23 loader: async () => {
24 // This runs on server during SSR AND on client during navigation
25 const response = await fetch('/api/products')
26 return response.json()
27 },
28})
29```
30β
31> **Critical Understanding**: Route `loader`s are isomorphic - they run on both server and client, not just the server.
32β
33## The Execution Boundary
34β
35TanStack Start applications run in two environments:
36β
37### Server Environment
38β
39- **Node.js runtime** with access to file system, databases, environment variables
40- **During SSR** - Initial page renders on server
41- **API requests** - Server functions execute server-side
42- **Build time** - Static generation and pre-rendering
43β
44### Client Environment
45β
46- **Browser runtime** with access to DOM, localStorage, user interactions
47- **After hydration** - Client takes over after initial server render
48- **Navigation** - Route loaders run client-side during navigation
49- **User interactions** - Event handlers, form submissions, etc.
50β
51## Execution Control APIs
52β
53### Server-Only Execution
54β
55| API | Use Case | Client Behavior |
56| ------------------------ | ------------------------- | ------------------------- |
57| `createServerFn()` | RPC calls, data mutations | Network request to server |
58| `createServerOnlyFn(fn)` | Utility functions | Throws error |
59β
60```tsx
61import { createServerFn, createServerOnlyFn } from '@tanstack/react-start'
62β
63// RPC: Server execution, callable from client
64const updateUser = createServerFn({ method: 'POST' })
65 .validator((data: UserData) => data)
66 .handler(async ({ data }) => {
67 // Only runs on server, but client can call it
68 return await db.users.update(data)
69 })
70β
71// Utility: Server-only, client crashes if called
72const getEnvVar = createServerOnlyFn(() => process.env.DATABASE_URL)
73```
74β
75### Client-Only Execution
76β
77| API | Use Case | Server Behavior |
78| ------------------------ | ------------------------------- | ---------------- |
79| `createClientOnlyFn(fn)` | Browser utilities | Throws error |
80| `<ClientOnly>` | Components needing browser APIs | Renders fallback |
81β
82```tsx
83import { createClientOnlyFn } from '@tanstack/react-start'
84import { ClientOnly } from '@tanstack/react-router'
85β
86// Utility: Client-only, server crashes if called
87const saveToStorage = createClientOnlyFn((key: string, value: any) => {
88 localStorage.setItem(key, JSON.stringify(value))
89})
90β
91// Component: Only renders children after hydration
92function Analytics() {
93 return (
94 <ClientOnly fallback={null}>
95 <GoogleAnalyticsScript />
96 </ClientOnly>
97 )
98}
99```
100β
101#### useHydrated Hook
102β
103For more granular control over hydration-dependent behavior, use the `useHydrated` hook. It returns a boolean indicating whether the client has been hydrated:
104β
105```tsx
106import { useHydrated } from '@tanstack/react-router'
107β
108function TimeZoneDisplay() {
109 const hydrated = useHydrated()
110 const timeZone = hydrated
111 ? Intl.DateTimeFormat().resolvedOptions().timeZone
112 : 'UTC'
113β
114 return <div>Your timezone: {timeZone}</div>
115}
116```
117β
118**Behavior:**
119β
120- **During SSR**: Always returns `false`
121- **First client render**: Returns `false`
122- **After hydration**: Returns `true` (and stays `true` for all subsequent renders)
123β
124This is useful when you need to conditionally render content based on client-side data (like browser timezone, locale, or localStorage) while providing a sensible fallback for server rendering.
125β
126### Environment-Specific Implementations
127β
128```tsx
129import { createIsomorphicFn } from '@tanstack/react-start'
130β
131// Different implementation per environment
132const getDeviceInfo = createIsomorphicFn()
133 .server(() => ({ type: 'server', platform: process.platform }))
134 .client(() => ({ type: 'client', userAgent: navigator.userAgent }))
135```
136β
137## Architectural Patterns
138β
139### Progressive Enhancement
140β
141Build components that work without JavaScript and enhance with client-side functionality:
142β
143```tsx
144function SearchForm() {
145 const [query, setQuery] = useState('')
146β
147 return (
148 <form action="/search" method="get">
149 <input
150 name="q"
151 value={query}
152 onChange={(e) => setQuery(e.target.value)}
153 />
154 <ClientOnly fallback={<button type="submit">Search</button>}>
155 <SearchButton onSearch={() => search(query)} />
156 </ClientOnly>
157 </form>
158 )
159}
160```
161β
162### Environment-Aware Storage
163β
164```tsx
165const storage = createIsomorphicFn()
166 .server((key: string) => {
167 // Server: File-based cache
168 const fs = require('node:fs')
169 return JSON.parse(fs.readFileSync('.cache', 'utf-8'))[key]
170 })
171 .client((key: string) => {
172 // Client: localStorage
173 return JSON.parse(localStorage.getItem(key) || 'null')
174 })
175```
176β
177### RPC vs Direct Function Calls
178β
179Understanding when to use server functions vs server-only functions:
180β
181```tsx
182// createServerFn: RPC pattern - server execution, client callable
183const fetchUser = createServerFn().handler(async () => await db.users.find())
184β
185// Usage from client component:
186const user = await fetchUser() // β
Network request
187β
188// createServerOnlyFn: Crashes if called from client
189const getSecret = createServerOnlyFn(() => process.env.SECRET)
190β
191// Usage from client:
192const secret = getSecret() // β Throws error
193```
194β
195## Common Anti-Patterns
196β
197### Module-Level `process.env` Reads
198β
199Reading `process.env` at module scope is wrong for **two** reasons, not one:
200β
2011. **Security:** the value can be inlined into the client bundle.
2022. **Runtime correctness:** on Cloudflare Workers and other edge SSR runtimes, env is injected per-request. Module-level code runs at module load, before the env exists, so the read evaluates to `undefined` even on the server.
203β
204```tsx
205// β Leaks to client AND is undefined under Worker SSR
206const apiKey = process.env.SECRET_KEY
207β
208// β
Wrap in a server-only function β read happens per call, on the server
209const apiKey = createServerOnlyFn(() => process.env.SECRET_KEY)
210β
211// β
Or read directly inside `.handler()` / middleware `.server()` / server-route handlers
212const fetchData = createServerFn().handler(async () => {
213 const apiKey = process.env.SECRET_KEY
214 // ...
215})
216```
217β
218### Incorrect Loader Assumptions
219β
220```tsx
221// β Assuming loader is server-only
222export const Route = createFileRoute('/users')({
223 loader: () => {
224 // This runs on BOTH server and client!
225 const secret = process.env.SECRET // Exposed to client
226 return fetch(`/api/users?key=${secret}`)
227 },
228})
229β
230// β
Use server function for server-only operations
231const getUsersSecurely = createServerFn().handler(() => {
232 const secret = process.env.SECRET // Server-only
233 return fetch(`/api/users?key=${secret}`)
234})
235β
236export const Route = createFileRoute('/users')({
237 loader: () => getUsersSecurely(), // Isomorphic call to server function
238})
239```
240β
241### Hydration Mismatches
242β
243```tsx
244// β Different content server vs client
245function CurrentTime() {
246 return <div>{new Date().toLocaleString()}</div>
247}
248β
249// β
Consistent rendering
250function CurrentTime() {
251 const [time, setTime] = useState<string>()
252β
253 useEffect(() => {
254 setTime(new Date().toLocaleString())
255 }, [])
256β
257 return <div>{time || 'Loading...'}</div>
258}
259```
260β
261## Manual vs API-Driven Environment Detection
262β
263```tsx
264// Manual: You handle the logic
265function logMessage(msg: string) {
266 if (typeof window === 'undefined') {
267 console.log(`[SERVER]: ${msg}`)
268 } else {
269 console.log(`[CLIENT]: ${msg}`)
270 }
271}
272β
273// API: Framework handles it
274const logMessage = createIsomorphicFn()
275 .server((msg) => console.log(`[SERVER]: ${msg}`))
276 .client((msg) => console.log(`[CLIENT]: ${msg}`))
277```
278β
279## Marking Whole Files Server- or Client-Only
280β
281The `.server.*` and `.client.*` filename suffixes opt a file into Start's import protection automatically. When you can't or don't want to rename the file, achieve the same effect with a side-effect import at the top:
282β
283```ts
284// src/lib/secrets.ts (filename can't be *.server.ts)
285import '@tanstack/react-start/server-only'
286β
287export function getApiKey() {
288 return process.env.API_KEY
289}
290```
291β
292```ts
293// src/lib/storage.ts
294import '@tanstack/react-start/client-only'
295β
296export function savePreferences(prefs: Record<string, string>) {
297 localStorage.setItem('prefs', JSON.stringify(prefs))
298}
299```
300β
301Both markers in the same file is an error. Type-only imports are ignored. See the [Import Protection guide](./import-protection.md) for the full reference, including dev vs build behavior, configuring deny rules, and reading violation traces.
302β
303## Architecture Decision Framework
304β
305**Choose Server-Only when:**
306β
307- Accessing sensitive data (environment variables, secrets)
308- File system operations
309- Database connections
310- External API keys
311β
312**Choose Client-Only when:**
313β
314- DOM manipulation
315- Browser APIs (localStorage, geolocation)
316- User interaction handling
317- Analytics/tracking
318β
319**Choose Isomorphic when:**
320β
321- Data formatting/transformation
322- Business logic
323- Shared utilities
324- Route loaders (they're isomorphic by nature)
325β
326## Security Considerations
327β
328### Bundle Analysis
329β
330Always verify server-only code isn't included in client bundles:
331β
332```bash
333# Analyze client bundle
334npm run build
335# Check dist/client for any server-only imports
336```
337β
338### Environment Variable Strategy
339β
340- **Client-exposed**: Use `VITE_` prefix for client-accessible variables
341- **Server-only**: Access via `createServerOnlyFn()` or `createServerFn()`
342- **Never expose**: Database URLs, API keys, secrets
343β
344### Error Boundaries
345β
346Handle server/client execution errors gracefully:
347β
348```tsx
349function ErrorBoundary({ children }: { children: React.ReactNode }) {
350 return (
351 <ErrorBoundaryComponent
352 fallback={<div>Something went wrong</div>}
353 onError={(error) => {
354 if (typeof window === 'undefined') {
355 console.error('[SERVER ERROR]:', error)
356 } else {
357 console.error('[CLIENT ERROR]:', error)
358 }
359 }}
360 >
361 {children}
362 </ErrorBoundaryComponent>
363 )
364}
365```
366β
367Understanding TanStack Start's execution model is crucial for building secure, performant, and maintainable applications. The isomorphic-by-default approach provides flexibility while the execution control APIs give you precise control when needed.