A Next.js server action is a public HTTP endpoint. Start there. Next.js's own docs say exported actions can be reached with a direct POST request, whether or not your UI ever renders the form, and that you must verify authentication and authorisation inside every one. The built-in protections help: hidden IDs, an Origin check and a body size cap. None of them replace your own checks. Below is a five-check template. Authenticate, authorise, validate with Zod, rate limit, then return safe errors. There is a vulnerable version and a fixed version, with the reasoning behind each line.
A server action is a public endpoint with a friendly wrapper
The 'use server' directive feels private. You write await deletePost(id) in a component and it just works, which makes the call look like an ordinary function call from inside your application. Under the hood, though, it is a network request. The Mutating Data docs say it plainly: actions use POST, only that method can invoke them, and they are reachable via direct POST requests, not just through your application's UI.
Next.js does add some armour. Know exactly what it is, so you do not over-trust it. According to the Data Security guide (last updated August 25, 2026):
- Action IDs are encrypted and non-deterministic, recalculated between builds.
- IDs are created at compile time and cached for a maximum of 14 days, then regenerated on a new build or cache invalidation.
- Unused actions are removed from the client bundle through dead code elimination.
The Next.js 15 release notes introduced the unguessable IDs and the dead code removal, and they are candid about why: even an action you never import elsewhere is still a publicly accessible HTTP endpoint. Obscurity lowers the odds of someone finding your action. It does not make the action safe once they do. Anyone with a logged-in session can open the network tab, copy a request and replay it with different values.
There is a CSRF layer too. Next.js compares the host in the Origin header with x-forwarded-host , or host if that is absent, and rejects a mismatch unless the origin appears in allowedOrigins . Per the serverActions config reference, that check runs in production too. But requests without an Origin header bypass the comparison. A script using curl simply does not send one. The check protects browsers from other sites, while doing nothing about a determined caller talking straight to your endpoint.
The vulnerable version I’ll keep coming back to is deliberately plain: illustrative code, not from any real project. A deletePost action lives in a file marked 'use server'. It takes a postId from the client, calls db.post.delete({ where: { id: postId } }), calls revalidatePath('/posts') and returns the deleted record. The page that renders the delete button sits behind a login check. It looks fine. It has at least five holes.
Check one: authenticate inside the action
The first hole is the one people argue about most. "But the page is already protected."
It is not fine for the action. The docs state that a page-level authentication check does not extend to Server Actions defined within it, because the action is a separate entry point. The Forms guide repeats it as a warning: verify authentication and authorisation inside each Server Action, even if the form is only rendered on an authenticated page.
The docs' own createPost example in the Server Actions guide shows the shape. Get the session. If there is no session?.user , throw Unauthorized before touching the database. It then sets authorId from session.user.id rather than accepting an author from the client. That second part matters as much as the first. Identity comes from the session, never from form fields.
Keep it thin with a Data Access Layer
If you paste a session check at the top of forty actions, you will eventually forget one. The docs recommend a Data Access Layer for new projects: a server-only module that holds auth, authorisation and database logic, while the 'use server' functions stay thin. Add the server-only package to that module and the build errors if anything imports it from client code. Then your action becomes a few lines that call getCurrentUser() and hand off.
A cached getCurrentUser helper, the docs use React's cache, means every layer reads the same verified user without you threading it through arguments. One place to audit. That is the whole point.
Check two: authorise against the resource
Authentication answers "who are you?". Authorisation answers "may you do this to that thing?". Miss the second, and you get an Insecure Direct Object Reference (IDOR), where a logged-in user changes an ID in the request and edits someone else's data.

