Sub topic 12
Treating Server Functions as public endpoints
This chapter assumes you know how to pass a function to <form action>, read FormData, and return results with useActionState. It also assumes you have seen a Server Function in a framework that supports them. Here you will learn what a Server Function exposes and how to protect it.
A Server Function is an endpoint
A function in a file marked "use server" runs on the server. When you import it into a client component or pass it to <form action>, your framework replaces the import with a reference. Submitting the form sends an HTTP request to the server, and the server runs the function.
That request is an ordinary network request. Anyone who can reach your server can send one, with or without your form. They can change field values, add fields, remove fields, or call the function from a script. The form you wrote is only one way to reach it.
Treat every exported function in a "use server" file as a public API route. The same rules apply as for any route handler:
- Check who is calling (authentication).
- Check that the caller may do this action on this resource (authorization).
- Check that the input has the shape and size you expect (validation).
Validate and authorize inside the function
Client-side checks such as required or maxLength improve the user experience. They do not protect you, because a caller can skip them. Repeat every check on the server.
The next example edits a todo. It checks the session, validates the input, and confirms that the todo belongs to the user. The getCurrentUser and db imports stand in for your own session and data code.
// actions.js
"use server";
import { getCurrentUser } from "./auth";
import { db } from "./db";
export async function renameTodo(previousState, formData) {
const user = await getCurrentUser();
if (!user) {
return { error: "Please sign in." };
}
const id = Number(formData.get("id"));
const title = String(formData.get("title") ?? "").trim();
if (!Number.isInteger(id) || id <= 0) {
return { error: "Invalid request." };
}
if (title.length === 0 || title.length > 200) {
return { error: "Title must be 1 to 200 characters." };
}
const todo = await db.todos.find(id);
if (!todo || todo.ownerId !== user.id) {
return { error: "Todo not found." };
}
await db.todos.update(id, { title });
return { error: null };
}Because the function has the (previousState, formData) signature, you can pass it to useActionState as shown in the earlier chapter.
Common mistakes
- Trusting hidden fields. An
<input type="hidden" name="userId">can be edited by the caller. Take the user from the session, never from the form. - Checking permission only in the UI. Hiding a delete button does not stop someone from calling the delete function directly. Check ownership inside the function.
- Skipping type conversion.
formData.getreturns a string, aFile, ornull. Convert and check the value before use, as the example does withNumberandString. - Exporting helpers by accident. In a
"use server"file, every exported async function becomes callable from outside. Keep internal helpers unexported or in a separate file without the directive. - Leaking details in errors. Return short messages that are safe to show. Log stack traces and database errors on the server only.
Returning errors the form can show
Expected failures, such as a bad title, should be returned as values. This is the same pattern you used with useActionState, and it keeps the error text under your control. Unexpected failures can throw. In that case React surfaces the error to the nearest error boundary, so keep thrown messages free of internal details.
Also remember that any value you return to the client is visible to the caller. Return only what the form needs, not whole database records.
Quick checklist
| Question | What to do |
|---|---|
| Who is calling? | Read the session on the server |
| May they do this? | Compare the resource owner or role with the caller |
| Is the input sane? | Convert types, check length and range |
| What do you return? | A small, safe object |
Exercise
A delete button is rendered only for the owner of a post, and its Server Function reads postId from a hidden form field and deletes that post. Why is this unsafe, and what two changes fix it?
Show answer
Anyone can call the function directly with any postId, because hiding the button is not a server-side check. First, get the current user from the session inside the function and reject the request if there is none. Second, load the post by postId, confirm its owner is that user, and only then delete it. Also validate that postId is a positive integer before using it.