To secure Next.js server actions, treat each one as a public API endpoint: read the user from the server-side session inside the action, confirm that user may change the specific record, validate every argument, and return only what the UI needs. A check on the page, the layout or in proxy.ts doesn't protect the action, because anyone can call it with a direct POST request.
Server actions are the default way to handle mutations in the Next.js App Router, so AI coding tools such as Cursor, v0, Bolt and Claude Code generate a lot of them. They work from the button they were written for. The gap is a call that skips the button.
Why Next.js server actions are public endpoints
A function marked "use server" looks like an ordinary import. At build time, Next.js replaces it in the client bundle with an action ID and a dispatcher that sends a POST request back to the server, with the ID in a Next-Action header.
The Next.js data security guide states the consequence: an exported server action is reachable via a direct POST request, not only through your UI, so verify authentication and authorization inside each one. Encrypted action IDs and removal of unused actions reduce exposure, but they don't decide who may call an action your app uses.
For every action, ask: what happens if a signed-out visitor, or a user from another account, sends this request with arguments of their choosing?
Why AI-generated server actions are often unprotected
These gaps come from how the code is requested and fixed:
- The prompt says "only admins can see the settings page," so the tool adds a role check to the page or layout. Actions in that file look protected, but the guide is explicit that a page-level check doesn't extend to the actions defined within it.
- The component already holds the user's ID or the full record, so the generated action accepts
userId,ownerIdor a whole object as an argument and trusts it. - An action throws an authorization error during development, and the quickest fix is to delete the check.
- Authentication lives in
proxy.ts(middleware.tsbefore Next.js 16), and everything behind its matcher is assumed safe.
How to secure Next.js server actions: one pattern for every action
Every action that reads private data or changes anything should authenticate, validate, authorize against the record, act, then return a minimal result. Put the session and ownership checks in a server-only data access layer (DAL), the approach Next.js recommends for new projects, so a new action can't skip them by accident.
// app/projects/actions.ts (example)
"use server";
import { z } from "zod";
import { requireUser } from "@/lib/dal"; // reads the session cookie, throws if signed out
import { db } from "@/lib/db";
const Rename = z.object({ projectId: z.string().uuid(), name: z.string().trim().min(1).max(100) });
export async function renameProject(input: unknown) {
const user = await requireUser();
const { projectId, name } = Rename.parse(input);
const project = await db.project.findFirst({
where: { id: projectId, members: { some: { userId: user.id, role: { in: ["owner", "editor"] } } } },
select: { id: true },
});
if (!project) throw new Error("Not found");
await db.project.update({ where: { id: project.id }, data: { name } });
return { ok: true };
}The user comes from the session, never from an argument. The ownership condition is part of the query, so a project the caller can't edit is simply not found. The action returns a flag, not the updated row.
Take an ID from the client, not a record
The Next.js server actions guide points out what schema validation misses: a schema checks the shape of the input, and a well-formed object can still refer to a row the caller doesn't own. Send a reference, usually an ID, plus the user's change, and re-read everything else from the database using the session.
- Accept the record ID and the fields the user may edit, nothing more.
- Never accept
userId,role,plan,organizationId,priceorisAdminfrom the client. Derive them on the server. - Use an allowlist schema, so extra keys in a modified request are dropped.
If your actions query through the Supabase service role key, or a Postgres role that owns the tables, row-level security doesn't apply. The action's own check is then the only barrier. Our guide to Supabase row-level security mistakes explains how to keep policies working as a second layer.
Don't rely on proxy or layouts for authorization
Proxy suits optimistic checks, such as redirecting signed-out visitors early. It's a poor place for the only check.
The proxy documentation notes that server actions are handled as POST requests to the route where they're used, so a matcher that excludes a path also skips its actions, and moving an action in a refactor can silently remove coverage. The framework layer has also failed before: CVE-2025-29927, rated critical, let requests bypass authorization checks in Next.js middleware on unpatched versions. Apps that repeated the check inside each action still enforced it.
Layouts have their own problem. The authentication guide warns that layouts don't re-render on client-side navigation, and a layout that hides its children doesn't stop them from rendering. Check close to the data, in the DAL.
Control what server actions return and capture
Whatever an action returns is serialized and sent to the browser. Returning the result of db.user.update(...) sends the whole row, including fields such as password hashes or internal flags. Return a status or a small object built field by field.
Inline actions inside a Server Component can capture variables from the render. Next.js encrypts captured values before sending them to the client, and its docs advise against relying on that encryption alone. Keep secrets and full records out of closures and look them up inside the action.
Don't weaken the built-in protections. Next.js rejects action requests whose Origin header doesn't match Host, its cross-site request forgery (CSRF) defense, so add to serverActions.allowedOrigins only domains you control. Request bodies are capped at 1MB by default; raise bodySizeLimit only as far as uploads need. Actions that send email or call a large language model (LLM) also need the per-user limits in our guide to adding rate limiting to an AI-built app.
Common server action mistakes in AI-generated code
| Mistake | What can go wrong | Fix |
|---|---|---|
| Auth check on the page or layout only | Signed-out users call the action directly | Call requireUser() inside the action |
| Session check without ownership check | Any user edits any record by changing an ID | Include the user or organization in the query |
userId or role taken from arguments | Users act as someone else or promote themselves | Derive identity and role from the session |
| Raw database row returned | Private fields reach the browser | Return a status or a minimal object |
Auth only in proxy.ts | Matcher gaps or framework bugs skip it | Enforce in the DAL; keep proxy checks optimistic |
Route handlers in app/api/**/route.ts need the same checks.
How to audit the server actions in your app
- Search the codebase for
"use server"and list every action, including inline ones. - For each, write down who may call it and which records they may touch.
- Confirm the action or the DAL it calls enforces both, not the page, layout or proxy.
- Check each argument: is it validated, and could it carry identity, role or pricing?
- Remove anything from the return value that the UI doesn't render.
- With two test accounts and the network tab open, trigger an action as the first account, find the POST request with the
Next-Actionheader, and replay it signed out and as the second account. Both attempts should fail.
Run step 6 on staging after every large AI-assisted change. Item 6 of our security checklist for AI-built apps covers the same cross-account test, and item 4 in our list of security mistakes in AI-built apps shows the general form of the problem. Our security audit for AI-built apps reviews authorization, exposed endpoints and input validation, with a written report and a prioritized fix list.
Frequently asked questions
Are Next.js server actions safe by default?
They have built-in protections: POST-only requests, an origin check, encrypted action IDs and removal of unused actions. None of these check who the caller is or what they may change. That's your code's job, inside every action.
Can someone call a server action without using my UI?
Yes. Any action your app uses is reachable with a POST request to the page that uses it. Anyone who can load that page can see the request in the browser and send their own version.
Should I use server actions or route handlers for mutations?
Both need the same session, ownership and validation checks. Server actions suit forms and mutations inside your own app. Route handlers suit endpoints other systems call, such as webhooks or a mobile client.
Does zod validation make a server action secure?
No. A schema confirms the input's shape and drops unexpected fields. It can't tell whether the ID belongs to the caller, so you still need the ownership check.