What Are Server Actions
A Server Action is an async function marked with the "use server" directive — either at the top of the function body or at the top of a whole file — that can be called directly from a Client or Server Component and executes exclusively on the server, letting you handle form submissions and mutations without manually building a Route Handler and a fetch call to reach it. Because Next.js compiles each Server Action into a secure, unguessable endpoint reference under the hood, the client only ever gets a reference to call it, never the function's actual source code.
Cricket analogy: Like a captain radioing instructions to the dressing room that only the team can act on, rather than shouting the tactical plan out loud for the opposition to overhear.
// app/actions.ts
'use server';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const body = formData.get('body') as string;
await db.post.create({ data: { title, body } });
}Invoking Server Actions from Forms and Progressive Enhancement
Passing a Server Action directly to a form's action prop — <form action={createPost}> — makes the form work even before JavaScript has hydrated, because Next.js can process the submission as a real HTML form POST if the client-side bundle hasn't loaded yet, then upgrade to a client-side submission once it has. Inside the action, the first parameter is automatically the submitted FormData object, from which you extract fields with formData.get('title') and can then write to your database directly.
Cricket analogy: Like a backup generator kicking in the instant floodlights fail mid-match so the game continues under some light, rather than the match being abandoned entirely without power.
Progressive enhancement means a <form action={serverAction}> submits correctly as a real HTML POST even if JavaScript fails to load, then upgrades to a smoother client-side submission once React has hydrated.
Managing Pending and Error States with useActionState
The useActionState hook wraps a Server Action so a component can read its returned state — such as a validation error object — and a pending boolean across the submission lifecycle, while the companion useFormStatus hook lets a nested submit button read pending without prop drilling, so you can disable it and show a spinner exactly while the action is in flight. This pairing is what makes it possible to build a fully accessible, progressively-enhanced form that still shows rich loading and error UI once JavaScript is running, without reinventing state management for every single form.
Cricket analogy: Like a third umpire's review light turning amber the instant a decision is under review, then flashing red or green once judgment is reached, so everyone in the stadium can see the exact status.
'use client';
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
import { createPost } from './actions';
function SubmitButton() {
const { pending } = useFormStatus();
return <button disabled={pending}>{pending ? 'Posting…' : 'Post'}</button>;
}
export function NewPostForm() {
const [state, formAction] = useActionState(createPost, { error: null });
return (
<form action={formAction}>
<input name="title" required />
<textarea name="body" required />
{state.error && <p role="alert">{state.error}</p>}
<SubmitButton />
</form>
);
}Security Considerations and Revalidating After Mutations
Because a Server Action's endpoint is technically a public, callable URL under the hood, Next.js does not treat "use server" alone as an authorization check — you must still explicitly verify the current user's session and permissions inside the action itself before performing any mutation, exactly as you would inside a Route Handler. After a successful write, calling revalidatePath or revalidateTag inside the same action is the standard way to ensure the page reflects the change immediately, since a Server Action's return value alone does not automatically refresh any cached data on the page.
Cricket analogy: Like a stadium's VIP gate still requiring a guard to check your credentials individually, even though the gate itself already looks official and unlocked to anyone walking past.
Never assume a Server Action is protected just because it isn't linked from a visible UI element. Its compiled endpoint can still be called directly, so always re-verify the session and authorization inside the action itself.
- A Server Action is an async function marked with 'use server' that runs exclusively on the server.
- Passing a Server Action to a form's action prop enables progressive enhancement, working even before JavaScript hydrates.
- Inside a form-bound action, the first argument is the submitted FormData object.
- useActionState exposes a Server Action's returned state and pending status to a component.
- useFormStatus lets a nested submit button read pending state without prop drilling.
- Server Actions must independently verify session and authorization — 'use server' is not an auth check.
- Call revalidatePath or revalidateTag inside the action after a successful mutation to refresh cached UI.
Practice what you learned
1. What directive marks a function as a Server Action?
2. Why does binding a Server Action to a form's action prop enable progressive enhancement?
3. What is automatically passed as the first argument to a Server Action bound to a form?
4. What does useFormStatus provide to a nested submit button?
5. Why must a Server Action explicitly check authorization even if it's not linked from any visible UI?
Was this page helpful?
You May Also Like
Revalidation Strategies
Understand time-based revalidation (ISR) and on-demand revalidation with revalidatePath and revalidateTag, and how to wire them into Server Actions and Route Handlers.
Caching in Next.js
A tour of the four caching mechanisms in the Next.js App Router — Request Memoization, the Data Cache, the Full Route Cache, and the Router Cache — and how they interact.
Route Handlers (API Routes)
Learn how to build server-side API endpoints in the Next.js App Router using route.ts files, the Web Request/Response APIs, dynamic segments, and their caching behavior.
Fetching Data in Server Components
Learn how to fetch data directly inside React Server Components using async/await, and how Next.js handles deduplication, parallelization, and streaming for those requests.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics