0
# Server Functions
1
2
Server functions are type-safe functions that run on the server but can be called from the client as if they were regular functions. They enable seamless client-server communication with automatic serialization, validation, and error handling.
3
4
## Capabilities
5
6
### Create Server Function
7
8
Creates a new server function with configurable HTTP method and middleware support.
9
10
```typescript { .api }
11
/**
12
* Creates a server function builder with optional configuration
13
* @param options - Configuration options including HTTP method
14
* @returns ServerFnBuilder for chaining additional configuration
15
*/
16
function createServerFn<TMethod extends Method>(
17
options?: { method?: TMethod }
18
): ServerFnBuilder<{}, TMethod>;
19
20
interface ServerFnBuilder<TRegister, TMethod extends Method> {
21
/** Define the server-side handler function */
22
handler<TResponse>(
23
handler: (...args: any[]) => Promise<TResponse> | TResponse
24
): ServerFn<TRegister, TMethod, TResponse>;
25
26
/** Add middleware to the server function */
27
middleware<TMiddleware>(
28
middleware: TMiddleware
29
): ServerFnBuilder<TRegister & TMiddleware, TMethod>;
30
31
/** Add input validation to the server function */
32
inputValidator<TValidator>(
33
validator: TValidator
34
): ServerFnBuilder<TRegister & { validator: TValidator }, TMethod>;
35
}
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import { createServerFn } from "@tanstack/react-start";
42
43
// Basic server function
44
const getUsers = createServerFn()
45
.handler(async () => {
46
return await db.user.findMany();
47
});
48
49
// Server function with POST method
50
const createUser = createServerFn({ method: 'POST' })
51
.handler(async (userData: { name: string; email: string }) => {
52
return await db.user.create({ data: userData });
53
});
54
55
// Server function with validation
56
const updateUser = createServerFn({ method: 'PUT' })
57
.inputValidator((data: unknown) => {
58
// Validation logic
59
return data as { id: string; name: string };
60
})
61
.handler(async ({ id, name }) => {
62
return await db.user.update({
63
where: { id },
64
data: { name }
65
});
66
});
67
```
68
69
### Use Server Function Hook
70
71
React hook for calling server functions from client components with automatic redirect handling.
72
73
```typescript { .api }
74
/**
75
* Hook for using server functions in React components
76
* @param serverFn - The server function to wrap
77
* @returns Function that calls the server function with redirect handling
78
*/
79
function useServerFn<T extends (...args: any[]) => Promise<any>>(
80
serverFn: T
81
): (...args: Parameters<T>) => ReturnType<T>;
82
```
83
84
**Usage Examples:**
85
86
```typescript
87
import { useServerFn } from "@tanstack/react-start";
88
import { getUsers, createUser } from "./server-functions";
89
90
function UserList() {
91
const getUsersFn = useServerFn(getUsers);
92
const createUserFn = useServerFn(createUser);
93
const [users, setUsers] = useState([]);
94
95
// Load users on mount
96
useEffect(() => {
97
getUsersFn().then(setUsers);
98
}, []);
99
100
// Handle form submission
101
const handleSubmit = async (userData) => {
102
const newUser = await createUserFn(userData);
103
setUsers(prev => [...prev, newUser]);
104
};
105
106
return (
107
<div>
108
{users.map(user => (
109
<div key={user.id}>{user.name}</div>
110
))}
111
</div>
112
);
113
}
114
```
115
116
### Middleware Application
117
118
Apply middleware to server functions for cross-cutting concerns like authentication, logging, and validation.
119
120
```typescript { .api }
121
/**
122
* Apply middleware to a server function
123
* @param middleware - The middleware to apply
124
* @param serverFn - The server function to wrap
125
* @returns Enhanced server function with middleware
126
*/
127
function applyMiddleware<T>(
128
middleware: AnyFunctionMiddleware[],
129
serverFn: T
130
): T;
131
132
/**
133
* Execute validation logic
134
* @param validator - The validator to execute
135
* @param input - The input to validate
136
* @returns Validated output
137
*/
138
function execValidator<T, U>(
139
validator: Validator<T, U>,
140
input: T
141
): U;
142
143
/**
144
* Flatten middleware arrays into a single middleware chain
145
* @param middlewares - Array of middleware to flatten
146
* @returns Flattened middleware array
147
*/
148
function flattenMiddlewares(
149
middlewares: AnyFunctionMiddleware[]
150
): AnyFunctionMiddleware[];
151
152
/**
153
* Execute a middleware chain
154
* @param middlewares - The middleware chain to execute
155
* @param context - The execution context
156
* @returns Result of middleware execution
157
*/
158
function executeMiddleware<T>(
159
middlewares: AnyFunctionMiddleware[],
160
context: T
161
): Promise<T>;
162
```
163
164
### Server Function Context
165
166
Access server-side context within server functions, including request information and execution environment.
167
168
```typescript { .api }
169
interface ServerFnCtx {
170
/** HTTP request object */
171
request: Request;
172
/** HTTP response headers */
173
headers: Headers;
174
/** Server-side execution context */
175
context: Record<string, any>;
176
}
177
```
178
179
### Response Utilities
180
181
Utilities for creating and manipulating HTTP responses from server functions.
182
183
```typescript { .api }
184
/**
185
* Create a JSON response with proper headers
186
* @param data - The data to serialize as JSON
187
* @param options - Response options including status and headers
188
* @returns JSON response object
189
*/
190
function json<T>(
191
data: T,
192
options?: {
193
status?: number;
194
headers?: HeadersInit;
195
}
196
): JsonResponse;
197
198
/**
199
* Merge multiple header objects into one
200
* @param headers - Array of header objects to merge
201
* @returns Merged headers object
202
*/
203
function mergeHeaders(...headers: HeadersInit[]): Headers;
204
205
/**
206
* Perform client-side hydration of server state
207
* @param router - The router instance to hydrate
208
* @returns Promise resolving to hydrated router
209
*/
210
function hydrate<T>(router: T): Promise<T>;
211
```
212
213
## Types
214
215
```typescript { .api }
216
// HTTP methods supported by server functions
217
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
218
219
// Server function interface
220
interface ServerFn<TRegister, TMethod extends Method, TResponse> {
221
(...args: any[]): Promise<TResponse>;
222
url: string;
223
functionId: string;
224
method: TMethod;
225
}
226
227
// Server function context
228
interface ServerFnCtx {
229
request: Request;
230
headers: Headers;
231
context: Record<string, any>;
232
}
233
234
// Middleware function type
235
interface MiddlewareFn<TInput, TOutput> {
236
(input: TInput, context: ServerFnCtx): Promise<TOutput> | TOutput;
237
}
238
239
// Server function builder options
240
interface ServerFnBaseOptions<TRegister, TMethod, TResponse, TMiddlewares, TInputValidator> {
241
method?: TMethod;
242
middleware?: TMiddlewares;
243
inputValidator?: TInputValidator;
244
handler?: (...args: any[]) => Promise<TResponse> | TResponse;
245
}
246
247
// Fetcher configuration for server functions
248
interface CompiledFetcherFnOptions {
249
method: Method;
250
headers?: HeadersInit;
251
body?: BodyInit;
252
}
253
254
interface CompiledFetcherFn {
255
(url: string, options: CompiledFetcherFnOptions): Promise<Response>;
256
}
257
258
interface Fetcher {
259
fn: CompiledFetcherFn;
260
options: CompiledFetcherFnOptions;
261
}
262
263
// JSON response type
264
interface JsonResponse {
265
json(): any;
266
status: number;
267
headers: Headers;
268
ok: boolean;
269
statusText: string;
270
}
271
272
// Dehydrated router state for SSR
273
interface DehydratedRouter {
274
state: Record<string, any>;
275
manifest: Record<string, any>;
276
}
277
```
278
279
## Constants
280
281
```typescript { .api }
282
// Server function markers and headers
283
const TSS_SERVER_FUNCTION: unique symbol;
284
const TSS_FORMDATA_CONTEXT: string;
285
const X_TSS_SERIALIZED: string;
286
```