Sub topic 11
Treating every Server Function as a public endpoint
This chapter assumes you can write React components and hooks, use async/await, and read a FormData object. It also assumes you know the basic request and response flow between a browser and a server. You should already know what "use server" marks and how to define and call a Server Function.
The core rule
A Server Function looks like a normal function call. Under the hood, the framework turns it into an HTTP request. When you mark a function with "use server", the bundler creates a reference to it and gives that reference to client code. Calling the reference sends a POST request to the server with the serialized arguments.
Anyone who can reach your server can send that request. They don't need your UI. They can use fetch, curl, or the browser's developer tools. They can change the arguments, call functions in any order, and call them as often as they like.
So the rule is simple: treat every exported function in a "use server" file, and every inline function with a "use server" directive, as a public API endpoint. Apply the same checks you would apply to a REST handler.
What the UI does not protect
Many mistakes come from trusting the interface. These things do not protect a Server Function:
- Hidden buttons. If you only render a "Delete" button for admins, a non-admin can still call
deleteNotedirectly. - Client-side validation. The
requiredattribute and any checks in a Client Component run in the user's browser. They are a convenience, not a control. - Argument types in your editor. TypeScript types disappear at runtime. A caller can send a number, an object, or
nullwhere you expect a string. - Not importing the function. A function that no component uses may still be reachable if it is exported from a
"use server"file. Exporting is what exposes it.
The three checks
Every Server Function that changes data or returns private data needs three checks, in this order.
- Validate input. Confirm the type, shape, and size of every argument.
- Authenticate. Confirm who is calling, using a session or token read on the server.
- Authorize. Confirm that this user may perform this action on this specific record.
This example shows all three:
// app/actions.js
'use server';
import { getSession } from './auth';
import { db } from './db';
export async function deleteNote(noteId) {
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');
}
await db.notes.delete(noteId);
}getSession and db are placeholders for your own modules. The important parts are the order and the source of each fact. The user identity comes from getSession() on the server, never from an argument. The owner comes from the database record, never from the client.
Validate input
Form data arrives as strings or File objects, and formData.get() returns null when a field is missing. Normalize and check each value before you use it.
// app/actions.js
'use server';
import { getSession } from './auth';
import { db } from './db';
const MAX_TITLE_LENGTH = 200;
export async function createNote(prevState, formData) {
const session = await getSession();
if (!session) {
throw new Error('Not signed in');
}
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
if (title.length > MAX_TITLE_LENGTH) {
return { error: 'Title is too long.' };
}
await db.notes.insert({ title, ownerId: session.userId });
return { error: null };
}Notice that ownerId is set from the session. If the form had a hidden ownerId field, a caller could change it to any value. Never read identity fields from the request.
For larger forms, a schema library such as Zod or Valibot keeps the checks in one place. The principle is the same: parse untrusted input into a known shape, and reject anything that does not fit.
Authenticate
Read credentials on the server, from a cookie or header, inside the function. Do not rely on a check that happens only in a layout or a page. A page-level redirect protects the page render. It does not run when someone calls the Server Function directly.
Authorize
Authentication answers "who are you?" Authorization answers "may you do this?" The most common bug is to stop after authentication. A signed-in user can then change any record by guessing or enumerating ids. This is called an insecure direct object reference (IDOR). The ownerId comparison in deleteNote prevents it.
A shorter way to scope the check is to put the user into the query itself, so the database enforces it:
// app/actions.js
'use server';
import { getSession } from './auth';
import { db } from './db';
export async function renameNote(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 title = String(formData.get('title') ?? '').trim();
if (title.length === 0) {
return { error: 'Title is required.' };
}
const updated = await db.notes.updateWhere(
{ id: noteId, ownerId: session.userId },
{ title }
);
if (!updated) {
throw new Error('Not allowed');
}
return { error: null };
}Here updateWhere is a placeholder for a query that matches both the id and the owner. If the note belongs to someone else, nothing matches, and the function fails.
Bound arguments are still client input
You can pre-fill arguments with bind, as in updateNote.bind(null, noteId). This is convenient, but it does not make the value trustworthy. The bound value is serialized and sent with the request, so a caller can alter it. Validate and authorize a bound noteId exactly as you would a normal argument.
Closures in inline functions
An inline Server Function can read variables from the Server Component around it. Those values are captured in the closure, then sent to the client and returned on the next call. React encrypts them so the client cannot read or change them in the normal flow, but you should not depend on this for security. Do not capture secrets such as API keys. Read them from the environment inside the function. Treat captured values that affect permissions with the same suspicion as any other input, and look them up again on the server when it matters.
Return values leak data too
What a Server Function returns goes back to the client. Do not return a full database row if the UI needs only a title. Rows can contain password hashes, internal flags, or other users' data. Return only the fields the caller is allowed to see.
Error messages are also output. A message such as "No user with email [email protected]" lets an attacker test which emails exist. In production, many frameworks replace the message of an unexpected thrown error with a generic one. Do not rely on that. Choose messages deliberately and log details on the server.
Other risks to plan for
| Risk | What goes wrong | Mitigation |
|---|---|---|
| Missing authorization | Any signed-in user edits any record | Check ownership or role per record |
| Trusting hidden fields | Caller changes `ownerId` or `price` | Read identity and prices on the server |
| No rate limit | Callers flood expensive functions | Apply rate limits per user or IP |
| Cross-site requests (CSRF) | Another site submits a form to yours | Rely on your framework's origin checks and cookie settings such as `SameSite` |
| Oversized input | Huge strings or files exhaust memory | Limit lengths and file sizes |
| Unused exported actions | Forgotten functions stay callable | Remove them, and export only what you need |
Frameworks add some protections. Next.js, for example, uses POST only, compares the Origin header to the host, and removes unused Server Functions from the client bundle. Treat these as extra layers, not a replacement for the three checks. Their exact behavior differs by framework and version, so read your framework's security notes.
A reusable guard
If many functions need authentication, put it in one helper so no function can forget it.
// app/guard.js
import { getSession } from './auth';
export async function requireUser() {
const session = await getSession();
if (!session) {
throw new Error('Not signed in');
}
return session;
}// app/actions.js
'use server';
import { requireUser } from './guard';
import { db } from './db';
export async function archiveNote(noteId) {
if (typeof noteId !== 'string') {
throw new Error('Invalid note id');
}
const user = await requireUser();
const note = await db.notes.find(noteId);
if (!note || note.ownerId !== user.userId) {
throw new Error('Not allowed');
}
await db.notes.update(noteId, { archived: true });
}The helper file has no "use server" directive. That matters: a file with the directive exports every function as a public endpoint, and requireUser should not be one. Keep helpers in plain modules and import them into the Server Function file.
A review checklist
Before you ship a Server Function, ask:
- Does it check the type and size of every argument, including bound ones?
- Does it read the user from the server session and not from the request?
- Does it check that this user may act on this record?
- Does it return only the fields the caller may see?
- If someone called it with no UI at all, would the result be safe?
The last question is the best test. If the answer is "no", the function needs more checks.
Exercise
A page shows a "Publish" button only when the signed-in user is an admin. The button calls publishPost(postId), a Server Function that sets published = true on the post. The function contains no checks. A regular user knows a post id. Can they publish it, and what three checks should the function perform?
Show answer
Yes. Hiding the button only changes the UI. The regular user can send the same POST request with curl or fetch and the function will run. The function should (1) validate that postId is a string of the expected form, (2) authenticate the caller by reading the session on the server and rejecting a missing session, and (3) authorize by confirming the session user is an admin, or owns the post, before updating the record.
Exercise
An edit form uses updateNote.bind(null, noteId) as its action. A developer says the noteId is safe because the server component set it. Why is that wrong, and what should updateNote do?
Show answer
The bound value is serialized and sent from the client with the request, so a caller can replace it with another id. updateNote should treat noteId as untrusted input: check that it is a string, read the session on the server, load the note, and confirm that the note's owner is the session user before updating.