Sub topic 12
Treating Server Functions as Public Endpoints
Earlier chapters showed how a Server Function can be passed to a form's action prop. This chapter covers what that convenience costs you. A function marked "use server" looks like a local function call, but it is a network endpoint. This chapter shows how to validate its input, authenticate and authorize its callers, and report errors without leaking information.
This chapter assumes you have read the chapters on form actions and useActionState. It also assumes you are using a framework that supports Server Functions, since React alone does not provide the server runtime. You should know basic HTTP: methods, cookies, and status codes.
What `"use server"` creates
When you mark a function with "use server", the framework's build step does two things:
- The function body stays on the server.
- The client receives a reference to it, which is an identifier the framework can resolve back to the function.
When a form submits, or your code calls the function, the framework sends an HTTP request to the server. The server finds the function from the reference, decodes the arguments, and runs it. To you this feels like a function call. For security purposes it is a request handler.
That means anyone who can reach your server can try to send that request. They do not have to use your form. They can use fetch, curl, or a script. They can send values your form never produces: an empty title, a 10 MB string, a negative number, or the ID of someone else's record. The exact wire format belongs to the framework and may change between versions. Your security should not depend on that format being hard to figure out.
The checks run on the server for every request, whatever sent it. Client-side checks such as required, maxLength, or a disabled button improve the user experience, but they do not enforce anything.
Start from a vulnerable example
This version looks reasonable and is unsafe:
// actions.js
"use server";
import { db } from "./db";
export async function deleteTodo(formData) {
const id = formData.get("id");
await db.todos.delete(id);
}It has three problems:
- No authentication. It never checks who is calling it.
- No authorization. It never checks that the todo belongs to the caller. If the form includes
<input type="hidden" name="id" value={todo.id} />, a caller can change that value to any ID. - No validation.
idis whatever string arrived. Depending on your data layer, an unexpected type could cause an error, or worse.
Hidden inputs are still user input. A hidden field only hides a value from the page layout. It does not stop anyone from changing it.
Validate every argument
Treat every value from FormData as untrusted. formData.get() returns a string, a File, or null. Your code must handle all three, even if your form only produces strings.
Follow this order:
- Convert to the type you expect.
- Check its shape: length, range, and allowed values.
- Reject anything that fails.
// actions.js
"use server";
import { getSessionUser } from "./auth";
import { db } from "./db";
const MAX_TITLE_LENGTH = 200;
export async function createTodo(previousState, formData) {
const user = await getSessionUser();
if (!user) {
return { error: "Please sign in to add a todo.", title: "" };
}
const title = String(formData.get("title") ?? "").trim();
if (title.length === 0 || title.length > MAX_TITLE_LENGTH) {
return {
error: `Title must be between 1 and ${MAX_TITLE_LENGTH} characters.`,
title,
};
}
await db.todos.insert({ ownerId: user.id, title });
return { error: null, title: "" };
}The example imports getSessionUser and db from your own application. The first reads the session cookie and returns the signed-in user or null. The second is your data layer.
Three details matter here:
String(formData.get("title") ?? "")turnsnulland missing fields into an empty string. AFilewould become the string"[object File]", so checktypeof value === "string"first if you need to reject files explicitly.- The length limit also protects your database and memory from huge inputs. Check any list or file for size and count as well.
ownerIdcomes from the session, not from the form. Never accept a user ID from the client and trust it.
For forms with many fields, a schema validation library keeps the rules in one place. The principle is the same either way: the server decides what is valid.
Authenticate, then authorize
These are separate questions:
- Authentication asks who the caller is. Read it from something the server controls, usually a signed session cookie.
- Authorization asks whether this caller may perform this action on this resource.
Passing authentication does not imply authorization. A signed-in user can still send another user's todo ID.
// actions.js (continued)
export async function deleteTodo(formData) {
const user = await getSessionUser();
if (!user) {
throw new Error("Not found");
}
const id = Number(formData.get("id"));
if (!Number.isInteger(id) || id <= 0) {
throw new Error("Not found");
}
const todo = await db.todos.findById(id);
if (!todo || todo.ownerId !== user.id) {
throw new Error("Not found");
}
await db.todos.delete(id);
}The function does its checks in the same order each time: session, input shape, then ownership. It returns the same "Not found" message when a todo is missing and when it belongs to someone else. If the messages differed, an attacker could use them to find out which IDs exist.
Put the authorization check inside the Server Function, or in a helper that the function always calls. Do not rely on the page that renders the form to decide who sees the button. Hiding the delete button from non-owners is good design, but it does not stop a direct request.
Choose between returning and throwing
How you report a failure affects both users and security:
| Situation | Approach | Why |
|---|---|---|
| Expected user mistake, such as an empty title | Return an error state | `useActionState` shows it next to the field and the form stays usable |
| Not signed in, in a form the user can fix | Return an error state | The UI can offer a sign-in link |
| Request that your form could never produce, such as an invalid ID | Throw | It signals a bug or a probing client, and the nearest error boundary handles it |
| Unexpected server failure, such as the database being down | Let it throw | An error boundary shows a generic fallback |
Whichever you choose, send the client a message that helps the user without revealing internals. Do not return raw database errors, SQL, file paths, or stack traces. Log the details on the server and show a general message to the client. Many frameworks hide production error messages from thrown errors for this reason, but you should not rely on that. Returned error state is something you wrote, so it reaches the client as written.
Here is the client side of createTodo:
// TodoForm.jsx
import { useActionState } from "react";
import { createTodo } from "./actions";
export function TodoForm() {
const [state, formAction, isPending] = useActionState(createTodo, {
error: null,
title: "",
});
return (
<form action={formAction}>
<input name="title" defaultValue={state.title} maxLength={200} required />
<button type="submit" disabled={isPending}>
Add
</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}maxLength and required give quick feedback, and the server repeats the same rules. The server copy is the one that counts.
Beyond input checks
Validation and authorization cover most of the risk. A few other habits matter too.
Know what you export
In a file marked "use server", every exported async function can become a callable endpoint. Do not export a helper just so another module can import it. A function like deleteAllTodosForUser(userId) exported from that file is reachable from outside, with an argument chosen by the caller. Keep internal helpers in a separate file without the directive. Export only functions that are safe for an untrusted caller to run.
Be careful with captured values
A function defined inline inside a Server Component can close over variables. Frameworks may serialize those captured values and send them to the client, and some protect them with encryption or signing. Check your framework's documentation before capturing anything sensitive. A safer rule is to pass nothing secret into closures and read secrets inside the function from server-only configuration.
Cross-site requests
A malicious site can try to make a signed-in user's browser submit a request to your server. Frameworks usually reduce this risk by accepting only POST requests for Server Functions and checking the Origin header against the host. Cookies with SameSite=Lax or Strict help as well. Learn what your framework does, and do not turn those protections off.
Rate limits and cost
An endpoint that anyone can call can be called many times. Limit how often a user or IP address may run expensive or abusive actions, such as sending email, creating accounts, or uploading files. A button that is disabled while isPending is true only slows down honest users.
Return only what the caller may see
Whatever a Server Function returns goes to the client. If you return a whole database row to simplify your code, you may expose fields such as email addresses or internal flags. Build the response from the fields you intend to share.
Summary of controls
| Threat | Control in the Server Function |
|---|---|
| Malformed or oversized input | Convert, check shape and size, reject |
| Anonymous caller | Read the session on the server, and refuse if there is none |
| Caller acts on someone else's data | Load the resource and compare its owner to the session user |
| Forged identity fields | Take the user ID from the session, never from the form |
| Information leaks | Use generic error messages and the same response for "missing" and "forbidden" |
| Accidental endpoints | Export only functions that are safe to call |
| Cross-site requests | Keep the framework's origin checks on, and use appropriate cookie settings |
| Abuse and cost | Add rate limits for expensive actions |
Common mistakes
- Validating only in the browser, and assuming the form is the only caller.
- Trusting a hidden input such as
userIdorprice. - Checking that the user is signed in but not that they own the resource.
- Using different error messages for "does not exist" and "not yours".
- Exporting internal helpers from a
"use server"file. - Returning full database records instead of selected fields.
Exercise
A teammate writes export async function renameProject(formData) in a "use server" file. It reads projectId from a hidden input and name from a text input, then runs db.projects.update(projectId, { name }). The page only shows the form to the project's owner. List the problems with this function and say what you would add.
Show answer
The function trusts the client in several ways. It does not check the session, so an anonymous caller can run it. It does not check ownership, so any caller can send any projectId, and hiding the form only controls what the page shows. It does not validate projectId (type and range) or name (string type, trimmed, non-empty, a maximum length). Fix it by loading the session user and refusing if there is none. Convert and check projectId, load the project, and refuse with a generic "Not found" if it is missing or its ownerId differs from the session user's ID. Then validate name and return an error state for user-fixable mistakes. Only then call db.projects.update.
Exercise
Why should a Server Function return the same message when a record does not exist and when it belongs to another user?
Show answer
Different messages let an attacker test IDs and learn which records exist, even without being able to read or change them. A single generic response, such as "Not found", gives them no signal.