Sub topic 6
What can cross the network: serialization rules
This chapter assumes you can write React components and hooks, use async/await, and read FormData. It also assumes you know the basic request and response flow of HTTP. You should have read the earlier chapters on what "use server" marks and on calling Server Functions from Client Components.
Why serialization matters
A Server Function looks like a normal function call from the client. The server and the client are separate processes, though, and a call crosses the network. React has to turn the arguments into bytes, send them, rebuild them on the server, run the function, and send the return value back the same way. This process is called serialization. Rebuilding the values is deserialization.
Not every JavaScript value can survive this trip. A function that closes over browser state, a class instance with methods, and a DOM node all depend on memory that exists in only one process. React rejects these values, usually with an error at the call site.
Supported argument types
React uses its own serialization format, not plain JSON. It supports more types than JSON.stringify, which is why a Date survives as a Date and a Map survives as a Map.
The React documentation lists these types as serializable arguments to a Server Function:
| Type | Notes |
|---|---|
| Primitives | `string`, `number`, `bigint`, `boolean`, `undefined`, `null` |
| Symbols | Only symbols registered globally with `Symbol.for` |
| Iterables of serializable values | `Array`, `Map`, `Set`, typed arrays, `ArrayBuffer`, and strings |
| `Date` | Rebuilt as a `Date`, not as a string |
| `FormData` | The usual argument for form actions |
| Plain objects | Created with `{}` or `new Object()`, with serializable properties |
| Server Functions | A reference to another Server Function can be passed as a value |
| Promises | A Promise of a serializable value |
The next table lists values that are not supported:
| Type | Why it fails |
|---|---|
| React elements (JSX) | They are not valid arguments to a Server Function |
| Functions that are not Server Functions | Their code and closed-over variables exist only on the sender |
| Class instances | Prototypes and methods are not transferred. Built-in types in the first table are the exception |
| Objects with a null prototype | They are not plain objects |
| Symbols not registered with `Symbol.for` | A local symbol has no identity on the other side |
Treat the table as a snapshot. Check the React reference for "use server" when you upgrade, because the supported set has grown between versions.
A function call with rich arguments
This Server Function takes a plain object that contains a Date and a Set. Both survive the trip.
// app/actions.js
'use server';
import { db } from './db';
export async function scheduleReminder({ title, dueAt, tags }) {
if (typeof title !== 'string' || title.trim() === '') {
throw new Error('Invalid title');
}
if (!(dueAt instanceof Date) || Number.isNaN(dueAt.getTime())) {
throw new Error('Invalid date');
}
if (!(tags instanceof Set)) {
throw new Error('Invalid tags');
}
await db.reminders.insert({
title: title.trim(),
dueAt,
tags: [...tags],
});
}The Client Component calls it like any function:
// app/ReminderButton.js
'use client';
import { useTransition } from 'react';
import { scheduleReminder } from './actions';
export function ReminderButton() {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
await scheduleReminder({
title: 'Review pull request',
dueAt: new Date(Date.now() + 60 * 60 * 1000),
tags: new Set(['work', 'code']),
});
});
}}
>
Remind me in one hour
</button>
);
}The instanceof checks in the first file are not paranoia. A client controls what it sends, and a hand-built request can put anything in dueAt. The security chapter covers this in depth. Here the point is that serialization only decides which shapes can travel. It does not prove the values are valid or trustworthy.
Class instances and other non-plain objects
A common mistake is passing a model object that came from an ORM or a class:
// app/models.js
export class Note {
constructor(id, title) {
this.id = id;
this.title = title;
}
get label() {
return `#${this.id}: ${this.title}`;
}
}If a Client Component holds a Note instance and passes it to a Server Function, serialization fails. The fix is to send only the data the server needs, as a plain object or as a single identifier.
// app/RenameButton.js
'use client';
import { useTransition } from 'react';
import { renameNote } from './actions';
export function RenameButton({ note }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
// Send plain values, not the Note instance.
await renameNote({ id: note.id, title: 'New title' });
});
}}
>
Rename
</button>
);
}Sending the identifier is usually the better design anyway. The server can load the current record itself, which avoids trusting a client-side copy that may be stale or altered.
Functions as arguments
You cannot pass an ordinary callback to a Server Function:
// This will fail: the arrow function is not a Server Function.
await runJob({ onProgress: (percent) => setProgress(percent) });The callback lives in the browser. The server cannot call into it. If the server needs to report progress, return a result and let the client act on it, or design an API that streams updates. A Server Function that is itself marked "use server" can be passed, because React sends a reference to it rather than its code.
Return values
Return values follow the same rule as props passed from a Server Component to a Client Component. Return plain data that React can serialize: primitives, plain objects, arrays, Date, Map, Set, and so on.
// app/actions.js
'use server';
import { db } from './db';
export async function findNotes(query) {
if (typeof query !== 'string') {
throw new Error('Invalid query');
}
const rows = await db.notes.search(query);
// Map rows to plain objects. Do not return ORM model instances.
return rows.map((row) => ({
id: String(row.id),
title: row.title,
createdAt: row.createdAt,
}));
}Mapping rows to plain objects has two benefits:
- It avoids serialization errors when the data layer returns class instances.
- It controls what leaves the server. Returning a whole database row can leak columns such as password hashes, internal flags, or other users' email addresses. The client receives everything you return.
Errors and what the client sees
An error thrown inside a Server Function does not travel back as a normal Error object with its original message in production. Frameworks typically replace the message with a generic one so that internal details do not leak. The exact behavior depends on the framework and on development or production mode.
This means a thrown error is a poor way to send a message such as "Title is required" to the user. For expected problems, return a plain object that describes the problem, as you saw with useActionState. Reserve throw for unexpected failures, which an error boundary should handle. The error handling chapter returns to this choice.
Files and large payloads
FormData can carry File entries from a form with <input type="file">. On the server, formData.get('avatar') returns a File. Check its type and size before you use it, because the client sets these values.
// app/actions.js
'use server';
export async function uploadAvatar(formData) {
const file = formData.get('avatar');
if (!(file instanceof File)) {
throw new Error('No file uploaded');
}
if (!['image/png', 'image/jpeg'].includes(file.type)) {
throw new Error('Unsupported file type');
}
if (file.size > 2 * 1024 * 1024) {
throw new Error('File is too large');
}
const bytes = await file.arrayBuffer();
// Store `bytes` using your storage layer.
}Servers and frameworks also limit the size of a request body. Next.js, for example, has a default limit of 1 MB for Server Actions, which you can change in its configuration. If a call fails only when the payload is large, check this limit before you suspect your code. Large uploads often go better through a dedicated upload route or a pre-signed URL to object storage.
Common errors
- Passing a class instance. Convert it to a plain object or send an ID.
- Passing a callback. Return data instead, or use a Server Function reference.
- Passing JSX or a React element. Send data and render it on the receiving side.
- Assuming JSON rules. React preserves
Date,Map, andSet, so do not re-parse them as strings. Do not assume that a value valid in JSON is a valid shape for your function either. Validate it. - Returning too much. Select fields explicitly.
- Relying on error messages. Return expected errors as data.
Exercise
A Client Component holds const user = new User('ada', 'Ada Lovelace'), where User is a class. It calls updateProfile(user), and the call fails with a serialization error. Name two ways to fix this, and say which one is safer with respect to stale or altered client data.
Show answer
Either send a plain object, such as updateProfile({ id: user.id, displayName: 'Ada' }), or send only the identifier and the changed value. Sending the identifier and loading the current record on the server is safer, because the server does not trust a client-side copy of the whole object. In both cases the server must still validate the values it receives.
Exercise
A Server Function returns db.users.find(id) directly, and the result is a model instance that includes a passwordHash field. Describe two problems with this and write the fix.
Show answer
First, a class instance may fail to serialize. Second, even if it serializes, every field is sent to the browser, including passwordHash. The fix is to return a plain object with selected fields: const user = await db.users.find(id); return { id: String(user.id), name: user.name };.