0
# Server Utilities
1
2
Server-side utilities for handling requests, creating handlers, and managing server operations within TanStack Start applications.
3
4
## Capabilities
5
6
### Request Handler Creation
7
8
Create and configure request handlers for server-side operations.
9
10
```typescript { .api }
11
/**
12
* Creates a start handler for server-side request processing
13
* @param options - Configuration options for the handler
14
* @returns Request handler function
15
*/
16
function createStartHandler(
17
options?: { streamHandler?: StreamHandler }
18
): RequestHandler<Register>;
19
20
/**
21
* Handle server actions and provide proper error handling
22
* @param action - The server action to handle
23
* @returns Promise resolving to action result
24
*/
25
function handleServerAction<T>(action: T): Promise<T>;
26
27
/**
28
* Create a request handler with custom logic
29
* @param handler - Function to handle the request
30
* @returns Request handler with proper typing
31
*/
32
function requestHandler<TRegister>(
33
handler: (request: Request) => Response | Promise<Response>
34
): RequestHandler<TRegister>;
35
```
36
37
**Usage Examples:**
38
39
```typescript
40
import { createStartHandler, requestHandler } from "@tanstack/react-start/server";
41
42
// Basic start handler
43
const handler = createStartHandler();
44
45
// Custom request handler
46
const apiHandler = requestHandler(async (request) => {
47
if (request.url.includes("/api/")) {
48
return new Response(JSON.stringify({ message: "API endpoint" }), {
49
headers: { "Content-Type": "application/json" }
50
});
51
}
52
return new Response("Not found", { status: 404 });
53
});
54
55
// Handler with custom stream handler
56
const streamHandler = createStartHandler({
57
streamHandler: (readable) => {
58
// Custom streaming logic
59
return readable;
60
}
61
});
62
```
63
64
### Request Context Access
65
66
Access request information and context within server functions.
67
68
```typescript { .api }
69
/**
70
* Get the current request object
71
* @returns Current HTTP request
72
*/
73
function getRequest(): Request;
74
75
/**
76
* Get all request headers as an object
77
* @returns Object containing all request headers
78
*/
79
function getRequestHeaders(): Record<string, string>;
80
81
/**
82
* Get a specific request header by name
83
* @param name - Header name to retrieve
84
* @returns Header value or undefined
85
*/
86
function getRequestHeader(name: string): string | undefined;
87
88
/**
89
* Get the client IP address from the request
90
* @param options - Options for IP detection
91
* @returns Client IP address or undefined
92
*/
93
function getRequestIP(options?: { ipHeader?: string }): string | undefined;
94
```
95
96
**Usage Examples:**
97
98
```typescript
99
import {
100
getRequest,
101
getRequestHeaders,
102
getRequestHeader,
103
getRequestIP
104
} from "@tanstack/react-start";
105
106
// Access request information in a server function
107
const getUserInfo = createServerFn()
108
.handler(async () => {
109
const request = getRequest();
110
const headers = getRequestHeaders();
111
const userAgent = getRequestHeader("user-agent");
112
const clientIP = getRequestIP();
113
114
return {
115
method: request.method,
116
url: request.url,
117
userAgent,
118
clientIP,
119
headers
120
};
121
});
122
```
123
124
### Response Utilities
125
126
Utilities for creating and manipulating HTTP responses.
127
128
```typescript { .api }
129
/**
130
* Create a JSON response with proper headers
131
* @param data - Data to serialize as JSON
132
* @param options - Response options
133
* @returns JSON response object
134
*/
135
function json<T>(
136
data: T,
137
options?: { status?: number; headers?: HeadersInit }
138
): JsonResponse;
139
140
/**
141
* Merge multiple header objects into one
142
* @param headers - Header objects to merge
143
* @returns Merged headers object
144
*/
145
function mergeHeaders(...headers: HeadersInit[]): Headers;
146
```
147
148
**Usage Examples:**
149
150
```typescript
151
import { json, mergeHeaders } from "@tanstack/react-start";
152
153
// Create JSON responses
154
const getUsers = createServerFn()
155
.handler(async () => {
156
const users = await db.user.findMany();
157
158
return json(users, {
159
status: 200,
160
headers: { "Cache-Control": "max-age=300" }
161
});
162
});
163
164
// Merge headers from multiple sources
165
const createUser = createServerFn()
166
.handler(async (userData) => {
167
const user = await db.user.create({ data: userData });
168
169
const responseHeaders = mergeHeaders(
170
{ "Content-Type": "application/json" },
171
{ "X-User-ID": user.id },
172
{ "Cache-Control": "no-cache" }
173
);
174
175
return json(user, { headers: responseHeaders });
176
});
177
```
178
179
### Router Server-Side Utilities
180
181
Server-side utilities specific to TanStack Router integration.
182
183
```typescript { .api }
184
/**
185
* Attach router server-side SSR utilities
186
* @param router - Router instance to enhance
187
* @returns Enhanced router with SSR utilities
188
*/
189
function attachRouterServerSsrUtils<T>(router: T): T;
190
191
/**
192
* Transform readable stream with router context
193
* @param stream - Readable stream to transform
194
* @param router - Router instance
195
* @returns Transformed stream
196
*/
197
function transformReadableStreamWithRouter<T>(
198
stream: ReadableStream<T>,
199
router: any
200
): ReadableStream<T>;
201
202
/**
203
* Transform pipeable stream with router context
204
* @param stream - Pipeable stream to transform
205
* @param router - Router instance
206
* @returns Transformed stream
207
*/
208
function transformPipeableStreamWithRouter<T>(
209
stream: T,
210
router: any
211
): T;
212
```
213
214
### Server Context Management
215
216
Functions for managing server execution context.
217
218
```typescript { .api }
219
/**
220
* Get the global Start context
221
* @returns Global Start context object
222
*/
223
function getGlobalStartContext(): StartContext;
224
225
/**
226
* Get the current router instance
227
* @returns Router instance
228
*/
229
function getRouterInstance(): AnyRouter;
230
```
231
232
## Types
233
234
```typescript { .api }
235
// Request handler types
236
interface RequestHandler<TRegister> {
237
(request: Request): Promise<Response> | Response;
238
}
239
240
interface RequestOptions {
241
onError?: (error: Error) => Response | Promise<Response>;
242
onRequest?: (request: Request) => Request | Promise<Request>;
243
onResponse?: (response: Response) => Response | Promise<Response>;
244
}
245
246
// Stream handler types
247
interface StreamHandler {
248
(readable: ReadableStream): ReadableStream;
249
}
250
251
// JSON response type
252
interface JsonResponse {
253
json(): any;
254
status: number;
255
headers: Headers;
256
ok: boolean;
257
statusText: string;
258
}
259
260
// Start context type
261
interface StartContext {
262
request: Request;
263
response?: Response;
264
[key: string]: any;
265
}
266
267
// Router types
268
interface AnyRouter {
269
// Router implementation from TanStack Router
270
}
271
272
// Registration interface
273
interface Register {
274
// Extend this for custom type registration
275
}
276
```
277
278
## Constants
279
280
```typescript { .api }
281
// HTTP headers constants
282
const HEADERS: {
283
readonly CONTENT_TYPE: string;
284
readonly CACHE_CONTROL: string;
285
readonly X_TSS_SERIALIZED: string;
286
};
287
```