Lesson 7 of 9 · 28m
Server Actions and Mutation Discipline
Server actions collapse the endpoint boilerplate for mutations, but production use still demands auth, validation, idempotency, rate limits, and clear revalidation.
Server actions are the point where many teams decide the App Router is either wonderful or terrifying. Wonderful because a form can invoke server code without a hand-written API route. Terrifying because suddenly functions are callable over the network and it is easy to forget that every one of them is a public mutation endpoint.
The correct frame is simple: a server action is an RPC endpoint with nice ergonomics. Treat it with the same discipline you would give POST /api/invoices/:id/refund — because that is what it is.
A small action with the right shape
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { requireUser } from "@/server/auth";
const Input = z.object({
invoiceId: z.string().uuid(),
reason: z.string().min(3).max(500),
});
export async function requestRefund(input: unknown) {
const user = await requireUser();
const data = Input.parse(input);
await refunds.request({ invoiceId: data.invoiceId, reason: data.reason, userId: user.id });
revalidatePath(`/billing/invoices/${data.invoiceId}`);
}Validate unknown, not typed trust. The compile-time type does not travel with a malicious request.
Forms get progressive enhancement
export function RefundForm({ invoiceId }: { invoiceId: string }) {
return (
<form action={requestRefund.bind(null, { invoiceId })}>
<textarea name="reason" required minLength={3} />
<button type="submit">Request refund</button>
</form>
);
}The shape depends on how you structure inputs and binding; the important part is that a real <form> can submit before or without client hydration. Use useActionState or useFormStatus for feedback when JavaScript is present, not as the only way the form can work.
Never trust the hidden field
Hidden inputs and bound arguments are convenient, but authorization cannot depend on them. The user can replay any action call with different IDs. Every action must derive the caller from cookies/session and check object ownership server-side.
Load the invoice server-side and compare its account or owner to the authenticated caller before mutating. Do not return raw database or validation errors to the client. Log detail server-side; return a stable, user-safe failure shape.
Mutations need idempotency and abuse controls
A double-click, mobile retry, or browser back-forward can repeat submission. If the operation is not naturally idempotent, add an idempotency key or database constraint. Rate limit destructive endpoints even when they sit behind a form. "Nobody will script this" has never been a security control.
Field notes
- Actions in files marked
"use server"are exported endpoints. Do not export helper functions from those files unless you intend them callable. - Mutations belong in POST-like actions, not route rendering. Rendering a page should not charge cards, send email, or mutate rows.
redirect()throws internally. Do not catch and swallow it in a broadtry/catch.- Revalidate exactly what changed after the transaction commits; use the previous lesson's invalidation map.
- Optimistic UI is excellent for low-risk edits and terrible for money movement, deletion, or permission changes.
Was this lesson helpful?