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 understand HTML forms and FormData. It also assumes you know what the "use server" directive marks. The chapter covers what a Server Function exposes, what it does not protect you from, and the checks every one should perform.
Why a Server Function is a public endpoint
A Server Function looks like a normal function call. Under the hood, React and your framework turn it into an HTTP request. The server exposes an endpoint for each function marked with "use server", and the client calls it with serialized arguments.
Anyone who can reach your server can send a request to that endpoint. They don't need your UI. A person with a browser's developer tools or a tool such as curl can replay or modify the request. They can pass any arguments they like.
This has three consequences:
- Hiding a button does not protect a function. If a user can't see "Delete", they can still call
deleteNote. - Arguments are untrusted input. Types, shapes, and values can all be wrong or hostile.
- Being exported from a
"use server"file is enough to expose a function. Importing it only in admin components does not limit who can call it.
The three checks
Every Server Function that changes data or returns private data should do these checks, in this order.
- Validate input. Check the type, shape, and range of each argument. Don't rely on what your form or TypeScript types say.
- Authenticate. Confirm who is making the request, using a session or token read on the server.
- Authorize. Confirm that this user may act on this specific resource. Being signed in is not enough.
Here is a function that does 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 stand in for your own modules. The important point is that the function reads the user's identity from the server-side session. It never accepts a userId argument, because the client could set that to anything.
Skipping the ownership check is the most common mistake. Without it, a signed-in user can delete another user's note by sending that note's ID.
Calling it from the client
The client side stays simple. The function checks everything, so the button only needs to call it.
// app/DeleteButton.js
'use client';
import { useTransition } from 'react';
import { deleteNote } from './actions';
export function DeleteButton({ noteId }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
await deleteNote(noteId);
});
}}
>
{isPending ? 'Deleting…' : 'Delete'}
</button>
);
}The disabled state is a convenience for the user, not a safeguard. A direct request ignores it.
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| Checking permissions only in the component | Requests can skip the component | Check inside the Server Function |
| Accepting `userId` or `role` as an argument | The client controls it | Read it from the server session |
| Trusting `formData` values | Fields can be missing or have unexpected types | Validate and convert each field |
| Exporting helper functions from a `"use server"` file | Every exported async function becomes callable | Keep helpers in a separate module |
| Returning whole database rows | Private fields reach the client | Return only the fields the UI needs |
Handling failures
When a check fails, you have two choices. Return an error as state when the user can fix the problem, such as an empty title. Throw when the request should never happen from your UI, such as a missing session. A thrown error goes to the nearest error boundary. Keep error messages short and don't include internal details such as database errors or file paths.
Exercise
A Server Function updateProfile(userId, data) is called from a settings form. The form passes the current user's ID. What is wrong with this design, and how would you fix it?
Show answer
The client controls userId, so someone can send another user's ID and edit that profile. Remove the userId parameter. Read the user from the server-side session inside the function (for example with getSession()), reject the request if there is no session, and validate data before writing it.
Exercise
You export a helper formatTitle(title) as an async function from app/actions.js, which begins with 'use server'. Why is this a problem, and what should you do?
Show answer
Every exported async function in a "use server" file becomes a callable endpoint, so formatTitle is now exposed to any client. Move it to a regular module that has no "use server" directive and import it where needed.