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

execution-model.md

331 lines9.1 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/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 )
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>
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 )
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>
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>
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 }
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 )
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.