npm-tanstack--react-start

Description
SSR, Streaming, Server Functions, API Routes, bundling and more powered by TanStack Router and Vite. Ready to deploy to your favorite hosting provider.
Author
tessl
Last updated

How to use

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

client.md docs/

1
# Client-Side Framework
2
3
Client-side functionality for TanStack React Start, including the main application component, hooks for server function integration, and utilities for handling full-stack React applications with hydration and routing.
4
5
## Capabilities
6
7
### StartClient Component
8
9
Main client-side application component that handles hydration and provides the router context for React applications.
10
11
```typescript { .api }
12
/**
13
* Main client-side application component for TanStack Start
14
* Handles hydration of server-rendered content and provides router context
15
* @param props - Component props containing the router instance
16
* @returns JSX element with router provider and hydration handling
17
*/
18
function StartClient(props: { router: AnyRouter }): JSX.Element;
19
```
20
21
**Usage Example:**
22
23
```typescript
24
import { StartClient } from '@tanstack/react-start';
25
import { createRouter } from './router';
26
27
const router = createRouter();
28
29
function App() {
30
return <StartClient router={router} />;
31
}
32
```
33
34
### useServerFn Hook
35
36
React hook for calling server functions with automatic router integration and redirect handling.
37
38
```typescript { .api }
39
/**
40
* Hook for calling server functions with router integration
41
* Automatically handles redirects and router state updates
42
* @param serverFn - Server function to wrap
43
* @returns Function that calls the server function with redirect handling
44
*/
45
function useServerFn<T extends (...deps: Array<any>) => Promise<any>>(
46
serverFn: T
47
): (...args: Parameters<T>) => ReturnType<T>;
48
```
49
50
**Usage Examples:**
51
52
```typescript
53
import { useServerFn, createServerFn } from '@tanstack/react-start';
54
55
// Define server function
56
const getUserData = createServerFn().handler(async (userId: string) => {
57
return await database.getUser(userId);
58
});
59
60
// Use in component
61
function UserProfile({ userId }: { userId: string }) {
62
const fetchUser = useServerFn(getUserData);
63
const [user, setUser] = useState(null);
64
65
const loadUser = async () => {
66
try {
67
const userData = await fetchUser(userId);
68
setUser(userData);
69
} catch (error) {
70
console.error('Failed to load user:', error);
71
}
72
};
73
74
return (
75
<div>
76
<button onClick={loadUser}>Load User</button>
77
{user && <div>{user.name}</div>}
78
</div>
79
);
80
}
81
```
82
83
### Server Function Creation
84
85
Core functionality for creating server functions that can be called from client-side code.
86
87
```typescript { .api }
88
/**
89
* Creates a server function that can be called from client-side code
90
* @param options - Optional configuration for the server function
91
* @returns Server function builder for chaining configuration
92
*/
93
function createServerFn<TValidator = undefined, TMiddleware = []>(
94
options?: ServerFnBaseOptions<TValidator, TMiddleware>
95
): ServerFnBuilder<TValidator, TMiddleware>;
96
97
interface ServerFnBuilder<TValidator, TMiddleware> {
98
/** Configure HTTP method for the server function */
99
method<TMethod extends Method>(method: TMethod): ServerFnBuilder<TValidator, TMiddleware>;
100
/** Add validation to the server function */
101
validator<V>(validator: V): ServerFnBuilder<V, TMiddleware>;
102
/** Add middleware to the server function */
103
middleware<M>(middleware: M): ServerFnBuilder<TValidator, M>;
104
/** Define the handler function that runs on the server */
105
handler<THandlerFn extends Function>(handlerFn: THandlerFn): CompiledFetcherFn<THandlerFn>;
106
}
107
108
interface ServerFnBaseOptions<TValidator, TMiddleware> {
109
method?: Method;
110
validator?: TValidator;
111
middleware?: TMiddleware;
112
}
113
114
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
115
```
116
117
### Isomorphic Functions
118
119
Functions that can run on both client and server environments with different implementations.
120
121
```typescript { .api }
122
/**
123
* Creates a function that works on both client and server with different implementations
124
* @param clientFn - Function to run on the client
125
* @param serverFn - Function to run on the server
126
* @returns Isomorphic function that automatically chooses the correct implementation
127
*/
128
function createIsomorphicFn<TArgs extends Array<any>, TReturn>(
129
clientFn: (...args: TArgs) => TReturn,
130
serverFn: (...args: TArgs) => TReturn
131
): IsomorphicFn<TArgs, TReturn>;
132
133
interface IsomorphicFn<TArgs extends Array<any>, TReturn> {
134
(...args: TArgs): TReturn;
135
}
136
```
137
138
### Environment-Specific Functions
139
140
Utilities for marking functions as client-only or server-only.
141
142
```typescript { .api }
143
/**
144
* Marks a function as server-only, throwing an error if called on client
145
* @param fn - Function that should only run on the server
146
* @returns Server-only function wrapper
147
*/
148
function serverOnly<T extends Function>(fn: T): ServerOnlyFn<T>;
149
150
/**
151
* Marks a function as client-only, throwing an error if called on server
152
* @param fn - Function that should only run on the client
153
* @returns Client-only function wrapper
154
*/
155
function clientOnly<T extends Function>(fn: T): ClientOnlyFn<T>;
156
157
interface ServerOnlyFn<T extends Function> extends Function {
158
(): never; // Throws error on client
159
}
160
161
interface ClientOnlyFn<T extends Function> extends Function {
162
(): never; // Throws error on server
163
}
164
```
165
166
### Middleware System
167
168
Middleware creation and management for server functions.
169
170
```typescript { .api }
171
/**
172
* Creates middleware for server functions
173
* @param options - Middleware configuration options
174
* @returns Configured middleware function
175
*/
176
function createMiddleware<TOptions extends FunctionMiddlewareOptions>(
177
options: TOptions
178
): FunctionMiddlewareWithTypes<TOptions>;
179
180
/**
181
* Registers middleware globally for all server functions
182
* @param middleware - Middleware function to register globally
183
*/
184
function registerGlobalMiddleware(middleware: AnyFunctionMiddleware): void;
185
186
/** Global middleware registry */
187
const globalMiddleware: Array<AnyFunctionMiddleware>;
188
189
interface FunctionMiddlewareOptions {
190
validator?: any;
191
server?: Function;
192
client?: Function;
193
after?: Function;
194
}
195
196
interface FunctionMiddlewareWithTypes<TOptions> {
197
validator: TOptions['validator'];
198
server: TOptions['server'];
199
client: TOptions['client'];
200
after: TOptions['after'];
201
}
202
203
type AnyFunctionMiddleware = FunctionMiddlewareWithTypes<any>;
204
```
205
206
### Utility Functions
207
208
Core utility functions for data handling and serialization.
209
210
```typescript { .api }
211
/**
212
* Creates a JSON response with proper headers
213
* @param data - Data to serialize as JSON
214
* @param init - Optional response initialization options
215
* @returns Response object with JSON content
216
*/
217
function json<T = any>(data: T, init?: ResponseInit): JsonResponse<T>;
218
219
/**
220
* Merges multiple headers objects or Headers instances
221
* @param headers - Headers to merge
222
* @returns Merged Headers object
223
*/
224
function mergeHeaders(...headers: Array<HeadersInit | undefined>): Headers;
225
226
/**
227
* Hydrates client-side router with server-rendered data
228
* @param router - Router instance to hydrate
229
* @returns Promise that resolves when hydration is complete
230
*/
231
function hydrate(router: AnyRouter): Promise<void | Array<Array<void>>>;
232
233
interface JsonResponse<T = any> extends Response {
234
json(): Promise<T>;
235
}
236
```
237
238
### Serialization
239
240
Custom serialization system for complex data transfer between client and server.
241
242
```typescript { .api }
243
/** Start framework serializer for handling complex data types */
244
const startSerializer: StartSerializer;
245
246
interface StartSerializer {
247
stringify: SerializerStringify;
248
parse: SerializerParse;
249
stringifyBy: SerializerStringifyBy;
250
parseBy: SerializerParseBy;
251
}
252
253
interface SerializerStringify {
254
(value: Serializable): string;
255
}
256
257
interface SerializerParse {
258
(value: string): Serializable;
259
}
260
261
interface SerializerStringifyBy {
262
(key: string, value: Serializable): string;
263
}
264
265
interface SerializerParseBy {
266
(key: string, value: string): Serializable;
267
}
268
269
type Serializable =
270
| string
271
| number
272
| boolean
273
| null
274
| undefined
275
| Date
276
| RegExp
277
| Array<Serializable>
278
| { [key: string]: Serializable };
279
280
interface SerializerExtensions {
281
ReadableStream: React.JSX.Element;
282
}
283
```
284
285
### React Server Components (Experimental)
286
287
Experimental support for React Server Components.
288
289
```typescript { .api }
290
/**
291
* Renders React Server Components (experimental feature)
292
* @param input - RSC input data or stream
293
* @returns JSX element from server component
294
*/
295
function renderRsc(input: any): React.JSX.Element;
296
```
297
298
### Deprecated Components
299
300
Legacy components maintained for backwards compatibility.
301
302
```typescript { .api }
303
/**
304
* @deprecated Use HeadContent from @tanstack/react-router instead
305
* Legacy Meta component for head content management
306
*/
307
function Meta(): JSX.Element;
308
309
/**
310
* @deprecated Moved to @tanstack/react-router as Scripts component
311
* Legacy Scripts component for script injection
312
*/
313
function Scripts(): JSX.Element;
314
```
315
316
## Core Types
317
318
```typescript { .api }
319
interface AnyRouter {
320
state: {
321
matches: Array<any>;
322
location: any;
323
};
324
navigate: (options: any) => Promise<any>;
325
resolveRedirect: (redirect: any) => { options: any };
326
}
327
328
interface CompiledFetcherFn<THandlerFn> extends Function {
329
(...args: Parameters<THandlerFn>): Promise<ReturnType<THandlerFn>>;
330
url: string;
331
functionId: string;
332
}
333
334
interface DehydratedRouter {
335
dehydratedMatches: Array<any>;
336
[key: string]: any;
337
}
338
339
interface FetcherData<T = any> {
340
data: T;
341
error?: Error;
342
isLoading: boolean;
343
}
344
345
interface ServerFnCtx {
346
request: Request;
347
params: Record<string, string>;
348
data: FormData | any;
349
}
350
351
type ServerFnResponseType = Response | any;
352
353
interface RscStream extends ReadableStream {
354
[Symbol.toStringTag]: 'RscStream';
355
}
356
357
// Middleware types
358
interface FunctionMiddlewareClientFnOptions<TValidator, TContext> {
359
validator: TValidator;
360
context: TContext;
361
next: FunctionMiddlewareClientNextFn;
362
}
363
364
interface FunctionMiddlewareClientFnResult<TResult, TContext> {
365
result: TResult;
366
context: TContext;
367
}
368
369
interface FunctionMiddlewareClientNextFn {
370
(): Promise<any>;
371
}
372
373
interface FunctionClientResultWithContext<TResult, TContext> {
374
result: TResult;
375
context: TContext;
376
}
377
378
interface FunctionMiddlewareServerFnOptions<TValidator, TContext> {
379
validator: TValidator;
380
context: TContext;
381
next: FunctionMiddlewareServerNextFn;
382
}
383
384
interface FunctionMiddlewareServerFnResult<TResult, TContext> {
385
result: TResult;
386
context: TContext;
387
}
388
389
interface FunctionMiddlewareServerNextFn {
390
(): Promise<any>;
391
}
392
393
interface FunctionServerResultWithContext<TResult, TContext> {
394
result: TResult;
395
context: TContext;
396
}
397
```