The docs' example is deliberately boring: load the post, compare post.authorId to session.user.id , and throw Forbidden if they differ. That is all. No framework magic, just a comparison you have to remember to write.
In the vulnerable deletePost, any signed-in user can delete any post by guessing or enumerating IDs. Sequential integer IDs make that trivial. UUIDs slow the guessing but do not fix it, because IDs leak through URLs, API responses and shared links.
Two habits help:
- Put the ownership check in the same query where you can. Deleting with a
whereclause that includes both the post ID and the user's ID means a mismatch simply affects zero rows. - Decide on role rules in one function, not inline. "Admins can delete anything" is a policy. Policies belong in the Data Access Layer.
If your data lives in Postgres behind Supabase, the database can enforce this as a second wall. I have written about that in the Supabase RLS guide. Row-level security does not replace the check in your action, but it means a forgotten check is not an instant breach. And if you want the wider comparison of how frameworks handle all this, that is covered in the framework security comparison. Here I am staying on the action itself.
Check three: validate input with Zod
The docs are blunt: always validate input from the client, because it is easily modified. That covers form data, URL parameters, headers and searchParams . A FormData object is just a bag of whatever the caller sent. formData.get('amount') returns FormDataEntryValue | null, and TypeScript will happily let you cast it to a number and move on.
That is the trap. As Makerkit points out, TypeScript types do not exist at runtime. Your postId: string annotation is a comment as far as an attacker is concerned. The old v13 docs already recommended a library like zod for server-side validation, with HTML attributes such as required and type="email" for basic client-side checks. Treat the HTML attributes as UX. Treat Zod as the gate.
The pattern is short. Declare a schema, call safeParse on the raw input, and bail out with a generic error if it fails. Type the action's argument as unknown , as Makerkit does, so you cannot accidentally trust it. Define the schema for deletePost as an object with a postId that is a string and a valid UUID. Reject anything else before a query runs.
A few things I'd add:
- Use
.strict()or pick explicit fields so unexpected keys don't ride along into a database update. Mass assignment bugs start with spreading the whole input into a write. - Bound your strings with
.max(). An unbounded text field is a storage and cost problem. - Use the parsed output (
result.data), never the original input, for the rest of the function.
The body size cap is a coarse backstop here. By default, the maximum request body for a Server Action is 1MB, to limit resource consumption and DDoS risk, configurable through experimental.serverActions.bodySizeLimit. The docs note the limit applies to the raw request body including multipart overhead, and suggest allowing an extra 10 to 20 KB on top of your target. Raising it for file uploads is fine. Just do it knowingly.
Check four: rate limit the expensive ones
Not every action needs a limiter. A toggle that flips a boolean can probably live without one. But anything that sends an email, writes rows, hits a paid API or checks a password is a target. The Data Security guide says to consider rate limiting for expensive operations such as sending emails or writing to a database, and points to the Rate limiting example in the Backend for Frontend guide.
The official pointer is thin, so use the concrete pattern from Makerkit. They use Upstash Ratelimit with Ratelimit.slidingWindow(5, '1 m'), which allows five requests a minute. The action reads x-forwarded-for from headers(), falls back to 'anonymous', calls ratelimit.limit(ip) and returns a generic Too many requests error when success is false. Redis is the store, which matters because an in-memory counter does not survive multiple server instances.
Pick the right key
Makerkit suggests three keys, and I agree with the split:
- IP address for unauthenticated actions (login, password reset, sign-up).
- User ID for authenticated actions. IPs are shared by offices and mobile carriers, so a user ID is fairer.
- Action plus resource for specific operations, such as editing one post. That stops a single record being hammered.
One caveat on IP keys: x-forwarded-for is only as trustworthy as the proxy chain that sets it. Know what your deployment puts in that header before you rely on it.
If you would rather not build this yourself, Arcjet has an example repo showing a form with a server action protected by bot detection, rate limiting per IP, and its Shield WAF. A decent reference for what a managed layer looks like. Either route works. What does not work is leaving no limiter on the password reset action.
Check five: return errors that leak nothing
A server action's return value is serialised and sent to the browser. So is anything you throw, in one form or another. The docs tell you to return only what the UI needs, not raw database records, and their good example returns { success: true }.
Our vulnerable deletePost returned the deleted row. That row might carry the author's email, an internal flag, a draft body. It is all in the response, visible in the network tab even if no component renders it.
The same rule applies to failures:
- Don't echo database errors, stack traces or SQL fragments. Log them server-side.
- Don't distinguish "no such post" from "not yours" if that tells an outsider which IDs exist. A single generic message does the job.
- Keep the rate-limit message as vague as Makerkit's. "Please try again later" is plenty.
Two more leak routes deserve a glance. Makerkit lists closure data exposure as a fifth vulnerability: an inline action defined inside a component can capture variables from the surrounding scope, and you want to be sure nothing sensitive gets captured. Defining actions in a separate 'use server' file sidesteps the question. And the docs mention React's experimental taint APIs ( experimental_taintObjectReference and experimental_taintUniqueValue , enabled via experimental.taint) as an extra layer, though they say to keep filtering data in the Data Access Layer regardless.
The fixed version, all five checks together
This table describes the illustrative deletePost before and after. I have listed the checks in the order of this article. In practice I would run the rate limit straight after authentication, since it is cheap and stops abuse before any database work.
| Check | Vulnerable version | Fixed version |
|---|---|---|
| 1. Authenticate | Assumes the page already did it | Calls getCurrentUser() from the Data Access Layer, throws Unauthorized if there's no session |
| 2. Authorise | Deletes whatever ID arrives | Loads the post, compares post.authorId to session.user.id , throws Forbidden on mismatch |
| 3. Validate | Trusts the postId: string type | Parses unknown input with a Zod schema (UUID string) via safeParse , uses result.data |
| 4. Rate limit | None | Sliding window keyed on user ID, generic error when exceeded |
| 5. Safe errors | Returns the deleted record, surfaces raw errors | Returns { success: true } or one generic message, logs details server-side |
The action body ends up around a dozen lines because the Data Access Layer does the heavy lifting. If a reviewer cannot see all five checks at a glance in the action or in the single function it calls, that is a flag.
Server actions or route handlers?
Both are public HTTP endpoints. Both need every check above. So the choice isn't about security, it's about fit.
Server actions are built for mutations triggered by your own UI. You get progressive enhancement for forms, a single round trip that returns the action's result and the re-rendered UI, and Next.js 16 APIs like updateTag() (read-your-writes) and refresh() that only work inside Server Actions, per the Next.js 16 post. There is a trade-off: the client dispatches them one at a time. The docs note this is a property of the client dispatcher and the server does not queue them, but still, do not expect Promise.all from the browser to parallelise them.
Route handlers are the better pick when:
- A third party, a mobile app or a webhook needs to call you. You want a stable, documented URL and contract.
- The request is a read, or otherwise not a mutation.
- You need control over headers, status codes and response format.
The docs themselves steer non-mutation and parallel work toward route handlers and Server Components. My rule is simple. If only your own Next.js front end calls it and it changes data, an action is fine. If anything else calls it, write a handler and give it proper API treatment. And in both cases, the five checks go inside, not around.
If you would rather have someone audit an existing codebase for missing checks, or set up a Data Access Layer before the action count gets out of hand, you can hire a Next.js developer to do that review.
FAQ
Does the Origin check mean I don't need CSRF protection of my own?
For browser-initiated cross-site requests, the built-in comparison covers the common case, and it runs in production as well as development. But requests without an Origin header bypass it, and it says nothing about who the caller is or what they may do. Treat it as one layer, with authentication and authorisation still inside the action.
Do I need `allowedOrigins`?
Only if your app is reached through a host that differs from what the server sees. Behind a reverse proxy that forwards the public host in x-forwarded-host , no entry is needed. If the proxy forwards its own host instead, add the host shown in the browser's address bar. Both allowedOrigins and bodySizeLimit remain experimental under experimental.serverActions.
Are unused actions still dangerous?
They are removed from the client bundle by dead code elimination, which makes them harder to find. The Next.js 15 notes still describe an unimported action as a publicly accessible endpoint, and an action you do use is obviously reachable. Secure it either way.
Should I put all my checks in the action file?
No. Put authentication, authorisation and database access in a server-only Data Access Layer and keep the 'use server' function as a thin caller. The docs recommend that structure for new projects, and it means one audited place instead of dozens of copies.
The sharpest point to remember: Next.js hides your action IDs, but it cannot know who should be allowed to run them. Authenticate, authorise, validate, limit and return the minimum, inside every action, every time.