Sub topic 10
Using Server Functions as form actions
This chapter assumes you know how to pass a function to a form's action prop, you can use useActionState and useFormStatus, and you understand async/await and FormData. It adds one idea: the function that runs on submit can live on the server.
What a Server Function is
A Server Function is an async function that runs on the server but can be called from client code. You mark it with the "use server" directive. The bundler replaces the function in the client bundle with a reference. When the client calls it, React sends a request to the server. The server runs the real function and returns the result.
Server Functions are a feature of a framework or bundler setup, such as Next.js or another React Server Components integration. Plain React with a client-only build can't run them, because something has to host the endpoint and generate the references.
The same feature used to be called Server Actions. React now uses "Server Function" for the function itself. "Action" still means a function that runs inside a transition, and a Server Function passed to a form's action prop is one.
The directive is not about Server Components
"use server" is often confused with the opposite of "use client". It isn't. Server Components need no directive, because they are the default in frameworks that support them. "use server" marks functions that a client may call.
It can be used in two places:
- At the top of a file, which marks every exported function in that file as a Server Function.
- Inside the body of an async function in a Server Component file, which marks only that function.
Client Components can't define Server Functions inline. They must import them from a file that starts with "use server".
The basic pattern
The simplest case is a Server Function that reads FormData and does its work, passed straight to action.
// actions.js
"use server";
export async function createTodo(formData) {
const title = String(formData.get("title") ?? "").trim();
if (title.length === 0 || title.length > 200) {
throw new Error("Invalid title");
}
// Check that the user is allowed to do this, then write to your data store here.
}
// TodoForm.jsx (a component in a framework that supports Server Functions)
import { createTodo } from "./actions";
export function TodoForm() {
return (
<form action={createTodo}>
<input name="title" />
<button type="submit">Add</button>
</form>
);
}Compared with a client-side Action, there is no fetch call and no API route to write. React serializes the FormData, sends it, and runs createTodo on the server. The form's pending state works as usual, so a child component can still read it with useFormStatus.
Returning results with useActionState
Throwing an error on bad input is a blunt tool. A thrown error propagates to the nearest error boundary, so the user loses the form. For expected problems such as validation, return a value and let useActionState hand it to the component.
A Server Function used with useActionState receives the previous state as its first argument and the FormData as its second.
// actions.js
"use server";
import { getSession } from "./session"; // your app's auth helper
import { db } from "./db"; // your app's data layer
export async function addTodo(previousState, formData) {
const session = await getSession();
if (!session) {
return { error: "Please sign in.", title: "" };
}
const title = String(formData.get("title") ?? "").trim();
if (title.length === 0) {
return { error: "Title is required.", title };
}
if (title.length > 200) {
return { error: "Title must be 200 characters or fewer.", title };
}
await db.todos.insert({ userId: session.userId, title });
return { error: null, title: "" };
}// AddTodoForm.jsx
"use client";
import { useActionState } from "react";
import { addTodo } from "./actions";
export function AddTodoForm() {
const [state, formAction, isPending] = useActionState(addTodo, {
error: null,
title: "",
});
return (
<form action={formAction}>
<input name="title" defaultValue={state.title} />
<button type="submit" disabled={isPending}>
Add
</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Three details matter here:
- The component is a Client Component because it uses a hook. It still imports and uses a Server Function, which is allowed.
- The returned object crosses the network, so it must be serializable. Plain objects, strings, numbers, arrays, and similar values work. Class instances and functions don't.
- The function returns the submitted
titleon failure, sodefaultValuerestores it. This matters because React resets uncontrolled fields after a form action completes.
Passing extra arguments with bind
A form action only receives FormData. If you need more data, such as the ID of the item to delete, you have two options. One is a hidden input. The other is bind, which creates a new function with leading arguments filled in.
// actions.js
"use server";
export async function deleteTodo(todoId, formData) {
// formData is still the last argument.
// Validate todoId, check the user may delete this todo, then delete it.
}
// TodoRow.jsx
import { deleteTodo } from "./actions";
export function TodoRow({ todo }) {
const deleteThisTodo = deleteTodo.bind(null, todo.id);
return (
<form action={deleteThisTodo}>
<span>{todo.title}</span>
<button type="submit">Delete</button>
</form>
);
}Both bind arguments and hidden inputs end up in the request, and a user can edit either one. Treat todoId as untrusted input in the function. Don't assume it is the ID you rendered.
Optimistic updates with Server Functions
useOptimistic works the same way. Call the optimistic setter inside the form action, then await the Server Function. A Client Component wraps the call:
"use client";
import { useOptimistic } from "react";
import { addTodoToList } from "./actions";
export function TodoList({ todos }) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(current, title) => [
...current,
{ id: `pending-${current.length}`, title, sending: true },
]
);
async function formAction(formData) {
const title = String(formData.get("title") ?? "");
addOptimisticTodo(title);
await addTodoToList(title);
}
return (
<div>
<ul>
{optimisticTodos.map((todo) => (
<li key={todo.id}>
{todo.title}
{todo.sending && <small> (Saving...)</small>}
</li>
))}
</ul>
<form action={formAction}>
<input name="title" />
<button type="submit">Add</button>
</form>
</div>
);
}Here addTodoToList is an imported Server Function that takes a plain string, while formAction is a local client function that reads the form. When the Action finishes and the framework refreshes the todos prop, the optimistic value is replaced by the real data. If the Server Function throws, the optimistic value also disappears, so make sure the user sees an error.
What the framework has to provide
React defines the model. The framework supplies the machinery. Before relying on Server Functions, check what your framework does for each of these:
| Responsibility | What to check |
|---|---|
| Bundling | It must recognize `"use server"` and replace the function with a client reference. |
| Transport | It must expose an endpoint, usually a POST route, and serialize arguments and return values. |
| Refreshing data | After a mutation, the framework decides how updated server data reaches the client, for example through cache revalidation. |
| Redirects | Many frameworks provide a way to redirect from a Server Function. React itself does not. |
| Progressive enhancement | The framework must handle the form post when JavaScript has not loaded. |
If a feature seems to "just work" in one framework and not another, the difference is usually in this table, not in React.
Progressive enhancement
When a Server Function is passed to action in a Server Component, a framework can render a normal HTML form that posts to the server. The form then works before JavaScript loads. The browser submits the form, the server runs the function, and the page reloads with the result.
The same applies to useActionState when you use it with a Server Function and the framework supports it. The first form with a Server Function from the earlier example (TodoForm) is the easiest case, because it needs no client JavaScript at all.
Two limits apply. First, a form that depends on client-only logic, such as the optimistic update above, can't work without JavaScript. Second, the framework determines how well this works. Test with JavaScript disabled instead of assuming.
Treat Server Functions as public endpoints
Every exported Server Function in a "use server" file is reachable over HTTP. A user does not have to use your form. They can send a crafted request to the function's endpoint with any arguments they like. Hiding the button in the UI does not protect the function.
For each Server Function, do all of the following on the server:
- Authenticate. Read the session inside the function. Don't rely on a prop or a hidden field to say who the user is.
- Authorize. Check that this user may perform this action on this resource. For a delete, load the todo and compare its owner to the session user.
- Validate. Check types, lengths, and allowed values.
FormDatavalues are strings or files, and never the types you hoped for. - Limit what you return. Return only data the caller is allowed to see. Return values are sent to the client.
Common errors
- Using
"use server"to mark a Server Component. The directive marks functions that a client can call. It has no effect on whether a component runs on the server. - Defining a Server Function inline in a Client Component. This fails. Move the function to a
"use server"file and import it. - Forgetting the extra argument when using
useActionState. The function receives(previousState, formData). If you write(formData), you will read the previous state as the form data. - Returning non-serializable values. Return plain data. Convert dates and complex objects first.
- Throwing for expected failures. Return an error value for validation problems and save thrown errors for unexpected failures.
- Trusting
bindarguments or hidden fields. Treat them as input from the user.
Summary
A Server Function passed to a form's action prop is an Action whose body runs on the server. The client-side model is the one you already know: transition, pending state, useActionState, and useOptimistic. What changes is where the code runs, who can call it, and how much responsibility the function has for its own validation and authorization.
Exercise
A teammate writes export async function deletePost(postId) { await db.posts.delete(postId); } in a file marked "use server". The delete button is only shown to the post's author. List two problems with this function and how to fix them.
Show answer
First, it never authenticates or authorizes. Anyone who can reach the endpoint can call it with any postId, because hiding the button in the UI does not restrict the endpoint. Fix: read the session inside the function, load the post, and check that the session user owns it before deleting. Second, it doesn't validate postId. If it is bound with bind or sent as a hidden field, a user can change it. Fix: check its type and format, and handle the case where the post doesn't exist. As a form action it also receives FormData as its last argument, so it should be called through bind(null, post.id), and the signature should be deletePost(postId, formData).
Exercise
You use useActionState(addTodo, initialState) with a Server Function. What arguments does addTodo receive, and why should it return the submitted title when validation fails?
Show answer
It receives the previous state first and the FormData second. After a form action completes, React resets uncontrolled fields. Returning the submitted title lets the component restore it with defaultValue={state.title}, so the user doesn't have to retype it.