Server Actions and Mutations
A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.
What you will be able to do
#- Define Server Actions inline and in files and wire them to forms with progressive enhancement.
- Collect pending and error state with useActionState and useFormStatus.
- Revalidate correctly after mutations using updateTag, revalidateTag with a profile, or revalidatePath.
Overview
#Defining and calling
A Server Action is an async function marked with 'use server', either at the top of a file (all exports become actions) or inline inside a component. The framework exposes it as an endpoint the client can call; the client never sees the body.
// app/actions.ts
'use server';
export async function createPost(formData: FormData) {
const title = formData.get('title');
await db.post.create({ data: { title: String(title) } });
updateTag('posts'); // Next.js 16: read-your-own-writes
redirect(`/posts`);
}
Forms call actions directly: <form action={createPost}>. This works before hydration, so the form submits even while JavaScript loads; that is progressive enhancement for free.
State around actions
useActionState(action, initialState) in a client component returns the latest return value, a form action to attach, and a pending flag. Per-button pending state comes from useFormStatus in a child component of the form. Expected errors are values you return; unexpected errors throw and flow to error boundaries.
'use client';
const [state, formAction, pending] = useActionState(createPost, { message: '' });
return <form action={formAction}>{/* fields */}<button disabled={pending}>Create</button></form>;
The security rule
An action is a public HTTP endpoint with a friendly name. Authenticate and authorize inside every action, validate input server-side, and never trust that the client UI gated the call. Treat action arguments like API inputs, because that is what they are.
Revalidation after mutation
Pick by contract: updateTag('posts') (Next.js 16, Server Actions only) when the user must see their own write immediately; revalidateTag('posts', 'max') for stale-while-revalidate where a short stale window is acceptable; revalidatePath('/posts') to discard cached output for a specific route. Setting cookies is allowed inside actions via (await cookies()).set(...), which triggers a re-render of the current page.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
A Server Action updates a product price and calls nothing else. The product page's price is read through a use cache function tagged 'products'. What does the user see right after the action completes, and what fixes it?
Exercise 2Explain
Explain why authorization must live inside every Server Action even when the UI hides the button for unauthenticated users.
Reveal the reference answer
reference.textAn action is an HTTP endpoint: its compiled reference is present in the client bundle and can be invoked by anyone with a crafted request, regardless of what the UI renders. Hiding a button is presentation, not access control. The action must verify the session and the permission for the specific resource on every invocation, validate inputs, and fail closed. The same reasoning applies to Route Handlers. This is the server-side gatekeeping rule that client frameworks make easy to forget.Authored expected output: Actions are public endpoints; UI hiding is not authorization.
This is the single most important security property of Server Actions.
Exercise 3Implement
Implement a signup form end to end: a Server Action createUser that validates the email, returns { message } on validation failure, creates the user, and redirects on success; plus a client form using useActionState and a submit button using useFormStatus.
starter.tsx// app/actions/auth.ts // TODO: createUser action // app/signup/form.tsx // TODO: client form with useActionState and useFormStatusReveal the reference answer
reference.tsx// app/actions/auth.ts 'use server'; import { redirect } from 'next/navigation'; export async function createUser(_prev: State, formData: FormData): Promise<State> { const email = String(formData.get('email') ?? ''); if (!/^[^@\s]+@[^@\s]+$/.test(email)) { return { message: 'Enter a valid email' }; } await db.user.create({ data: { email } }); redirect('/welcome'); } // app/signup/form.tsx 'use client'; import { useActionState } from 'react'; import { useFormStatus } from 'react-dom'; import { createUser } from '@/app/actions/auth'; function Submit() { const { pending } = useFormStatus(); return <button disabled={pending}>{pending ? 'Creating...' : 'Sign up'}</button>; } export function SignupForm() { const [state, formAction] = useActionState(createUser, { message: '' }); return ( <form action={formAction}> <label htmlFor="email">Email</label> <input id="email" name="email" type="email" required /> <p aria-live="polite">{state.message}</p> <Submit /> </form> ); }Authored expected output: Validation errors render inline; success redirects to /welcome; the button disables while pending.
useActionState pairs with the (prevState, formData) action signature; useFormStatus must be used inside the form.
Exercise 4Debug
This action works but every logged-out user can delete any comment. Identify the missing piece and fix it. 'use server' export async function deleteComment(formData: FormData) { const id = String(formData.get('id')); await db.comment.delete({ where: { id } }); revalidatePath('/comments'); }
starter.ts'use server' export async function deleteComment(formData: FormData) { const id = String(formData.get('id')); await db.comment.delete({ where: { id } }); revalidatePath('/comments'); }Reveal the reference answer
reference.tsThere is no authorization check. Read the session inside the action, load the comment, and verify the caller owns it or has moderation rights before deleting; otherwise return an error or throw. Example: const session = await auth(); if (!session) return { error: 'Unauthorized' }; const comment = await db.comment.findUnique({ where: { id } }); if (!comment || comment.authorId !== session.user.id) return { error: 'Forbidden' }; then delete and revalidate.Authored expected output: Only authorized callers can delete; others receive an error.
The action runs with server privileges; without a check it is an open delete endpoint.
Exercise 5Test
Write a pure function nextInvalidation(kind: 'own-write' | 'background' | 'path-only', api: 'server-action' | 'route-handler') that returns the correct Next.js 16 call: own-write in a server action gives updateTag; background from either gives revalidateTag with profile 'max'; path-only gives revalidatePath. Assert all combinations, and assert that own-write from a route handler is rejected (returns 'error: updateTag is Server-Actions-only').
starter.tsexport function nextInvalidation( kind: 'own-write' | 'background' | 'path-only', api: 'server-action' | 'route-handler', ): string { // TODO }Reveal the reference answer
reference.tsexport function nextInvalidation( kind: 'own-write' | 'background' | 'path-only', api: 'server-action' | 'route-handler', ): string { if (kind === 'own-write') { return api === 'server-action' ? "updateTag('tag')" : 'error: updateTag is Server-Actions-only'; } if (kind === 'background') { return api === 'server-action' ? "revalidateTag('tag', 'max')" : "revalidateTag('tag', 'max')"; } return "revalidatePath('/path')"; } // The matrix encodes the decision table from the lesson.Authored expected output: All assertions pass, including the route-handler rejection.
Making the decision table executable is the fastest way to internalize it.
Exercise 6Interview
An interviewer asks: when would you choose a Route Handler over a Server Action for a mutation, and vice versa? Give two criteria for each side.
Reveal the reference answer
reference.textChoose a Server Action when the caller is your own first-party React UI and you want typed, collocated mutations with progressive-enhancement forms and no manual fetch wiring; and when revalidation of app caches should happen in the same unit of work. Choose a Route Handler when the caller is not your React tree (webhooks, third-party integrations, mobile clients, cron), when you need precise HTTP semantics such as status codes, headers, content types or caching on GET, or when the endpoint must be publicly addressable and versioned. The overlap rule: anything reachable from outside your app is an API surface and needs Route Handler-grade rigor regardless of which mechanism you used.Authored expected output: First-party UI versus external callers, plus HTTP semantics as the tiebreaker.
The answer shows mechanism choice follows caller and contract, not fashion.
Common misconceptions
#- Server Actions replace API design. They are endpoints; the same auth, validation and rate-limit thinking applies as for any public route.
- useActionState lives in the action file. It is a client hook from react; the action itself lives server-side.
- Calling revalidateTag is optional after a mutation. Without invalidation, cached reads keep serving pre-mutation data until their TTL.
- Forms need onSubmit handlers to use actions. Passing the action to the form's action prop works without JavaScript on first load.
Follow-up practice
#- nextjs-request-apis
- nextjs-cache-components
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.