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/solid-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/solid-start'
84import { ClientOnly } from '@tanstack/solid-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 an accessor (signal) indicating whether the client has been hydrated:
104β
105```tsx
106import { useHydrated } from '@tanstack/solid-router'
107β
108function TimeZoneDisplay() {
109 const hydrated = useHydrated()
110 const timeZone = () =>
111 hydrated() ? Intl.DateTimeFormat().resolvedOptions().timeZone : 'UTC'
112β
113 return <div>Your timezone: {timeZone()}</div>
114}
115```
116β
117**Behavior:**
118β
119- **During SSR**: Always returns `false`
120- **First client render**: Returns `false`
121- **After hydration**: Returns `true` (and stays `true` for all subsequent renders)
122β
123This 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.
124β
125### Environment-Specific Implementations
126β
127```tsx
128import { createIsomorphicFn } from '@tanstack/solid-start'
129β
130// Different implementation per environment
131const getDeviceInfo = createIsomorphicFn()
132 .server(() => ({ type: 'server', platform: process.platform }))
133 .client(() => ({ type: 'client', userAgent: navigator.userAgent }))
134```
135β
136## Architectural Patterns
137β
138### Progressive Enhancement
139β
140Build components that work without JavaScript and enhance with client-side functionality:
141β
142```tsx
143function SearchForm() {
144 const [query, setQuery] = createSignal('')
145β
146 return (
147 <form action="/search" method="get">
148 <input
149 name="q"
150 value={query()}
151 onChange={(e) => setQuery(e.target.value)}
152 />
153 <ClientOnly fallback={<button type="submit">Search</button>}>
154 <SearchButton onSearch={() => search(query())} />
155 </ClientOnly>
156 </form>
157 )
158}
159```
160β
161### Environment-Aware Storage
162β
163```tsx
164const storage = createIsomorphicFn()
165 .server((key: string) => {
166 // Server: File-based cache
167 const fs = require('node:fs')
168 return JSON.parse(fs.readFileSync('.cache', 'utf-8'))[key]
169 })
170 .client((key: string) => {
171 // Client: localStorage
172 return JSON.parse(localStorage.getItem(key) || 'null')
173 })
174```
175β
176### RPC vs Direct Function Calls
177β
178Understanding when to use server functions vs server-only functions:
179β
180```tsx
181// createServerFn: RPC pattern - server execution, client callable
182const fetchUser = createServerFn().handler(async () => await db.users.find())
183β
184// Usage from client component:
185const user = await fetchUser() // β
Network request
186β
187// createServerOnlyFn: Crashes if called from client
188const getSecret = createServerOnlyFn(() => process.env.SECRET)
189β
190// Usage from client:
191const secret = getSecret() // β Throws error
192```
193β
194## Common Anti-Patterns
195β
196### Environment Variable Exposure
197β
198```tsx
199// β Exposes to client bundle
200const apiKey = process.env.SECRET_KEY
201β
202// β
Server-only access
203const apiKey = createServerOnlyFn(() => process.env.SECRET_KEY)
204```
205β
206### Incorrect Loader Assumptions
207β
208```tsx
209// β Assuming loader is server-only
210export const Route = createFileRoute('/users')({
211 loader: () => {
212 // This runs on BOTH server and client!
213 const secret = process.env.SECRET // Exposed to client
214 return fetch(`/api/users?key=${secret}`)
215 },
216})
217β
218// β
Use server function for server-only operations
219const getUsersSecurely = createServerFn().handler(() => {
220 const secret = process.env.SECRET // Server-only
221 return fetch(`/api/users?key=${secret}`)
222})
223β
224export const Route = createFileRoute('/users')({
225 loader: () => getUsersSecurely(), // Isomorphic call to server function
226})
227```
228β
229### Hydration Mismatches
230β
231```tsx
232// β Different content server vs client
233function CurrentTime() {
234 return <div>{new Date().toLocaleString()}</div>
235}
236β
237// β
Consistent rendering
238function CurrentTime() {
239 const [time, setTime] = createSignal<string>()
240β
241 createEffect(() => {
242 setTime(new Date().toLocaleString())
243 })
244β
245 return <div>{time() || 'Loading...'}</div>
246}
247```
248β
249## Manual vs API-Driven Environment Detection
250β
251```tsx
252// Manual: You handle the logic
253function logMessage(msg: string) {
254 if (typeof window === 'undefined') {
255 console.log(`[SERVER]: ${msg}`)
256 } else {
257 console.log(`[CLIENT]: ${msg}`)
258 }
259}
260β
261// API: Framework handles it
262const logMessage = createIsomorphicFn()
263 .server((msg) => console.log(`[SERVER]: ${msg}`))
264 .client((msg) => console.log(`[CLIENT]: ${msg}`))
265```
266β
267## Architecture Decision Framework
268β
269**Choose Server-Only when:**
270β
271- Accessing sensitive data (environment variables, secrets)
272- File system operations
273- Database connections
274- External API keys
275β
276**Choose Client-Only when:**
277β
278- DOM manipulation
279- Browser APIs (localStorage, geolocation)
280- User interaction handling
281- Analytics/tracking
282β
283**Choose Isomorphic when:**
284β
285- Data formatting/transformation
286- Business logic
287- Shared utilities
288- Route loaders (they're isomorphic by nature)
289β
290## Security Considerations
291β
292### Bundle Analysis
293β
294Always verify server-only code isn't included in client bundles:
295β
296```bash
297# Analyze client bundle
298npm run build
299# Check dist/client for any server-only imports
300```
301β
302### Environment Variable Strategy
303β
304- **Client-exposed**: Use `VITE_` prefix for client-accessible variables
305- **Server-only**: Access via `createServerOnlyFn()` or `createServerFn()`
306- **Never expose**: Database URLs, API keys, secrets
307β
308### Error Boundaries
309β
310Handle server/client execution errors gracefully:
311β
312```tsx
313function ErrorBoundary(props) {
314 return (
315 <ErrorBoundaryComponent
316 fallback={<div>Something went wrong</div>}
317 onError={(error) => {
318 if (typeof window === 'undefined') {
319 console.error('[SERVER ERROR]:', error)
320 } else {
321 console.error('[CLIENT ERROR]:', error)
322 }
323 }}
324 >
325 {props.children}
326 </ErrorBoundaryComponent>
327 )
328}
329```
330β
331Understanding 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.