Open History to see the last commit
1---
2id: code-execution-patterns
3title: Code Execution Patterns
4---
5β
6This guide covers patterns for controlling where code runs in your TanStack Start application - server-only, client-only, or isomorphic (both environments). For foundational concepts, see the [Execution Model](./execution-model.md) guide.
7β
8## Quick Start
9β
10Set up execution boundaries in your TanStack Start application:
11β
12```tsx
13import {
14 createServerFn,
15 createServerOnlyFn,
16 createClientOnlyFn,
17 createIsomorphicFn,
18} from '@tanstack/solid-start'
19β
20// Server function (RPC call)
21const getUsers = createServerFn().handler(async () => {
22 return await db.users.findMany()
23})
24β
25// Server-only utility (crashes on client)
26const getSecret = createServerOnlyFn(() => process.env.API_SECRET)
27β
28// Client-only utility (crashes on server)
29const saveToStorage = createClientOnlyFn((data: any) => {
30 localStorage.setItem('data', JSON.stringify(data))
31})
32β
33// Different implementations per environment
34const logger = createIsomorphicFn()
35 .server((msg) => console.log(`[SERVER]: ${msg}`))
36 .client((msg) => console.log(`[CLIENT]: ${msg}`))
37```
38β
39## Implementation Patterns
40β
41### Progressive Enhancement
42β
43```tsx
44// Component works without JS, enhanced with JS
45function SearchForm() {
46 const [query, setQuery] = createSignal('')
47β
48 return (
49 <form action="/search" method="get">
50 <input
51 name="q"
52 value={query()}
53 onChange={(e) => setQuery(e.target.value)}
54 />
55 <ClientOnly fallback={<button type="submit">Search</button>}>
56 <SearchButton onSearch={() => search(query())} />
57 </ClientOnly>
58 </form>
59 )
60}
61```
62β
63### Environment-Aware Storage
64β
65```tsx
66const storage = createIsomorphicFn()
67 .server((key: string) => {
68 // Server: File-based cache
69 const fs = require('node:fs')
70 return JSON.parse(fs.readFileSync('.cache', 'utf-8'))[key]
71 })
72 .client((key: string) => {
73 // Client: localStorage
74 return JSON.parse(localStorage.getItem(key) || 'null')
75 })
76```
77β
78## Common Problems
79β
80### Environment Variable Exposure
81β
82```tsx
83// β Exposes to client bundle
84const apiKey = process.env.SECRET_KEY
85β
86// β
Server-only access
87const apiKey = createServerOnlyFn(() => process.env.SECRET_KEY)
88```
89β
90### Incorrect Loader Assumptions
91β
92```tsx
93// β Assuming loader is server-only
94export const Route = createFileRoute('/users')({
95 loader: () => {
96 // This runs on BOTH server and client!
97 const secret = process.env.SECRET // Exposed to client
98 return fetch(`/api/users?key=${secret}`)
99 },
100})
101β
102// β
Use server function for server-only operations
103const getUsersSecurely = createServerFn().handler(() => {
104 const secret = process.env.SECRET // Server-only
105 return fetch(`/api/users?key=${secret}`)
106})
107β
108export const Route = createFileRoute('/users')({
109 loader: () => getUsersSecurely(), // Isomorphic call to server function
110})
111```
112β
113### Hydration Mismatches
114β
115```tsx
116// β Different content server vs client
117function CurrentTime() {
118 return <div>{new Date().toLocaleString()}</div>
119}
120β
121// β
Consistent rendering
122function CurrentTime() {
123 const [time, setTime] = createSignal<string>()
124β
125 createEffect(() => {
126 setTime(new Date().toLocaleString())
127 })
128β
129 return <div>{time() || 'Loading...'}</div>
130}
131```
132β
133## Production Checklist
134β
135- [ ] **Bundle Analysis**: Verify server-only code isn't in client bundle
136- [ ] **Environment Variables**: Ensure secrets use `createServerOnlyFn()` or `createServerFn()`
137- [ ] **Loader Logic**: Remember loaders are isomorphic, not server-only
138- [ ] **ClientOnly Fallbacks**: Provide appropriate fallbacks to prevent layout shift
139- [ ] **Error Boundaries**: Handle server/client execution errors gracefully
140β
141## Related Resources
142β
143- [Execution Model](./execution-model.md) - Core concepts and architectural patterns
144- [Server Functions](./server-functions.md) - Deep dive into server function patterns
145- [Environment Variables](./environment-variables.md) - Secure environment variable handling
146- [Middleware](./middleware.md) - Server function middleware patterns