A React Server Action is an async function marked with the 'use server' directive that runs exclusively on the server but can be called directly from a client component, most often through a form's action prop, without a hand-written fetch() call or API route. The API route was never really the point, it existed to give client code something to fetch(). Server Actions remove the middle step for mutations: the function you'd have put in that route now runs directly when a form submits, with the request/response plumbing handled by the framework instead of hand-written by you, so there are no extra APIs to keep in sync.
When the compiler rejects one of your actions, seven form action errors decoded shows what each message means and which fix compiles.
Progressive enhancement, in this context, means a form still functions as a real HTML submission even if the page's JavaScript bundle hasn't loaded or fails entirely, because the browser's native form behavior carries the request through.
Form submission before Server Actions
A settings update used to mean three separate pieces of code that all had to agree on the same shape:
// 1. Client component with a fetch call
function SettingsForm() {
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
const formData = new FormData(e.currentTarget as HTMLFormElement);
await fetch('/api/settings', {
method: 'POST',
body: formData,
});
}
return <form onSubmit={handleSubmit}>{/* fields */}</form>;
}
// 2. API route handling the same shape
export async function POST(req: Request) {
const formData = await req.formData();
await db.settings.update({ name: formData.get('name') });
return new Response(null, { status: 204 });
}
Two files, one implicit contract between them, and no compiler check that they stay in sync if a field gets renamed. The React documentation on Server Functions describes the replacement, a function the client calls through a reference React creates for you. Until that existed, this split was the default shape of a React mutation, because the framework had no built-in way to run server code from a client trigger, so every team reinvented the same boilerplate: a fetch call, a matching route handler, and a manually maintained URL string connecting the two. That duplication is exactly what Server Actions collapse into one function.
Before Server Actions, every mutation needed two files that had to agree on the same implicit contract, a fetch call and a matching API route, with no compiler check that a renamed field stayed in sync between them.
The same form with a Server Action
// actions.ts
'use server';
export async function updateSettings(formData: FormData) {
const name = formData.get('name') as string;
await db.settings.update({ name });
}
// SettingsForm.tsx
import { updateSettings } from './actions';
function SettingsForm() {
return (
<form action={updateSettings}>
<input name="name" />
<button type="submit">Save</button>
</form>
);
}
It's one function, imported directly into the component that uses it, with no fetch(), route file or separate URL to keep in sync. The 'use server' directive tells the bundler this function's code stays on the server, the client only gets a reference it can call.
To put a real number on "less code" instead of just asserting it, I counted both versions above myself, the two fetch() snippets saved as one file and the two Server Action snippets as another, with comment-only and blank lines stripped: grep -v -e '^[[:space:]]*//' -e '^[[:space:]]*$' file.tsx | wc -lc. It's my own count of the code on this page, so you can rerun it:
| Version | Lines (non-blank) | Bytes |
|---|---|---|
| fetch() + API route | 16 | 520 |
| Server Action | 14 | 365 |
That's 30% fewer bytes. The bigger win is that the URL string '/api/settings' and the formData.get('name') field name only need to agree in one place now instead of two. A line count doesn't capture that, but it's the part that breaks silently when someone renames a field months later.
Pending state and errors with useActionState
Real forms need a loading state and error handling, not just a fire-and-forget submit. useActionState wraps a Server Action and gives you both, as long as the action takes the previous state as its first argument:
// actions.ts
'use server';
export type SettingsState = { error?: string };
export async function saveSettings(
_prevState: SettingsState,
formData: FormData,
): Promise<SettingsState> {
const name = formData.get('name');
if (typeof name !== 'string' || !name.trim()) {
return { error: 'Name cannot be empty' };
}
await db.settings.update({ name });
return {};
}
'use client';
import { useActionState } from 'react';
import { saveSettings } from './actions';
function SettingsForm() {
const [state, formAction, isPending] = useActionState(saveSettings, {});
return (
<form action={formAction}>
<input name="name" disabled={isPending} />
{state.error && <p role="alert">{state.error}</p>}
<button type="submit" disabled={isPending}>
{isPending ? 'Saving...' : 'Save'}
</button>
</form>
);
}
isPending tracks the in-flight request automatically, no manual useState toggle before and after the call. The validation logic lives inside the server action, right next to the mutation it guards, which is where I'd want it during a code review anyway, and it runs on the server, so a caller who skips the browser can't skip it. Passing the Server Action itself to useActionState, rather than a client-side wrapper around it, also keeps the form submittable before hydration, and React can show the returned error state even then. Wrap it in an inline client function and you lose both. The state object here is a loose { error?: string }; the useActionState typing patterns article shows a status union and a schema-backed action factory that type this same form more tightly.
Progressive enhancement, the underrated win
Because a Server Action attached to a form's action prop is a real HTML form submission under the hood, the form still works if JavaScript hasn't loaded yet, a slow connection, an ad blocker interfering, or a bug in an unrelated script. A fetch()-based onSubmit handler has no such fallback, if the JS bundle didn't execute, the button does nothing.
Picture a user on a spotty connection who taps Save before the JS bundle finished loading. With a Server Action on a form, the browser's native form submission carries the request through. With a fetch() handler, nothing happens, and nothing tells the user why. That gap is the reason I'd reach for the form-first version on anything a visitor might submit from a train.
When Should You Keep an API Route Instead?
| Scenario | Use |
|---|---|
| Form submit from your own React UI | Server Action |
| Button click that triggers a mutation | Server Action |
| Webhook receiver (Stripe, GitHub) | API route |
| Endpoint called by a mobile app | API route |
| Public API consumed by third parties | API route |
| Cron job hitting an endpoint | API route |
If your React app's UI is the only caller, use a Server Action. If anything outside your UI needs to call it, that's what a stable, versioned API route is for.
The dividing line is ownership: if your React app's UI is the only caller, a Server Action removes a layer of indirection for free.
What Server Actions don't protect you from
The ergonomics hide something worth saying plainly: a Server Action is a public HTTP endpoint. The framework generates an ID for it and wires up the request, but anyone can call it with any payload. The React docs call Server Functions exposed server endpoints and say their arguments are fully client-controlled, so treat them as untrusted input. Importing a function instead of writing a fetch() doesn't put a wall in front of it.
That means the checks you used to write in the API route still belong in the action body, all of them. Read the session inside the action and verify the caller is allowed to mutate this particular record, not just that they're logged in. Validate the FormData with a schema rather than trusting field names, because nothing stops a caller from omitting a field or sending an array where you expected a string. And rate-limit the ones that cost money or send mail; the endpoint is as reachable as any route you'd have protected by hand.
The checklist I'd run on every Server Action before it ships:
- Confirm the action reads the session and checks ownership of the specific record, not just that a session exists.
- Confirm the incoming
FormDatais validated against a schema, not read field-by-field with implicit trust. - Confirm nothing sensitive, a database handle, an API key, gets closed over from the enclosing scope; read secrets from the environment inside the action body instead.
- Confirm rate limiting exists for any action that costs money or sends mail, since the action is as publicly reachable as a hand-written route.
The other trap is what you close over. Values captured in an action defined inside a Server Component get serialized into the client payload so they can be sent back on invocation. Close over an API key and it travels to the browser and back. Next.js encrypts closed-over values, but its own data security guide says not to rely on encryption alone. Read secrets inside the action body from the environment, never from the enclosing scope.
None of this is a criticism of the API: it's the same work the API route always needed, moved somewhere less obvious, which is why it gets skipped.
Go check the table above one more time. If your own settings form still looks like the "before" row, that's the one worth migrating first, it's low-risk (a single owner, no external caller) and it's exactly the shape Server Actions were built for.