npm-tanstack--react-start

Description
Modern full-stack React framework with SSR, streaming, server functions, and API routes powered by TanStack Router and Vite.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-tanstack--react-start@1.132.0

server-functions.md docs/

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