0
# TanStack React Start
1
2
TanStack React Start is a modern full-stack React framework that provides server-side rendering (SSR), streaming, server functions, API routes, and integrated bundling capabilities built on top of TanStack Router and Vite. It enables developers to build scalable React applications with advanced features like type-safe server functions, real-time data streaming, and seamless client-server communication through RPC-style APIs.
3
4
## Package Information
5
6
- **Package Name**: @tanstack/react-start
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @tanstack/react-start`
10
11
## Core Imports
12
13
```typescript
14
import {
15
useServerFn,
16
createServerFn,
17
createIsomorphicFn,
18
createServerOnlyFn,
19
createClientOnlyFn,
20
createMiddleware,
21
createStart,
22
hydrate,
23
json,
24
mergeHeaders
25
} from "@tanstack/react-start";
26
```
27
28
For entry points:
29
```typescript
30
// Client-side components
31
import { StartClient, hydrateStart } from "@tanstack/react-start/client";
32
33
// Server-side components
34
import { StartServer, defaultStreamHandler, defaultRenderHandler } from "@tanstack/react-start/server";
35
36
// RPC functionality
37
import { createClientRpc } from "@tanstack/react-start/client-rpc";
38
import { createServerRpc } from "@tanstack/react-start/server-rpc";
39
40
// Vite plugin
41
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
42
```
43
44
## Basic Usage
45
46
```typescript
47
// 1. Server function example
48
import { createServerFn } from "@tanstack/react-start";
49
50
const getUser = createServerFn()
51
.handler(async (id: string) => {
52
// Server-only code
53
return await db.user.findUnique({ where: { id } });
54
});
55
56
// 2. Client usage of server function
57
import { useServerFn } from "@tanstack/react-start";
58
59
function UserProfile({ userId }: { userId: string }) {
60
const getUserFn = useServerFn(getUser);
61
const [user, setUser] = useState(null);
62
63
useEffect(() => {
64
getUserFn(userId).then(setUser);
65
}, [userId]);
66
67
return user ? <div>Hello, {user.name}!</div> : <div>Loading...</div>;
68
}
69
70
// 3. Vite configuration
71
import { defineConfig } from "vite";
72
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
73
74
export default defineConfig({
75
plugins: [tanstackStart()],
76
});
77
```
78
79
## Architecture
80
81
TanStack React Start is built around several key components:
82
83
- **Server Functions**: Type-safe functions that run on the server but can be called from the client
84
- **Isomorphic Functions**: Functions with different implementations for client and server environments
85
- **Middleware System**: Composable middleware for server function validation, authentication, and processing
86
- **SSR Components**: `StartClient` and `StartServer` for hydration and server-side rendering
87
- **RPC System**: Client-server communication layer with automatic serialization
88
- **Vite Integration**: Seamless development experience with hot module replacement and bundling
89
90
## Capabilities
91
92
### Server Functions
93
94
Create and manage server-side functions with full type safety and automatic serialization. Perfect for database operations, API calls, and server-side business logic.
95
96
```typescript { .api }
97
function createServerFn<TMethod extends Method>(
98
options?: { method?: TMethod }
99
): ServerFnBuilder<{}, TMethod>;
100
101
interface ServerFnBuilder<TRegister, TMethod extends Method> {
102
handler<TResponse>(
103
handler: (...args: any[]) => Promise<TResponse> | TResponse
104
): ServerFn<TRegister, TMethod, TResponse>;
105
middleware<TMiddleware>(
106
middleware: TMiddleware
107
): ServerFnBuilder<TRegister & TMiddleware, TMethod>;
108
inputValidator<TValidator>(
109
validator: TValidator
110
): ServerFnBuilder<TRegister & { validator: TValidator }, TMethod>;
111
}
112
113
function useServerFn<T extends (...args: any[]) => Promise<any>>(
114
serverFn: T
115
): (...args: Parameters<T>) => ReturnType<T>;
116
```
117
118
[Server Functions](./server-functions.md)
119
120
### Isomorphic Functions
121
122
Create functions with different implementations for client and server environments, enabling code that adapts to its execution context.
123
124
```typescript { .api }
125
function createIsomorphicFn(): IsomorphicFnBase;
126
127
interface IsomorphicFnBase {
128
server<TArgs extends Array<any>, TServer>(
129
serverImpl: (...args: TArgs) => TServer
130
): ServerOnlyFn<TArgs, TServer>;
131
client<TArgs extends Array<any>, TClient>(
132
clientImpl: (...args: TArgs) => TClient
133
): ClientOnlyFn<TArgs, TClient>;
134
}
135
136
function createServerOnlyFn<TArgs extends Array<any>, TServer>(
137
serverImpl: (...args: TArgs) => TServer
138
): ServerOnlyFn<TArgs, TServer>;
139
140
function createClientOnlyFn<TArgs extends Array<any>, TClient>(
141
clientImpl: (...args: TArgs) => TClient
142
): ClientOnlyFn<TArgs, TClient>;
143
```
144
145
[Isomorphic Functions](./isomorphic-functions.md)
146
147
### Middleware System
148
149
Build composable middleware for server functions to handle validation, authentication, logging, and other cross-cutting concerns.
150
151
```typescript { .api }
152
function createMiddleware<TType extends MiddlewareType>(
153
options?: { type?: TType }
154
): CreateMiddlewareResult<{}, TType>;
155
156
interface CreateMiddlewareResult<TRegister, TType> {
157
middleware<T>(middleware: T): CreateMiddlewareResult<TRegister & T, TType>;
158
inputValidator<T>(validator: T): CreateMiddlewareResult<TRegister & T, TType>;
159
client<T>(client: T): CreateMiddlewareResult<TRegister & T, TType>;
160
server<T>(server: T): CreateMiddlewareResult<TRegister & T, TType>;
161
}
162
```
163
164
[Middleware](./middleware.md)
165
166
### SSR Components
167
168
React components for server-side rendering and client-side hydration with streaming support.
169
170
```typescript { .api }
171
function StartClient(): JSX.Element;
172
function StartServer<TRouter extends AnyRouter>(props: {
173
router: TRouter;
174
}): JSX.Element;
175
176
function createStartHandler(
177
streamHandler?: StreamHandler
178
): RequestHandler<Register>;
179
180
function defaultStreamHandler(): StreamHandler;
181
function defaultRenderHandler(): RenderHandler;
182
```
183
184
[SSR Components](./ssr-components.md)
185
186
### RPC System
187
188
Type-safe client-server RPC communication with automatic serialization and request handling.
189
190
```typescript { .api }
191
function createClientRpc(
192
functionId: string,
193
fetcher: (...args: any[]) => Promise<any>
194
): ClientRpc;
195
196
function createServerRpc(
197
functionId: string,
198
splitImportFn: (...args: any[]) => any
199
): ServerRpc;
200
```
201
202
[RPC System](./rpc-system.md)
203
204
### Core Utilities
205
206
Core utilities for application initialization, hydration, and response handling.
207
208
```typescript { .api }
209
function createStart<TOptions>(
210
options?: TOptions
211
): StartInstance<TOptions>;
212
213
function hydrate<T>(data: T): Promise<T>;
214
215
function json<T>(
216
data: T,
217
options?: { status?: number; headers?: HeadersInit }
218
): JsonResponse;
219
220
function mergeHeaders(...headers: HeadersInit[]): Headers;
221
```
222
223
### Request/Response Utilities
224
225
Utilities for accessing request information and handling server-side operations.
226
227
```typescript { .api }
228
function getRequest(): Request;
229
function getRequestHeaders(): Record<string, string>;
230
function getRequestHeader(name: string): string | undefined;
231
function getRequestIP(options?: { ipHeader?: string }): string | undefined;
232
```
233
234
[Request/Response Utilities](./request-response.md)
235
236
### Server Handler Creation
237
238
Functions for creating request handlers and managing server-side operations.
239
240
```typescript { .api }
241
function createStartHandler(
242
options?: { streamHandler?: StreamHandler }
243
): RequestHandler<Register>;
244
245
function handleServerAction<T>(action: T): Promise<T>;
246
247
function requestHandler<TRegister>(
248
handler: (request: Request) => Response | Promise<Response>
249
): RequestHandler<TRegister>;
250
```
251
252
[Server Utilities](./server-utilities.md)
253
254
### Vite Integration
255
256
Vite plugin for seamless integration with TanStack Start, providing automatic configuration and development tools.
257
258
```typescript { .api }
259
function tanstackStart(
260
options?: TanStackStartInputConfig
261
): Array<PluginOption>;
262
263
interface TanStackStartInputConfig {
264
framework?: 'react';
265
defaultEntryPaths?: {
266
client?: string;
267
server?: string;
268
start?: string;
269
};
270
// Additional configuration options
271
}
272
```
273
274
[Vite Plugin](./vite-plugin.md)
275
276
## Types
277
278
```typescript { .api }
279
// Core server function types
280
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
281
282
interface ServerFn<TRegister, TMethod extends Method, TResponse> {
283
(...args: any[]): Promise<TResponse>;
284
url: string;
285
functionId: string;
286
}
287
288
interface ServerFnBuilder<TRegister, TMethod extends Method> {
289
handler<TResponse>(
290
handler: (...args: any[]) => Promise<TResponse> | TResponse
291
): ServerFn<TRegister, TMethod, TResponse>;
292
middleware<TMiddleware>(
293
middleware: TMiddleware
294
): ServerFnBuilder<TRegister & TMiddleware, TMethod>;
295
inputValidator<TValidator>(
296
validator: TValidator
297
): ServerFnBuilder<TRegister & { validator: TValidator }, TMethod>;
298
}
299
300
// Isomorphic function types
301
interface IsomorphicFn<TArgs extends Array<any>, TServer, TClient> {
302
(...args: TArgs): TServer | TClient;
303
}
304
305
interface ServerOnlyFn<TArgs extends Array<any>, TServer>
306
extends IsomorphicFn<TArgs, TServer> {
307
client<TClient>(
308
clientImpl: (...args: TArgs) => TClient
309
): IsomorphicFn<TArgs, TServer, TClient>;
310
}
311
312
interface ClientOnlyFn<TArgs extends Array<any>, TClient>
313
extends IsomorphicFn<TArgs, undefined, TClient> {
314
server<TServer>(
315
serverImpl: (...args: TArgs) => TServer
316
): IsomorphicFn<TArgs, TServer, TClient>;
317
}
318
319
interface IsomorphicFnBase {
320
server<TArgs extends Array<any>, TServer>(
321
serverImpl: (...args: TArgs) => TServer
322
): ServerOnlyFn<TArgs, TServer>;
323
client<TArgs extends Array<any>, TClient>(
324
clientImpl: (...args: TArgs) => TClient
325
): ClientOnlyFn<TArgs, TClient>;
326
}
327
328
// Middleware types
329
interface FunctionMiddleware<TRegister = {}, TMethod extends Method = Method> {
330
// Middleware implementation details
331
}
332
333
interface RequestMiddleware {
334
// Request middleware implementation
335
}
336
337
type AnyFunctionMiddleware = FunctionMiddleware<any, any>;
338
type AnyRequestMiddleware = RequestMiddleware;
339
340
// Session management types
341
interface SessionManager<T> {
342
get(): Promise<T | undefined>;
343
update(updater: (current: T | undefined) => T): Promise<void>;
344
clear(): Promise<void>;
345
}
346
347
interface SessionOptions {
348
cookie?: {
349
domain?: string;
350
httpOnly?: boolean;
351
maxAge?: number;
352
path?: string;
353
sameSite?: 'strict' | 'lax' | 'none';
354
secure?: boolean;
355
};
356
}
357
358
// Cookie management types
359
interface CookieOptions {
360
domain?: string;
361
expires?: Date;
362
httpOnly?: boolean;
363
maxAge?: number;
364
path?: string;
365
sameSite?: 'strict' | 'lax' | 'none';
366
secure?: boolean;
367
}
368
369
// Request/Response types
370
interface RequestHandler<T> {
371
(request: Request): Promise<Response>;
372
}
373
374
interface RequestOptions {
375
onError?: (error: Error) => Response | Promise<Response>;
376
onRequest?: (request: Request) => Request | Promise<Request>;
377
onResponse?: (response: Response) => Response | Promise<Response>;
378
}
379
380
// Router types
381
interface AnyRouter {
382
// Router implementation details from TanStack Router
383
}
384
385
// Response types
386
interface JsonResponse {
387
json(): any;
388
status: number;
389
headers: Headers;
390
}
391
392
interface DehydratedRouter {
393
// Dehydrated router state
394
}
395
396
// Start instance types
397
interface StartInstance<TSerializationAdapters = any, TDefaultSsr = any, TRequestMiddlewares = any, TFunctionMiddlewares = any> {
398
getOptions(): StartInstanceOptions<TSerializationAdapters, TDefaultSsr, TRequestMiddlewares, TFunctionMiddlewares>;
399
}
400
401
interface StartInstanceOptions<TSerializationAdapters, TDefaultSsr, TRequestMiddlewares, TFunctionMiddlewares> {
402
// Start instance configuration options
403
}
404
405
type AnyStartInstance = StartInstance<any, any, any, any>;
406
type AnyStartInstanceOptions = StartInstanceOptions<any, any, any, any>;
407
408
// RPC types
409
interface ClientRpc {
410
// Client RPC implementation
411
}
412
413
interface ServerRpc {
414
// Server RPC implementation
415
}
416
417
// Vite plugin types
418
interface TanStackStartInputConfig {
419
framework?: 'react';
420
defaultEntryPaths?: {
421
client?: string;
422
server?: string;
423
start?: string;
424
};
425
[key: string]: any;
426
}
427
428
interface PluginOption {
429
name: string;
430
configResolved?: (config: any) => void;
431
configureServer?: (server: any) => void;
432
buildStart?: (options: any) => void;
433
transform?: (code: string, id: string) => any;
434
}
435
436
// Registration interface for type augmentation
437
interface Register {
438
// Extend this interface to register custom types
439
}
440
```