Sub topic 12
Passing extra arguments with bind and understanding closures
This chapter assumes you can write a Server Function in a "use server" file or inline in a Server Component. It also assumes you know that a form's action prop accepts a function that receives FormData. You should be comfortable with Function.prototype.bind and JavaScript closures. Earlier chapters covered the serialization rules and the security model, and this chapter relies on both.
The problem: a form action only receives FormData
A form action called by <form action={fn}> receives one argument, the FormData of the submitted form. Often the function also needs a value that is not in a form field, such as the id of the note being edited. There are three ways to supply it:
- Put it in a hidden
<input>. - Close over it, using an inline Server Function that reads a variable from the surrounding component.
- Pre-fill it with
bind.
All three put the value in a place the client can see and change. That is the main point of this chapter, and the sections below show why.
Using bind
bind returns a new function with some leading arguments already filled in. For a Server Function, the new function is still a Server Function. React keeps the reference to the original function plus the bound values.
// app/actions.js
'use server';
import { getSession } from './auth';
import { db } from './db';
export async function updateNote(noteId, formData) {
if (typeof noteId !== 'string') {
throw new Error('Invalid note id');
}
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
throw new Error('Title is required');
}
const session = await getSession();
if (!session) {
throw new Error('Not signed in');
}
const note = await db.notes.find(noteId);
if (!note || note.ownerId !== session.userId) {
throw new Error('Not allowed');
}
await db.notes.update(noteId, { title });
}The getSession and db modules are placeholders for your own code. Now bind the id in a Server Component:
// app/EditForm.js (a Server Component)
import { updateNote } from './actions';
export default function EditForm({ noteId }) {
const updateNoteWithId = updateNote.bind(null, noteId);
return (
<form action={updateNoteWithId}>
<input name="title" />
<button type="submit">Save</button>
</form>
);
}The first argument to bind is the value of this. Server Functions do not use this, so pass null. Every argument after that is a bound argument. When the form is submitted, React calls updateNote(noteId, formData). The bound arguments come first, and the arguments the caller supplies come after them.
The function above validates noteId itself. The reason is covered in the security section below.
Argument order with useActionState
useActionState adds the previous state as an argument. The order becomes: bound arguments, then previous state, then FormData.
// app/actions.js
'use server';
import { getSession } from './auth';
import { db } from './db';
export async function renameNote(noteId, prevState, formData) {
if (typeof noteId !== 'string') {
throw new Error('Invalid note id');
}
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
const session = await getSession();
const note = session ? await db.notes.find(noteId) : null;
if (!note || note.ownerId !== session.userId) {
throw new Error('Not allowed');
}
await db.notes.update(noteId, { title });
return { error: null };
}A Client Component can import the Server Function and bind it before passing it to the hook:
// app/RenameForm.js
'use client';
import { useActionState } from 'react';
import { renameNote } from './actions';
export function RenameForm({ noteId }) {
const boundRename = renameNote.bind(null, noteId);
const [state, formAction, isPending] = useActionState(boundRename, { error: null });
return (
<form action={formAction}>
<input name="title" />
<button type="submit" disabled={isPending}>Rename</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Binding in a Client Component works because React treats an imported Server Function as a reference object that supports bind. A plain client-side function does not behave this way once it crosses to the server, so keep the bound function a Server Function reference.
A common mistake is to put the bound arguments in the wrong position. If you write renameNote(prevState, noteId, formData), bind still passes noteId first, and your function then reads the state object as the id. The typeof noteId !== 'string' check turns that bug into a clear error instead of a silent wrong write.
Closures in inline Server Functions
An inline Server Function, one with 'use server' as the first statement in its body, can read variables from the component around it. This is a closure. Here is an example:
// app/NoteRow.js (a Server Component)
import { db } from './db';
export default function NoteRow({ note }) {
async function archive() {
'use server';
await db.notes.update(note.id, { archived: true });
}
return (
<form action={archive}>
<span>{note.title}</span>
<button type="submit">Archive</button>
</form>
);
}The function archive uses note.id, which comes from the props. The bundler cannot leave that value behind on the server, because the function runs later in a separate request. So React treats the captured variable as a bound argument. The behavior is equivalent to the bind form. The closure is syntax that hides the same mechanism.
This has four consequences.
- Captured values are serialized. They must follow the serialization rules from the earlier chapter. A captured class instance, a function, or a database connection cannot be captured. The build or the render fails.
- Captured values go to the client. The value is part of the rendered output, so the browser holds it between the render and the submit. Some frameworks encrypt closed-over values so that casual inspection does not reveal them. Next.js does this, for example. Check what your framework does. Encryption protects the value from being read or edited by a user. It does not make the value a statement of identity or permission.
- Captured values are a snapshot. The value is fixed at render time. If the page stays open while the underlying data changes, the submit uses the old value. This is usually what you want for an id. It is a bug for something like a "current price" or a "version". Read those on the server inside the function.
- Module-level values are not captured. An imported
dbor a constant at the top of the file is resolved on the server when the function runs. Only variables from the enclosing function scope are captured.
Capturing a whole object is the easiest way to leak data by accident. In the example above, note is not captured, only note.id. If the function had used note.secretField, that field would travel with the page. Capture the smallest value you need.
What actually happens
The diagram shows where each value lives from render to execution.
The middle steps are where an attacker acts. The browser can send a different noteId or call the function reference directly with any arguments, without using your form.
Bound values are untrusted input
Binding does not make a value safe. The bound noteId reaches your function in the same request as the form fields, and the client controls that request. A user who owns note A can alter the request so it carries the id of note B.
Treat a bound argument as you would treat a URL parameter:
- Check its type and shape.
- Check authentication with the session on the server, not with a bound
userId. - Check that the signed-in user is allowed to touch the record with that id.
The following function shows the wrong approach.
// app/actions.js (unsafe version, for illustration)
'use server';
import { db } from './db';
export async function deleteNoteUnsafe(userId, noteId) {
// userId was bound at render time, so the client can replace it.
await db.notes.deleteWhere({ id: noteId, ownerId: userId });
}The function trusts userId because "we bound it ourselves". But the caller can supply any userId. Read the identity from the session inside the function instead, as the updateNote example earlier does.
Choosing between the three techniques
| Technique | Where the value lives | Visible in the page | Works with a Client Component | Best for |
|---|---|---|---|---|
| Hidden input | In `FormData` | Yes, as an HTML field | Yes | Values the user could also type, or forms shared with non-React code |
| `bind` | Bound argument on the reference | Not as a visible field | Yes, if the function is a Server Function reference | A record id for one form, with a typed function signature |
| Closure in an inline function | Captured variable | Not as a visible field | No, inline functions exist only in Server Components | Small one-off actions next to the markup that uses them |
All three are equally untrusted. Pick by readability. bind keeps the action in a shared file, which makes it easy to test and reuse. A closure keeps the action next to the component, which is shorter but hides the data flow.
Gotchas
- Bound arguments must be serializable. Binding a
Dateor a plain object is fine. Binding a function, a class instance, or aSymbolthat is not registered fails. - Large bound values bloat the page. Each rendered form carries its own bound values. Rendering a list of 500 rows, each with a bound object, sends 500 copies. Bind an id, and load the rest on the server.
- Binding creates a new function each render. That is fine for a form action. If you pass the bound function to
useActionState, the hook uses the latest function, so a changed id applies to the next submit. - An arity mismatch is silent. JavaScript does not complain if a function receives too few or too many arguments. Validate the shape of every argument you read.
- Refreshing data after a write is separate. Binding only controls the input of the call. Updating the visible page is handled by your framework, which the next chapter covers.
Exercise
A Server Function is declared as async function setRole(userId, role, formData). A teammate writes const action = setRole.bind(null, user.id, 'admin') in a Server Component and says "the role is fixed on the server, so users can't change it". What is wrong with this claim, and what should the function do instead?
Show answer
The bound 'admin' is serialized into the rendered output and returned with the submit request, so the client can send a different value, or call the function directly with any arguments. The function must not accept a role from its arguments. It should read the signed-in user from the session, check that this user is allowed to assign roles, and validate userId as a string that refers to an existing user. The role to assign should come from a server-side rule, or be checked against an allowed list.
Exercise
You bind noteId to renameNote and pass the result to useActionState. In what order does renameNote receive its arguments, and what happens if you define it as renameNote(prevState, noteId, formData)?
Show answer
The order is the bound arguments, then the previous state, then FormData: renameNote(noteId, prevState, formData). With the wrong definition, prevState receives the bound noteId, and noteId receives the previous state object. A type check on noteId throws, and without such a check the function could run with a wrong id. Always validate the type of each argument.