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

ssr-components.md docs/

1
# SSR Components
2
3
SSR (Server-Side Rendering) components provide the foundation for rendering React applications on both server and client sides. These components handle hydration, streaming, and the coordination between server and client rendering processes.
4
5
## Capabilities
6
7
### StartClient Component
8
9
The main client-side React component that handles hydration and router initialization for client-side rendering.
10
11
```typescript { .api }
12
/**
13
* Client-side root component for hydrating the application
14
* Automatically handles router hydration and initial render
15
* @returns JSX.Element - The hydrated client application
16
*/
17
function StartClient(): JSX.Element;
18
```
19
20
**Usage Examples:**
21
22
```typescript
23
import { StrictMode, startTransition } from "react";
24
import { hydrateRoot } from "react-dom/client";
25
import { StartClient } from "@tanstack/react-start/client";
26
27
// Basic client hydration
28
startTransition(() => {
29
hydrateRoot(
30
document,
31
<StrictMode>
32
<StartClient />
33
</StrictMode>
34
);
35
});
36
37
// Custom root element hydration
38
const rootElement = document.getElementById("app");
39
if (rootElement) {
40
hydrateRoot(rootElement, <StartClient />);
41
}
42
```
43
44
### StartServer Component
45
46
The main server-side React component that provides the router for server-side rendering.
47
48
```typescript { .api }
49
/**
50
* Server-side root component for SSR
51
* @param props - Configuration object with router instance
52
* @returns JSX.Element - The server-rendered application
53
*/
54
function StartServer<TRouter extends AnyRouter>(props: {
55
router: TRouter;
56
}): JSX.Element;
57
58
interface AnyRouter {
59
// Router instance from TanStack Router
60
state: RouterState;
61
options: RouterOptions;
62
history: RouterHistory;
63
}
64
```
65
66
**Usage Examples:**
67
68
```typescript
69
import { StartServer } from "@tanstack/react-start/server";
70
import { createRouter } from "@tanstack/react-router";
71
72
// Create router instance
73
const router = createRouter({
74
routeTree: rootRoute,
75
context: {
76
// Server context
77
}
78
});
79
80
// Server-side rendering
81
function renderApp() {
82
return <StartServer router={router} />;
83
}
84
85
// In server handler
86
export default {
87
fetch: async (request) => {
88
const html = ReactDOMServer.renderToString(<StartServer router={router} />);
89
return new Response(html, {
90
headers: { "content-type": "text/html" }
91
});
92
}
93
};
94
```
95
96
### Create Start Handler
97
98
Creates a request handler for the server that processes incoming requests and renders the application.
99
100
```typescript { .api }
101
/**
102
* Creates the main request handler for server-side processing
103
* @param streamHandler - Optional custom streaming handler
104
* @returns RequestHandler for processing HTTP requests
105
*/
106
function createStartHandler(
107
streamHandler?: StreamHandler
108
): RequestHandler<Register>;
109
110
interface RequestHandler<TRegister> {
111
(request: Request): Promise<Response>;
112
router?: AnyRouter;
113
}
114
115
interface StreamHandler {
116
(renderOptions: RenderOptions): ReadableStream | Promise<ReadableStream>;
117
}
118
119
interface RenderOptions {
120
router: AnyRouter;
121
request: Request;
122
responseHeaders: Headers;
123
}
124
```
125
126
**Usage Examples:**
127
128
```typescript
129
import {
130
createStartHandler,
131
defaultStreamHandler
132
} from "@tanstack/react-start/server";
133
134
// Basic server handler
135
const handler = createStartHandler();
136
137
export default {
138
fetch: handler
139
};
140
141
// Custom streaming handler
142
const customHandler = createStartHandler((options) => {
143
// Custom streaming logic
144
return new ReadableStream({
145
start(controller) {
146
// Custom rendering logic
147
const html = renderToString(<StartServer router={options.router} />);
148
controller.enqueue(new TextEncoder().encode(html));
149
controller.close();
150
}
151
});
152
});
153
154
// Advanced server setup
155
const handler = createStartHandler(defaultStreamHandler);
156
157
export default {
158
fetch: async (request, env) => {
159
// Add custom headers or processing
160
const response = await handler(request);
161
response.headers.set("X-Powered-By", "TanStack Start");
162
return response;
163
}
164
};
165
```
166
167
### Default Stream Handler
168
169
Provides the default streaming implementation for server-side rendering with proper error handling and response streaming.
170
171
```typescript { .api }
172
/**
173
* Default streaming handler for SSR with error handling
174
* @returns StreamHandler that processes render options and returns a stream
175
*/
176
function defaultStreamHandler(): StreamHandler;
177
```
178
179
**Usage Examples:**
180
181
```typescript
182
import {
183
createStartHandler,
184
defaultStreamHandler
185
} from "@tanstack/react-start/server";
186
187
// Use default streaming
188
const handler = createStartHandler(defaultStreamHandler());
189
190
// Extend default streaming
191
const extendedHandler = createStartHandler(
192
async (options) => {
193
console.log(`Rendering ${options.request.url}`);
194
return await defaultStreamHandler()(options);
195
}
196
);
197
```
198
199
### Default Render Handler
200
201
Provides the default rendering implementation for server-side rendering without streaming.
202
203
```typescript { .api }
204
/**
205
* Default render handler for non-streaming SSR
206
* @returns RenderHandler that processes render options and returns HTML
207
*/
208
function defaultRenderHandler(): RenderHandler;
209
210
interface RenderHandler {
211
(renderOptions: RenderOptions): string | Promise<string>;
212
}
213
```
214
215
**Usage Examples:**
216
217
```typescript
218
import { defaultRenderHandler } from "@tanstack/react-start/server";
219
220
// Custom non-streaming handler
221
const renderHandler = defaultRenderHandler();
222
223
async function customRenderToString(options) {
224
const html = await renderHandler(options);
225
return `<!DOCTYPE html><html><body>${html}</body></html>`;
226
}
227
```
228
229
### Server Utilities
230
231
Additional server-side utilities for advanced SSR scenarios.
232
233
```typescript { .api }
234
/**
235
* Attach server-side SSR utilities to a router instance
236
* @param router - The router to enhance with SSR capabilities
237
* @returns Enhanced router with SSR utilities
238
*/
239
function attachRouterServerSsrUtils<T extends AnyRouter>(
240
router: T
241
): T & ServerSsrUtils;
242
243
/**
244
* Create a generic request handler with custom configuration
245
* @param options - Handler configuration options
246
* @returns Configured request handler
247
*/
248
function createRequestHandler<T>(
249
options: RequestHandlerOptions<T>
250
): RequestHandler<T>;
251
252
/**
253
* Define a handler callback for custom server processing
254
* @param callback - The handler callback function
255
* @returns Configured handler callback
256
*/
257
function defineHandlerCallback<T>(
258
callback: HandlerCallback<T>
259
): HandlerCallback<T>;
260
261
/**
262
* Transform a ReadableStream with router context
263
* @param stream - The stream to transform
264
* @param router - Router instance for context
265
* @returns Transformed stream with router utilities
266
*/
267
function transformReadableStreamWithRouter(
268
stream: ReadableStream,
269
router: AnyRouter
270
): ReadableStream;
271
272
/**
273
* Transform a pipeable stream with router context
274
* @param stream - The pipeable stream to transform
275
* @param router - Router instance for context
276
* @returns Transformed pipeable stream
277
*/
278
function transformPipeableStreamWithRouter(
279
stream: any, // React's PipeableStream type
280
router: AnyRouter
281
): any;
282
```
283
284
### Client Hydration
285
286
Functions for handling client-side hydration and startup processes.
287
288
```typescript { .api }
289
/**
290
* Perform client-side hydration of the application
291
* @returns Promise resolving to the hydrated router instance
292
*/
293
function hydrateStart(): Promise<AnyRouter>;
294
295
/**
296
* Render React Server Components on the client
297
* @param components - RSC components to render
298
* @returns Rendered RSC content
299
*/
300
function renderRsc(components: any): any;
301
```
302
303
## Advanced Usage Patterns
304
305
### Custom Server Handler with Middleware
306
307
```typescript
308
import {
309
createStartHandler,
310
defaultStreamHandler
311
} from "@tanstack/react-start/server";
312
313
const handler = createStartHandler(defaultStreamHandler());
314
315
export default {
316
fetch: async (request) => {
317
// Add CORS headers
318
if (request.method === "OPTIONS") {
319
return new Response(null, {
320
status: 204,
321
headers: {
322
"Access-Control-Allow-Origin": "*",
323
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",
324
"Access-Control-Allow-Headers": "Content-Type, Authorization"
325
}
326
});
327
}
328
329
const response = await handler(request);
330
331
// Add security headers
332
response.headers.set("X-Frame-Options", "DENY");
333
response.headers.set("X-Content-Type-Options", "nosniff");
334
335
return response;
336
}
337
};
338
```
339
340
### Custom Streaming Implementation
341
342
```typescript
343
import { createStartHandler } from "@tanstack/react-start/server";
344
import { renderToPipeableStream } from "react-dom/server";
345
346
const customStreamHandler = (options) => {
347
return new ReadableStream({
348
start(controller) {
349
const stream = renderToPipeableStream(
350
<StartServer router={options.router} />,
351
{
352
onShellReady() {
353
controller.enqueue(new TextEncoder().encode("<!DOCTYPE html>"));
354
stream.pipe(new WritableStream({
355
write(chunk) {
356
controller.enqueue(chunk);
357
},
358
close() {
359
controller.close();
360
}
361
}));
362
},
363
onError(error) {
364
console.error("Stream error:", error);
365
controller.error(error);
366
}
367
}
368
);
369
}
370
});
371
};
372
373
const handler = createStartHandler(customStreamHandler);
374
```
375
376
## Types
377
378
```typescript { .api }
379
// Router types from TanStack Router
380
interface AnyRouter {
381
state: RouterState;
382
options: RouterOptions;
383
history: RouterHistory;
384
navigate: (options: any) => Promise<void>;
385
resolveRedirect: (redirect: any) => any;
386
}
387
388
// Request handler types
389
interface RequestHandler<TRegister> {
390
(request: Request): Promise<Response>;
391
router?: AnyRouter;
392
}
393
394
interface RequestOptions {
395
request: Request;
396
responseHeaders?: Headers;
397
context?: any;
398
}
399
400
// Streaming types
401
interface StreamHandler {
402
(renderOptions: RenderOptions): ReadableStream | Promise<ReadableStream>;
403
}
404
405
interface RenderHandler {
406
(renderOptions: RenderOptions): string | Promise<string>;
407
}
408
409
interface RenderOptions {
410
router: AnyRouter;
411
request: Request;
412
responseHeaders: Headers;
413
context?: any;
414
}
415
416
// Server utilities types
417
interface ServerSsrUtils {
418
dehydrate: () => DehydratedRouter;
419
serialize: (data: any) => string;
420
deserialize: (data: string) => any;
421
}
422
423
interface HandlerCallback<T> {
424
(context: T): Response | Promise<Response>;
425
}
426
427
interface RequestHandlerOptions<T> {
428
createRouter: () => AnyRouter;
429
getRouterContext?: (request: Request) => T;
430
onError?: (error: Error) => Response;
431
}
432
433
// Dehydrated state for SSR
434
interface DehydratedRouter {
435
state: Record<string, any>;
436
manifest: Record<string, any>;
437
context?: any;
438
}
439
```
440
441
## Constants
442
443
```typescript { .api }
444
// HTTP headers used by the SSR system
445
const HEADERS: {
446
readonly contentType: "Content-Type";
447
readonly location: "Location";
448
readonly cacheControl: "Cache-Control";
449
};
450
```