Sub topic 12
Server functions and progressive enhancement
This chapter assumes you can write a basic useActionState form: an action that takes (prevState, formData), a state object, and a form with action={formAction}. It also assumes you know what a React component is on the server versus the client. Server functions need a framework or bundler that supports React Server Components, such as Next.js. Plain Vite or Create React App setups can't use them.
What a server function is
A server function is an async function that runs on the server but can be imported and called from client code. You mark it with the "use server" directive. At the top of a file, the directive makes every export a server function.
The client bundle doesn't contain the function body. The bundler replaces the import with a reference. When the client calls it, React serializes the arguments, sends a POST request to the server, runs the function there, and sends the return value back.
This fits useActionState well, because an action already receives its inputs as plain data (the previous state and a FormData) and returns plain data (the next state).
| Row | Client action | Server function action |
|---|---|---|
| Where the body runs | Browser | Server |
| Can read secrets and the database | No | Yes |
| Arguments and return value | Anything | Must be serializable |
| Works before JavaScript loads | No | Yes, with a permalink |
Writing the action
The action below validates a title and returns the next state. It has the same shape as any other useActionState action.
// actions.js
"use server";
export async function createPost(prevState, formData) {
const title = String(formData.get("title") ?? "").trim();
if (!title) {
return { error: "Title is required.", title };
}
// save the post here
return { error: null, title: "" };
}Then the client component imports it and passes the action to the hook, along with a third argument, the permalink.
// PostForm.jsx
"use client";
import { useActionState } from "react";
import { createPost } from "./actions";
export function PostForm() {
const [state, formAction, isPending] = useActionState(
createPost,
{ error: null, title: "" },
"/posts/new"
);
return (
<form action={formAction}>
<input name="title" type="text" defaultValue={state.title} />
<button type="submit" disabled={isPending}>Create</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}The two files are separate. "use server" goes in actions.js and "use client" goes in PostForm.jsx. A file can't carry both directives.
What the permalink does
The third argument to useActionState is the permalink. It is the URL of the page that renders this form. It only has an effect when the action is a server function and the form is submitted before the client JavaScript has loaded.
Without JavaScript, <form action={formAction}> renders as a normal HTML form. The browser submits it with a regular POST, which causes a full page navigation. The permalink tells React and the framework where that navigation should go, so the server can:
- Receive the form data.
- Run the server function with the initial state as
prevState. - Render the page at the permalink again, with the returned state as the form's state.
- Send that HTML back.
The user sees the validation error or the success result even though no JavaScript ran. This is progressive enhancement: the form works with HTML alone, then gets faster behavior once JavaScript arrives.
Why `defaultValue={state.title}` matters here
In the no-JavaScript path, the whole page is re-rendered by the server. If the title was empty, the action returns { error: "Title is required.", title }. The server renders the form with that state, so the error appears and the input holds whatever the user typed.
If you left out defaultValue, the field would come back blank after a failed submission. The same technique also covers the JavaScript path, where React resets uncontrolled forms after an action finishes. Returning the submitted values and putting them in defaultValue keeps the input in both cases.
What survives without JavaScript
Only what the server can render survives. Check each feature of the form against this list:
- The returned state, error messages and success text all work, because they are rendered by the server.
isPendingdoes not work. There is no client to track a pending transition, and the browser's own loading indicator takes over.useFormStatusdoes not work for the same reason.- Controlled inputs and
onChangehandlers don't run. - Client-only validation doesn't run, so the server function must validate everything.
Design the form so the no-JavaScript path is complete but plain. Treat pending UI and instant feedback as enhancements on top.
Serialization limits
Arguments to a server function and its return value travel over the network. React can serialize primitives, arrays, plain objects, FormData, Date, Map, Set, and promises, among others. It can't serialize functions, class instances with methods, DOM nodes, or symbols that aren't registered globally.
For useActionState, this means the state returned by a server function must be plain data. Don't return an Error object to show in the UI. Return a message string, as the example does.
// Good: plain data
return { error: "Title is required.", title };
// Bad: not safe to return from a server function
// return { error: new Error("Title is required."), validate: () => {} };Treat server functions as public endpoints
A server function is reachable by anyone who can send a POST request to your server, not only by your form. Hiding the button or form in the UI does not protect it. Inside every server function you should:
- Validate all input again, even if the client validated it.
- Check that the user is signed in and allowed to perform the action.
- Treat
prevStateas untrusted. It comes from the client, so don't use it for security decisions such as "the user is already an admin".
The code below adds an authorization check to the post action. Here getSession stands for whatever your framework or auth library provides.
// actions.js
"use server";
import { getSession } from "./auth";
export async function createPost(prevState, formData) {
const session = await getSession();
if (!session) {
return { error: "You must be signed in.", title: "" };
}
const title = String(formData.get("title") ?? "").trim();
if (!title) {
return { error: "Title is required.", title };
}
if (title.length > 120) {
return { error: "Title must be 120 characters or fewer.", title };
}
// save the post here
return { error: null, title: "" };
}Common mistakes
Setting a permalink on a client-only action. If the action is a normal function defined in the component file, there is nothing the server can run. The permalink is ignored and the form needs JavaScript to work.
Pointing the permalink at the wrong page. The permalink must be a page that renders the same form component with the same action. If it points somewhere else, the user lands on a page that doesn't show the result.
Forgetting name attributes. FormData only contains fields that have a name. A missing name gives you null from formData.get, which is the same bug with or without JavaScript.
Returning non-serializable state. This usually shows up as a runtime error in the framework, not at build time.
Importing server code into a client file by accident. Only files marked "use server" produce references. A regular helper that touches the database, imported into a "use client" file, ends up in the browser bundle. Keep database access inside "use server" files or server-only modules.
Assuming the permalink works in every setup. It relies on the framework to handle the no-JavaScript POST. Check your framework's documentation to confirm it supports this before you depend on it.
Checklist
- Put the action in a
"use server"file and keep it async. - Keep state and arguments serializable.
- Return submitted values and use
defaultValueso inputs keep their text. - Pass the page's URL as the permalink.
- Validate and authorize inside the function.
- Test the form with JavaScript disabled in your browser's developer tools.
Exercise
A form uses useActionState with a server function and a correct permalink. A user on a slow connection submits it before JavaScript loads, and the server function returns { error: "Title is required.", title: "" }. Which of these will the user see: the error message, the disabled button with "Creating...", or both? Explain.
Show answer
Only the error message. The page is re-rendered by the server with the returned state, so the error text is in the HTML. The disabled button depends on isPending, which is tracked by React on the client. Without JavaScript there is no client transition to track, so the button stays in its normal state until the page reloads.
Exercise
A teammate adds a permalink as the third argument to useActionState, but the action is an async function defined in the same "use client" file as the component. They say the form now works without JavaScript. Are they right? What should they change?
Show answer
No. The permalink only has an effect when the action is a server function, because the server must be able to run it when the browser posts the form without JavaScript. They should move the action into a file with "use server" at the top, export it, and import it into the client component.