Sub topic 12
Passing extra arguments with bind and understanding closures
This chapter assumes you can write React components and hooks, you know async/await, and you have defined a Server Function with "use server". It covers two ways to give a Server Function extra data, and why one of them needs care.
The problem: forms only send FormData
A form action receives a FormData object. Often the function also needs a value that is not a form field, such as the id of the note being edited. You could add a hidden input, but there is a cleaner option.
Pre-filling arguments with bind
Function.prototype.bind returns a new function with some leading arguments already fixed. The first argument to bind is the this value, which Server Functions do not use, so pass null.
// app/actions.js
'use server';
import { db } from './db';
export async function updateNote(noteId, formData) {
const title = String(formData.get('title') ?? '').trim();
await db.notes.update(noteId, { title });
}// 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>
);
}When the form is submitted, React calls updateNote(noteId, formData). The bound noteId comes first, and the FormData is appended after it.
Bound arguments must be serializable, because they travel to the browser and back. Strings, numbers, plain objects and arrays work. Class instances and functions do not.
Closures in inline Server Functions
An inline Server Function defined inside a component can read variables from the surrounding scope. That is a closure.
// app/page.js (a Server Component)
import { db } from './db';
export default function Page({ noteId }) {
async function archive() {
'use server';
await db.notes.update(noteId, { archived: true });
}
return (
<form action={archive}>
<button type="submit">Archive</button>
</form>
);
}Here archive uses noteId without it being a parameter. The bundler turns this into a bound argument. React sends the captured value along with the reference to the function, and the server restores it when the form is submitted.
The two approaches do the same job. Use bind when you want the data flow to be visible in the code. Use a closure when it reads more naturally.
Closed-over values are not trusted
The captured value does not stay on the server. It is sent to the browser as part of the page, and it comes back with the request. React encrypts closed-over variables in some frameworks, which hides them from casual reading. Encryption does not make them trustworthy, and your setup might not encrypt at all.
A safe version of updateNote checks identity and ownership:
// 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 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');
}
const title = String(formData.get('title') ?? '').trim();
await db.notes.update(noteId, { title });
}Common errors
- Forgetting the argument order. Bound arguments come first, so the signature is
(noteId, formData), not(formData, noteId). - Binding with
useActionState. The previous state is also passed in, so the order becomes(noteId, prevState, formData)when you bind first. - Capturing something large or secret. A closure over a whole database row or an API key sends that data to the client. Capture only the small value you need, such as an id.
- Passing a non-serializable value, such as a class instance, which fails at runtime.
Exercise
A Server Component defines async function remove() { 'use server'; await db.notes.delete(noteId); }, where noteId comes from props. Is it safe to skip the ownership check because noteId is set by the server when it renders the page? Explain.
Show answer
No. The captured noteId is sent to the client and returned with the request, so a user can alter or replay it. The function must still validate the id and check authentication and ownership before deleting.
Exercise
Given updateNote(noteId, formData), write the line that produces a form action with the id pre-filled.
Show answer
const updateNoteWithId = updateNote.bind(null, noteId); The first argument, null, is the unused this value.