0
# Server APIs
1
2
Server-side functionality for rendering React Server Components to streams with client communication support and manifest-based module resolution.
3
4
## Capabilities
5
6
### Render to Readable Stream
7
8
Renders React Server Components to a ReadableStream for browser and edge environments with streaming support.
9
10
```javascript { .api }
11
/**
12
* Renders server components to a readable stream
13
* @param model - React server component tree to render
14
* @param webpackMap - Client manifest for module resolution
15
* @param options - Optional rendering configuration
16
* @returns ReadableStream containing rendered component data
17
*/
18
function renderToReadableStream(
19
model: ReactClientValue,
20
webpackMap: ClientManifest,
21
options?: ServerOptions
22
): ReadableStream;
23
```
24
25
**Usage Example:**
26
27
```javascript
28
import { renderToReadableStream } from "react-server-dom-webpack/server.browser";
29
30
// Render server component to stream
31
async function handleRequest(request) {
32
const clientManifest = JSON.parse(await fs.readFile("./react-client-manifest.json"));
33
34
const stream = renderToReadableStream(
35
<App userId={request.params.userId} />,
36
clientManifest,
37
{
38
onError: (error) => {
39
console.error("RSC rendering error:", error);
40
},
41
identifierPrefix: "rsc-"
42
}
43
);
44
45
return new Response(stream, {
46
headers: {
47
"Content-Type": "text/x-component",
48
"Cache-Control": "no-cache"
49
}
50
});
51
}
52
```
53
54
### Render to Pipeable Stream
55
56
Renders React Server Components to a Node.js PipeableStream for server environments with pipe and abort capabilities.
57
58
```javascript { .api }
59
/**
60
* Renders server components to a pipeable stream for Node.js
61
* @param model - React server component tree to render
62
* @param webpackMap - Client manifest for module resolution
63
* @param options - Optional rendering configuration
64
* @returns PipeableStream with pipe and abort methods
65
*/
66
function renderToPipeableStream(
67
model: ReactClientValue,
68
webpackMap: ClientManifest,
69
options?: ServerOptions
70
): PipeableStream;
71
```
72
73
**Usage Example:**
74
75
```javascript
76
import { renderToPipeableStream } from "react-server-dom-webpack/server.node";
77
import { createWriteStream } from "fs";
78
79
// Render to Node.js stream
80
const clientManifest = JSON.parse(fs.readFileSync("./react-client-manifest.json"));
81
82
const { pipe, abort } = renderToPipeableStream(
83
<ServerApp data={serverData} />,
84
clientManifest,
85
{
86
onError: (error) => {
87
console.error("Server rendering error:", error);
88
},
89
signal: abortController.signal
90
}
91
);
92
93
// Pipe to response or file
94
pipe(response);
95
96
// Abort if needed
97
setTimeout(() => abort("timeout"), 10000);
98
```
99
100
### Decode Reply
101
102
Decodes client-to-server data transmitted from the client, supporting various formats.
103
104
```javascript { .api }
105
/**
106
* Decodes client data sent to the server
107
* @param body - Request body containing encoded client data
108
* @param webpackMap - Server manifest for module resolution
109
* @param options - Optional temporary references for decoding
110
* @returns Promise resolving to decoded client data
111
*/
112
function decodeReply<T>(
113
body: string | FormData,
114
webpackMap: ServerManifest,
115
options?: {temporaryReferences?: TemporaryReferenceSet}
116
): Thenable<T>;
117
```
118
119
**Usage Example:**
120
121
```javascript
122
import { decodeReply } from "react-server-dom-webpack/server.browser";
123
124
// Handle server action request
125
async function handleServerAction(request) {
126
const serverManifest = JSON.parse(await fs.readFile("./react-ssr-manifest.json"));
127
128
// Decode client data
129
const clientData = await decodeReply(
130
await request.formData(),
131
serverManifest
132
);
133
134
// Process the action
135
const result = await processAction(clientData);
136
137
return Response.json(result);
138
}
139
```
140
141
### Decode Reply from Busboy
142
143
Decodes multipart form data using busboy for Node.js environments, handling file uploads and complex data.
144
145
```javascript { .api }
146
/**
147
* Decodes multipart form data using busboy
148
* @param busboyStream - Busboy stream containing multipart data
149
* @param bundlerConfig - Optional server manifest for module resolution
150
* @returns Promise resolving to decoded form data
151
*/
152
function decodeReplyFromBusboy(
153
busboyStream: any,
154
bundlerConfig?: ServerManifest
155
): Promise<any>;
156
```
157
158
**Usage Example:**
159
160
```javascript
161
import { decodeReplyFromBusboy } from "react-server-dom-webpack/server.node";
162
import busboy from "busboy";
163
164
// Handle multipart form upload
165
async function handleUpload(request) {
166
const bb = busboy({ headers: request.headers });
167
168
const formData = await decodeReplyFromBusboy(bb, serverManifest);
169
170
// Process uploaded files and data
171
const { files, fields } = formData;
172
return processUpload(files, fields);
173
}
174
```
175
176
### Decode Action
177
178
Decodes form actions submitted from the client, returning executable action functions.
179
180
```javascript { .api }
181
/**
182
* Decodes form action from client submission
183
* @param body - FormData containing action information
184
* @param bundlerConfig - Optional server manifest for module resolution
185
* @returns Promise resolving to executable action function or null
186
*/
187
function decodeAction(
188
body: FormData,
189
bundlerConfig?: ServerManifest
190
): Promise<() => any> | null;
191
```
192
193
**Usage Example:**
194
195
```javascript
196
import { decodeAction } from "react-server-dom-webpack/server.browser";
197
198
// Handle form action
199
async function handleFormAction(request) {
200
const formData = await request.formData();
201
const action = await decodeAction(formData, serverManifest);
202
203
if (action) {
204
// Execute the decoded action
205
const result = await action();
206
return Response.json(result);
207
}
208
209
return new Response("Invalid action", { status: 400 });
210
}
211
```
212
213
### Decode Form State
214
215
Decodes form state information for progressive enhancement scenarios.
216
217
```javascript { .api }
218
/**
219
* Decodes form state from action result and form data
220
* @param actionResult - Result from previous action execution
221
* @param body - FormData containing form state
222
* @param bundlerConfig - Optional server manifest for module resolution
223
* @returns Decoded form state
224
*/
225
function decodeFormState(
226
actionResult: any,
227
body: FormData,
228
bundlerConfig?: ServerManifest
229
): any;
230
```
231
232
**Usage Example:**
233
234
```javascript
235
import { decodeFormState } from "react-server-dom-webpack/server.browser";
236
237
// Handle progressive form enhancement
238
async function handleFormState(request, previousResult) {
239
const formData = await request.formData();
240
241
const formState = decodeFormState(
242
previousResult,
243
formData,
244
serverManifest
245
);
246
247
return renderFormWithState(formState);
248
}
249
```
250
251
### Server Reference Management
252
253
Functions for registering and managing server-side function references.
254
255
```javascript { .api }
256
/**
257
* Registers a server function reference
258
* @param reference - Function to register as server reference
259
* @param id - Unique identifier for the function
260
* @param exportName - Export name of the function
261
* @returns Registered function reference
262
*/
263
function registerServerReference(
264
reference: Function,
265
id: string,
266
exportName: string | null
267
): Function;
268
269
/**
270
* Registers a client component reference
271
* @param reference - Component reference to register
272
* @param id - Unique identifier for the component
273
* @param exportName - Export name of the component
274
* @returns Registered component reference
275
*/
276
function registerClientReference(
277
reference: any,
278
id: string,
279
exportName: string | null
280
): any;
281
282
/**
283
* Creates a proxy for client module references
284
* @param moduleId - Module identifier for the client component
285
* @returns Proxy object for client module
286
*/
287
function createClientModuleProxy(moduleId: string): any;
288
```
289
290
**Usage Example:**
291
292
```javascript
293
import { registerServerReference, registerClientReference } from "react-server-dom-webpack/server.node";
294
295
// Register server function
296
const serverAction = registerServerReference(
297
async function updateUser(data) {
298
return await database.updateUser(data);
299
},
300
"user-actions#updateUser",
301
"updateUser"
302
);
303
304
// Register client component
305
const ClientButton = registerClientReference(
306
ButtonComponent,
307
"components/Button.tsx",
308
"Button"
309
);
310
```
311
312
### Temporary Reference Management
313
314
Server-side temporary reference management for complex object serialization.
315
316
```javascript { .api }
317
/**
318
* Creates a set for tracking temporary references on the server
319
* @returns TemporaryReferenceSet for server-side reference tracking
320
*/
321
function createTemporaryReferenceSet(): TemporaryReferenceSet;
322
```
323
324
**Usage Example:**
325
326
```javascript
327
import { createTemporaryReferenceSet, renderToReadableStream } from "react-server-dom-webpack/server.browser";
328
329
// Use temporary references for complex object handling
330
const tempRefs = createTemporaryReferenceSet();
331
332
const stream = renderToReadableStream(
333
<App complexData={circularObject} />,
334
clientManifest,
335
{
336
temporaryReferences: tempRefs
337
}
338
);
339
```
340
341
## Types
342
343
```javascript { .api }
344
interface ServerOptions {
345
/** Error handling callback */
346
onError?: (error: Error) => void;
347
/** Postpone handling callback */
348
onPostpone?: (reason: string) => void;
349
/** Prefix for generated identifiers */
350
identifierPrefix?: string;
351
/** AbortSignal for cancelling rendering */
352
signal?: AbortSignal;
353
/** Temporary references for complex object serialization */
354
temporaryReferences?: TemporaryReferenceSet;
355
/** Environment name for development tools */
356
environmentName?: string | (() => string);
357
/** Filter stack frames in error reporting */
358
filterStackFrame?: (url: string, functionName: string) => boolean;
359
}
360
361
interface PipeableStream {
362
/** Pipe the stream to a writable destination */
363
pipe(destination: NodeJS.WritableStream): void;
364
/** Abort the rendering process */
365
abort(reason?: string): void;
366
}
367
368
type ReactServerValue = any;
369
type ClientManifest = Record<string, ImportManifestEntry>;
370
type ServerManifest = Record<string, any>;
371
type TemporaryReferenceSet = any;
372
373
interface ImportManifestEntry {
374
id: string;
375
chunks: string[];
376
name: string;
377
}
378
```