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

execution-model.md

367 lines10.6 KB

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)
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 )
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>
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 )
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>
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>
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 }
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
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))
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 )
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.