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

code-execution-patterns.md

146 lines3.9 KB

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/react-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] = useState('')
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 )
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>
120​
121// βœ… Consistent rendering
122function CurrentTime() {
123 const [time, setTime] = useState<string>()
124​
125 useEffect(() => {
126 setTime(new Date().toLocaleString())
127 }, [])
128​
129 return <div>{time || 'Loading...'}</div>
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