Skip to content
LockShip

Guide · Next.js · Updated

Next.js Server Actions security for vibe-coded apps: auth, ownership, zod and rate limits, tested

Rather check your own app first and read later? Paste its address, prove it’s yours, and the free scan shows you the worst thing a stranger can reach. Run the free scan

When an AI builder adds a Save or Delete button to a Next.js app, it usually writes a Server Action: a function marked "use server" that the button calls. It reads like part of the page. It isn’t. Every action is an address on your server that takes a POST from anyone, with any arguments they like, whether or not your button is on their screen. We built a small app with careless and fixed versions of the actions builders write most, attacked each one from a terminal, and wrote down what happened. This page is what we learned, with every fix run against a real server first.

New to this? Start with our vibe coding security checklist. Server Actions are check 5 there. API routes, which have the same problem with a different shape, have their own guide.

What we tested, and how

Everything here we ran ourselves on 26 October 2026, on our own machine, with two made-up users, Alice and Bob. The app is a small notes app on Next.js 16.4.3, built with next build and run with next start, so it behaves like production, not the dev server. It has a signed-in dashboard guarded by proxy.ts, careless and fixed versions of the usual actions (delete, rename, update a profile, send an invite, publish), zod 4.6.7 for validation, and a few Supabase actions using the real @supabase/supabase-js 2.118.0 and @supabase/ssr 0.12.7 libraries. Those talked to a small stand-in we wrote for Supabase Auth and the table API, backed by real Postgres Row Level Security rules running in PGlite. It is not Supabase, and we say below where that matters. A second app ran on Next.js 15.2.2 and 15.2.3 to see what CVE-2025-29927 does to an action. Finally we ran LockShip’s own scanner code against the lab, so what we say about our scan comes from running it.

The ten steps

  1. A Server Action is a public POST endpoint
  2. List every action, in your code and on your live site
  3. Check who is calling, inside the action
  4. Check the record is theirs, and don’t trust bound ids
  5. Validate every argument, and send back less
  6. Closures, encrypted values and the action ID myth
  7. Supabase: getUser() and RLS inside the action
  8. Rate limit the actions that cost you
  9. The fix, in one action
  10. Test it without breaking your live app

01

A Server Action is a public POST endpoint

Next.js says this plainly. Its Server Actions guide says “A Server Action runs as a POST request against the page that invokes it,” and that “the route is reachable to anyone who can send the same POST. Treat every action as an untrusted entry point.” React’s own “use server” reference puts it shorter: “Arguments to Server Functions are fully client-controlled.”

Here is what that looks like. When Bob clicks Delete on his own note, his browser sends a POST to the page with the action’s ID in a Next-Action header and the arguments as JSON. We copied that request into a terminal and changed one number:

Our lab, on localhost
# What the browser sends when Bob clicks Delete on his own note 2:
POST /dashboard
Next-Action: 40ac19f2dd0550be19b6c3d0375bc2cb6aab6a6aaa
Content-Type: text/plain;charset=UTF-8

[2]

# The same request from a terminal, with 1 (Alice's note) instead of 2,
# and a cookie we made up so proxy.ts lets it through:
$ curl -X POST -H 'Cookie: session=x' -H 'Next-Action: 40ac19f2...' \
    -H 'Content-Type: text/plain;charset=UTF-8' --data '[1]' http://127.0.0.1:4500/dashboard
1:{"ok":true}  [200]          <- Alice's note is gone

That is the whole attack: one request, no browser, no button. The Delete button only showed on your own notes, and the action trusted that. It’s an easy mistake for an AI builder to make, because the code that draws the button and the code that runs on the server sit next to each other and look like one thing. Broken access control is “Maintaining its position at #1” in OWASP’s 2025 Top 10, and MITRE’s name for this exact bug is Missing Authorization (CWE-862).

One more reason to keep Next.js itself up to date: in December 2025 React disclosed CVE-2025-55182, “an unauthenticated remote code execution vulnerability in React Server Components,” rated CVSS 10.0. The React team wrote that an attacker “could craft a malicious HTTP request to any Server Function endpoint.” No check you write fixes that; only the patched versions in the Next.js advisory do. Our scan reads your live Next.js version and flags it if it’s in that range.

02

List every action, in your code and on your live site

You can’t fix actions you don’t know about, and agents add them without saying so. If you have the code, this lists every file and function marked "use server":

Terminal, in your project folder
# Run in your project folder: every file with a "use server" line, and the line itself
grep -rnE --include=*.ts --include=*.tsx --include=*.js --include=*.jsx \
  --exclude-dir=node_modules --exclude-dir=.next "[\"']use server[\"']" .
What it printed on our lab
./app/dashboard/page.tsx:16:          "use server";     <- an inline action inside a page
./app/dashboard/page.tsx:22:          "use server";
./app/actions.ts:1:"use server";                         <- a whole file of actions
./app/unused-actions.ts:1:"use server";
./app/public-actions.ts:1:"use server";
./app/sb/actions.ts:1:"use server";

A file that starts with "use server" makes every function it exports an action (Next.js’s use server reference shows both forms). A "use server" line inside a function, usually in a page, makes just that function one. Open each match. You’ll read their first lines in check 3.

Then look at your live site the way a stranger does. This one-liner downloads the scripts a page loads and prints every action ID in them, with the function’s name. Next.js production builds keep the name next to the ID, so you’ll see deleteNote, not just a long number. Change PAGE to read other pages:

Terminal
# The Server Actions your live page's scripts can call, with their names. Put your address in APP.
APP=https://yourapp.com
PAGE=/
curl -s "$APP$PAGE" | grep -oE '<script[^>]+src="[^"]+"' | sed -E 's/.*src="([^"]+)".*/\1/' | while read -r s; do
  case "$s" in http*) curl -s "$s" ;; *) curl -s "$APP$s" ;; esac
done | grep -oE 'createServerReference\)?\("[0-9a-f]{40,66}"[^)]{0,200}\)' | sed -E 's/.*\("([0-9a-f]+)".*"([A-Za-z_$][A-Za-z0-9_$]*)"\)$/\2 \1/' | sort -u
What it printed
Bob's /dashboard (signed in), next build + next start:

deleteNote 40ac19f2dd0550be19b6c3d0375bc2cb6aab6a6aaa
deleteNoteLoginOnly 40aea8a152da1c9abc8eed85968ff7c0b4a962fbc7
deleteNoteSafe 40e9909018d3aa80c84018ad4293df55848921d1f7
renameNote 60b5f6e321969f85ebb8766571edf611eff3a84bb2
updateProfile 600d5fe9fa19ad386c97913f5843884e26bf787c8b
sendInvite 40da04688dccf3077b08daa6c0906e9ed0b07f0fde
...and four more

The public home page: subscribe 409fc74d1b5b651ad8de24f1ec49a79b98657b4b47
lockship.dev: nothing (our forms post to route handlers, not Server Actions)

Two things it won’t show, and our scan has the same blind spots. Pages behind a login don’t load for a stranger, so their actions only show up if you run it signed in (add -H "Cookie: ..." to the first curl). And an inline action in a Server Component, like the Publish form in check 6, doesn’t appear in any script at all; its ID sits in the page’s HTML. The code search above finds both.

03

Check who is calling, inside the action

The check has to be inside the action. Not in the page, not in a layout, and not only in proxy.ts (called middleware.ts before Next.js 16). The data security guide says “A page-level authentication check does not extend to the Server Actions defined within it,” and the Server Actions guide adds: “Render-time gating (only rendering a form on an authenticated page) is not a security boundary, because requests can be sent without going through the UI.”

Proxy is the one people trust most, so we tested it. Our dashboard had a proxy that refused any request to /dashboard without a session cookie. That’s what Next.js’s authentication guide calls an “optimistic” check: it looks at the cookie, it doesn’t verify it. Here is what it stopped and what it didn’t:

Our lab, Next.js 16.4.3
deleteNote (checks nothing), proxy.ts matcher "/dashboard/:path*" checks a cookie exists

no cookie                          401 {"error":"Not signed in"}   <- proxy stopped it
Cookie: session=x (made up)        200 {"ok":true}                 <- proxy only saw a cookie; Alice's note deleted
same ID POSTed to /about           200 {}                          <- nothing ran: the action lives on /dashboard

deleteNoteSafe (getUser() first)
Cookie: session=x                  500, threw "Not signed in", nothing deleted

Proxy stopped the request with no cookie, and waved through a cookie we typed ourselves. Posting the same ID to a different page ran nothing, which matches Next.js’s security post: “Server Actions live on the page they’re used on and as such inherit the same access control.” So proxy is a fine first filter. It just can’t be the check, because it doesn’t know who the cookie belongs to or what the action is about to touch.

And sometimes the first filter isn’t there at all. On Next.js 15.2.2 we put the cookie check in middleware.ts and the action behind it checked nothing. One extra header skipped the middleware, as the advisory describes: “It is possible to bypass authorization checks within a Next.js application, if the authorization check occurs in middleware.”

Our lab, Next.js 15.2.2 and 15.2.3
Next.js 15.2.2: middleware.ts checks a cookie on /dashboard/:path*; deleteAllNotes checks nothing

deleteAllNotes, no cookie                                 401 {"error":"Not signed in"}
deleteAllNotes, no cookie, + x-middleware-subrequest      200 {"ok":true}    <- every note deleted

Next.js 15.2.3, same app
deleteAllNotes, no cookie, + x-middleware-subrequest      401 {"error":"Not signed in"}

Our API route guide reproduces the same bug on a route handler and has more on proxy matchers. The fix for both is the same: upgrade, and put the check where the work happens. Here’s the action with the check inside. The first two lines are the part that matters:

app/actions.ts (lab version)
// app/actions.ts
"use server";
import { z } from "zod";
import { db } from "@/lib/db";
import { getUser } from "@/lib/session"; // your auth library's "who is this?" call, read from the request

export async function deleteNoteSafe(id: unknown) {
  const user = await getUser();
  if (!user) throw new Error("Not signed in");
  const noteId = z.number().int().positive().parse(id);
  const note = db.byIdAndOwner(noteId, user.id);
  if (!note) throw new Error("Not found");
  db.remove(note.id);
  return { ok: true };
}

getUser() here stands for whatever your auth library gives you to read the signed-in user from the request’s cookie or token and verify it on the server. Next.js’s own examples call it auth(); with Supabase it’s supabase.auth.getUser() (check 7). With a thrown error, Next.js production builds send the caller only a digest number, and the message goes to your server log, so “Not signed in” doesn’t leak anything.

04

Check the record is theirs, and don’t trust bound ids

A login check answers “is somebody signed in?” It doesn’t answer “is this note theirs?” Without the second question, any signed-in user can act on anyone’s records by changing an id. That’s an insecure direct object reference, IDOR, and Next.js’s data security guide names it directly: “remember to check authorization (does this user have permission to act on this specific resource?). This prevents Insecure Direct Object Reference (IDOR) vulnerabilities.”

Ids passed with .bind() are the version of this that catches people. Next.js’s forms guide shows updateUser.bind(null, userId) as the way to pass extra arguments, and it’s a fine way to pass them. But in a Client Component the bound value is just the first argument in the request body, in plain JSON. Next.js’s security post says bound arguments “are NOT encrypted,” and that “the argument list to Server Actions ("use server") must always be treated as hostile.” Here’s both, on our lab:

Our lab, Bob signed in
Bob is signed in. Note 1 is Alice's, note 2 is Bob's.

deleteNoteLoginOnly(1)   (checks the login only)          200 {"ok":true}   <- Alice's note deleted
deleteNoteSafe(1)        (login + owner in the lookup)    500 "Not found"    <- Alice's note survives
deleteNoteSafe(2)        (Bob's own)                      200 {"ok":true}

renameNote, bound in the browser with renameNote.bind(null, note.id):
what Bob's Rename button sends               [2,"renamed"]
what Bob sent instead from curl              [1,"Bob was here"]   200   <- Alice's note now says "Bob was here"
renameNoteSafe, same edited body             [1,"Bob was here"]   500 "Not found"

The fix is the same for both: put the signed-in user’s id into the lookup itself, so someone else’s record simply isn’t found.

Binding an id, and the action that doesn’t trust it (lab version)
// app/dashboard/buttons.tsx ("use client")
const rename = renameNote.bind(null, id); // id travels to the server in plain JSON
<button onClick={() => rename("renamed")}>Rename</button>

// app/actions.ts: the bound id is just the first argument, and anyone can change it
export async function renameNoteSafe(id: unknown, text: unknown) {
  const user = await getUser();
  if (!user) throw new Error("Not signed in");
  const input = z.object({ id: z.number().int().positive(), text: z.string().trim().min(1).max(500) }).parse({ id, text });
  const note = db.byIdAndOwner(input.id, user.id);
  if (!note) throw new Error("Not found");
  note.text = input.text;
  return { ok: true };
}

Note that db.byIdAndOwner() is one query with both conditions, not “load it, then compare.” If your code loads first and compares after, make sure it handles the missing case. Next.js’s own example on the Server Actions guide does it with where: { id: itemId, ownerId: session.user.id }, and says to “derive identity from the session, look up by ownership.”

05

Validate every argument, and send back less

TypeScript types are gone by the time your code runs, so id: number in the signature checks nothing. A request can send a string, an object, or a field you never meant to accept. The worst version is an action that takes an object and copies it onto a database row. OWASP calls that mass assignment: an attacker adds fields the developer never planned for, which “creates or overwrites new variable or objects in program code that was not intended.” MITRE files it as CWE-915. We wrote the careless version AI builders often produce, a profile update that trusts the user id and spreads whatever it’s sent:

Our lab, Bob signed in
updateProfile(userId, changes): checks the login, trusts the userId, copies every field, returns the row

Bob sends ["alice",{"name":"Hacked"}]
  200 {"id":"alice","name":"Hacked","email":"alice@example.com","role":"user","passwordHash":"$argon2id$..."}
Bob sends ["bob",{"role":"admin"}]
  200 {"id":"bob",...,"role":"admin",...}          <- Bob made himself an admin

updateProfileSafe(changes): zod strictObject, user from the session, returns only the name
Bob sends [{"name":"Bobby","role":"admin"}]       200 {"error":"Invalid input"}
Bob sends [{"name":"Bobby"}]                      200 {"name":"Bobby"}
made-up cookie                                    200 {"error":"Not signed in"}

deleteNoteSafe, Bob sends "1" (a string) or {"id":1}   500, zod refused both

Two bugs in one request, plus a third: the careless action returned Alice’s whole row, password hash included, because it returned whatever the database gave back. Next.js’s data security guide warns about exactly this: “Server Action return values are serialized and sent to the client. Only return what the UI needs, not raw database records.” OWASP’s API list covers both halves, reading and writing fields you shouldn’t, as broken object property level authorization.

The fix is a schema that lists the fields a person may change, the user taken from the session, and a return value with only what the page shows. We used zod, the library Next.js’s forms guide uses for server-side validation. Two details matter. A plain z.object() quietly drops extra keys (zod’s docs: “By default, unrecognized keys are stripped from the parsed result”), which is safe as long as you only use the parsed data. z.strictObject() refuses them outright, which tells you when someone is poking. And safeParse() returns an error you can answer with instead of throwing:

app/actions.ts (lab version)
// app/actions.ts
"use server";
import { z } from "zod";

// Only the fields a person may change. strictObject refuses anything extra, like "role".
const ProfileChanges = z.strictObject({ name: z.string().trim().min(1).max(80) });

export async function updateProfileSafe(changes: unknown) {
  const user = await getUser();
  if (!user) return { error: "Not signed in" };
  const parsed = ProfileChanges.safeParse(changes);
  if (!parsed.success) return { error: "Invalid input" };
  const profile = db.profile(user.id); // the session says whose profile, never an argument
  if (!profile) return { error: "Not found" };
  profile.name = parsed.data.name;
  return { name: profile.name }; // only what the page shows
}

Validation is about shape, not permission. Next.js’s Server Actions guide says it well: “Schema validation (zod or similar) only checks the shape of the input. A well-formed Item object can still refer to a row the caller does not own.” OWASP’s input validation cheat sheet says to check “both syntax (the expected type and format) and semantics (whether the value makes sense for the operation).” Do both, then check 4.

06

Closures, encrypted values and the action ID myth

Two features make Server Actions feel private when they aren’t. Both are real protections. Neither is a check.

Encrypted closures. An action defined inside a Server Component can use variables from around it, like note.id in a list. Next.js sends those values to the browser and back, and its data security guide says it “automatically encrypts the closed-over variables.” We tried to change one. We couldn’t. We could, however, send the encrypted value back exactly as it was, from a terminal, with a cookie we made up, and the action ran. Encryption stops someone editing the captured id. It doesn’t stop anyone who has the page’s HTML from calling the action. The same guide says “We don’t recommend relying on encryption alone to prevent sensitive values from being exposed on the client.”

Our lab, Next.js 16.4.3
What Bob's page carries for the inline "publish" action (in the HTML, not in any script):
$ACTION_2:0  {"id":"40c7b6c4b99afb7d32fd64bcc5ac0ee73f004c4b9f","bound":"$@1"}
$ACTION_2:2  "LhxpWGgCIWbp+veb1NAabBrpX...oVX8A="     <- note.id, encrypted

publish (no check inside)
  encrypted value sent back as-is, Bob's cookie            200   Bob's note published
  encrypted value sent back as-is, made-up cookie          200   Bob's note published
  encrypted value with one bit changed                     500   refused
  encrypted value swapped for a plain 1                    500   refused

publishSafe (getUser + owner check inside)
  Bob's encrypted value, made-up cookie                    500   "Not signed in"
  Bob's encrypted value, Alice's cookie                    500   "Not found"
  Bob's encrypted value, Bob's cookie                      200   published

Action IDs: identical over four rebuilds of the same project; new ones after rm -rf .next.
wipeAllNotes, exported from a "use server" file and never imported: not in the build at all.

So the inline version still asks who is calling and checks the owner, even though the id itself can be trusted:

app/dashboard/page.tsx (lab version)
// app/dashboard/page.tsx (a Server Component)
{notes.map((note) => {
  async function publishSafe() {
    "use server";
    // note.id was captured when the page rendered. Next.js encrypts it on the way to the browser.
    const me = await getUser();
    if (!me) throw new Error("Not signed in");
    const n = db.byIdAndOwner(note.id, me.id); // still check: anyone holding the form can send it
    if (!n) throw new Error("Not found");
    n.published = true;
  }
  return <form key={note.id} action={publishSafe}><button>Publish</button></form>;
})}

“Encrypted” action IDs. Since Next.js 15, action IDs are “unguessable, non-deterministic IDs” that “are periodically recalculated between builds,” and unused actions are left out of the client bundle. The data security guide is careful about what that buys you: it “reduces the risk in cases where an authentication layer is missing. However, you should still treat Server Actions as reachable via direct POST requests and verify authentication and authorization inside each one.” Our lab matched that. An exported action nobody imported was missing from the build entirely, which is good. Every action a button used was readable in the page’s script with its name, as it has to be for the button to work. The IDs stayed the same over four rebuilds and only changed when we deleted the build cache, which fits the docs’ note that they are “cached for a maximum of 14 days.” Unguessable doesn’t help when the page hands the ID to everyone who loads it.

One thing that does work in your favour: Next.js compares the request’s Origin header with the host and aborts on a mismatch (the data security guide describes it under CSRF). In our lab a request claiming to come from https://evil.example was refused. A request with no Origin at all, which is what curl sends, went through. That check protects your users from other websites. It doesn’t protect your actions from people with a terminal. If you put your app behind another domain or proxy, list it in serverActions.allowedOrigins rather than turning anything off.

07

Supabase: getUser() and RLS inside the action

Supabase apps get this wrong in one particular way. The action calls supabase.auth.getSession() as its login check, then does the work with the secret key (the old service_role key) so it doesn’t have to think about policies. Both halves are the problem. Supabase’s Next.js guide says getSession’s session “isn’t re-validated against the Auth server,” so “don’t rely on the user object it returns for authorization decisions.” And the API keys page says the secret key “bypasses Row Level Security, so it must never leave” your server, which also means nothing in the database stops it deleting the wrong row.

Our lab, real supabase-js against our stand-in
deleteSbNoteCareless: getSession() as the login check, then the secret key to delete
  forged cookie (claims to be Alice, signed with a made-up key), delete note 2 (Bob's)   200, deleted
  Bob's real cookie, delete note 1 (Alice's)                                           200, deleted

deleteSbNoteSafe: getUser() + the user's own client + RLS
  forged cookie, delete note 2                       {"error":"Not signed in"}
  Bob, delete note 1 (Alice's)                       {"error":"Not found"}     <- RLS: 0 rows matched
  Bob, id "1 or 1=1"                                 {"error":"Invalid id"}
  Bob, delete note 2 (his own)                       {"ok":true}

The forged cookie had the right name and shape, but its token was signed with a key we made up. getSession() believed it; getUser(), which the reference describes as fetching “the user object directly from the Auth server,” refused it. The fixed action uses the user’s own client, so the delete runs as that user, and the database’s policy decides which rows they can touch:

app/sb/actions.ts (lab version)
// app/sb/actions.ts
"use server";
import { z } from "zod";
import { createClient } from "@/lib/supabase/server"; // the cookie-based server client from Supabase's Next.js guide

export async function deleteSbNoteSafe(id: unknown) {
  const noteId = z.number().int().positive().safeParse(id);
  if (!noteId.success) return { error: "Invalid id" };
  const supabase = await createClient();
  // getUser() asks Supabase Auth whether the token is real. getSession() only reads the cookie.
  const { data: { user }, error: authError } = await supabase.auth.getUser();
  if (authError || !user) return { error: "Not signed in" };
  // The user's own client, so the delete runs as them and RLS decides which rows it can touch.
  const { data, error } = await supabase.from("notes").delete().eq("id", noteId.data).select("id");
  if (error) return { error: "Could not delete" };
  if (!data.length) return { error: "Not found" }; // RLS hid the row: not theirs, or gone
  return { ok: true };
}
SQL (ran in our stand-in’s Postgres)
alter table public.notes enable row level security;

create policy "Users read their own notes"
on public.notes for select
to authenticated
using ((select auth.uid()) = user_id);

create policy "Users delete their own notes"
on public.notes for delete
to authenticated
using ((select auth.uid()) = user_id);

Note the .select("id") and the data.length check. With RLS, deleting someone else’s row isn’t an error; it just matches nothing. Without asking for the deleted rows back, Bob’s attempt on Alice’s note would have looked like a success. getClaims() works in place of getUser() too, and is faster on projects with asymmetric signing keys. We only tested the shared-secret setup, against a stand-in rather than a hosted project. For the policies themselves, Supabase’s RLS docs and our RLS checklist go further.

08

Rate limit the actions that cost you

An action that sends an email, calls a paid AI API, or creates a record does real work every time it runs, and a loop can run it thousands of times. OWASP’s API list calls this unrestricted resource consumption and lists “emails/SMS/phone calls” among the things that cost money per request. Next.js’s data security guide says: “For expensive operations (sending emails, writing to a database), consider adding rate limiting to prevent abuse.”

If the action calls OpenAI or Anthropic, our AI API route guide has a limit counted in Postgres that holds when your app runs as several copies, plus output caps and provider spend limits. The same checks work inside an action.

Our invite action was signed-in only, and that didn’t slow anything down:

Our lab, Bob signed in
sendInvite (signed in, no limit), 20 calls in a loop as Bob     20 of 20 went through
sendInviteLimited (5 a minute per user), 7 calls as Bob        calls 1-5 {"ok":true}
                                                               calls 6-7 {"error":"Too many invites. Try again in a minute."}
Alice, right after                                             {"ok":true}   <- her own count

Count per user for signed-in actions, so one person’s loop doesn’t lock everyone else out. Count per IP only for public ones, like a newsletter signup. Here is the small limiter we tested:

lib/rate-limit.ts and app/actions.ts (lab version)
// lib/rate-limit.ts: a fixed window kept in this server's memory.
// Fine for one long-running server. On Vercel or any host that runs several copies,
// each copy keeps its own count: use your host's rate limiting or a shared store instead.
const hits = new Map<string, { count: number; resetAt: number }>();

export function rateLimit(key: string, limit: number, windowMs: number): boolean {
  const now = Date.now();
  const entry = hits.get(key);
  if (!entry || entry.resetAt <= now) {
    hits.set(key, { count: 1, resetAt: now + windowMs });
    return true;
  }
  entry.count += 1;
  return entry.count <= limit;
}

// app/actions.ts
export async function sendInviteLimited(email: unknown) {
  const user = await getUser();
  if (!user) return { error: "Not signed in" };
  const parsed = z.email().safeParse(email);
  if (!parsed.success) return { error: "Invalid email" };
  if (!rateLimit(`invite:${user.id}`, 5, 60_000)) return { error: "Too many invites. Try again in a minute." };
  // ...send the email...
  return { ok: true };
}

The honest caveat is in the comment. This counts in one server’s memory. On Vercel and most hosts your app runs as several copies that come and go, and each would keep its own count, so it’s a speed bump, not a wall. For a real limit, use a shared store or your host. Upstash’s @upstash/ratelimit keeps the count in Redis over HTTP and drops in where our rateLimit() call is. On Vercel, WAF rate limiting “is available on all plans” (Hobby gets one rule), and the @vercel/firewall SDK lets you check it from code with your own key; “By default, the key is the client IP.” Next.js’s backend guide suggests both: “In addition to code-based checks, enable any rate limiting features provided by your host.” We didn’t test Upstash or Vercel’s firewall for this page. Next.js also caps an action’s request body at 1MB by default (bodySizeLimit), so leave that alone unless you upload files through actions.

09

The fix, in one action

Here is everything above in one action, in the order it should happen: who is calling, how often, what they sent, whose it is, and what goes back. This is the shape to copy for every action that isn’t public on purpose:

app/actions.ts (lab version)
// app/actions.ts
"use server";
import { z } from "zod";
import { db } from "@/lib/db";
import { getUser } from "@/lib/session";
import { rateLimit } from "@/lib/rate-limit";

const UpdateNote = z.strictObject({
  id: z.number().int().positive(),
  text: z.string().trim().min(1).max(500),
});

export async function updateNote(input: unknown) {
  // 1. Who is calling? Ask the session on the server, every time.
  const user = await getUser();
  if (!user) return { error: "Not signed in" };

  // 2. Slow down scripts. 30 saves a minute is plenty for a person.
  if (!rateLimit(`updateNote:${user.id}`, 30, 60_000)) return { error: "Too many requests" };

  // 3. Is it what we expect? Anything else, including extra fields, is refused.
  const parsed = UpdateNote.safeParse(input);
  if (!parsed.success) return { error: "Invalid input" };

  // 4. Is it theirs? The owner goes into the lookup itself.
  const note = db.byIdAndOwner(parsed.data.id, user.id);
  if (!note) return { error: "Not found" };

  note.text = parsed.data.text;
  // 5. Send back only what the page shows.
  return { ok: true, text: note.text };
}
What it did in our lab
made-up cookie                               {"error":"Not signed in"}
Bob, Alice's note 1                          {"error":"Not found"}
Bob, his note plus "ownerId":"alice"         {"error":"Invalid input"}
Bob, id as the string "2"                    {"error":"Invalid input"}
Bob, 600 characters of text                  {"error":"Invalid input"}
Bob, his own note                            {"ok":true,"text":"Bob edited this"}
35 more saves in a loop                      25 saved, 10 refused with "Too many requests"
                                             (the 30-a-minute limit counts his 5 earlier calls too)

If you have many actions, Next.js’s data security guide suggests moving steps 1 and 4 into a server-only data access layer, so every action that touches notes goes through the same checked functions and a new action can’t forget them.

Have your AI builder do it

This is the prompt we’d paste into v0, Cursor, Lovable or whatever wrote the app. It asks for a list back, so you can check what it did instead of trusting that it did:

Prompt for your AI builder
Go through every Server Action in this app: every file that starts with "use server" and every function with "use server" inside it, including inline ones in pages. Treat each one as a public POST endpoint that anyone can call with any arguments, whether or not a button for it is on screen. For each action that isn't meant to be public: (1) the first thing it does is find out who is signed in on the server, from the session or a verified token (with Supabase, supabase.auth.getUser() or getClaims(), never getSession()), and stop if nobody is; (2) it validates every argument with a zod schema (z.strictObject for objects, so extra fields like role or ownerId are refused) and never trusts a user id, owner id or price sent by the browser, including values passed with .bind(); (3) every record it reads or changes is looked up with the signed-in user's id in the query itself, and someone else's record is treated as not found; (4) it returns only the fields the page shows, never a whole database row; (5) actions that send email, call paid APIs or create records have a per-user rate limit. Don't rely on proxy.ts, middleware, a layout or a hidden button for any of this. List every action, what it checks now, and anything you left public on purpose. Change nothing else.

10

Test it without breaking your live app

Don’t aim the curl tests on this page at your live app. An action runs for real, so testing it from outside means really deleting or changing something. Run your app locally or on a preview with test data, sign in as a test user, copy one action’s request from DevTools (Network tab, the POST with a Next-Action header), and replay it with curl: once with no cookie, once with a made-up cookie, once with a second test account’s cookie and the first account’s id. You want “Not signed in”, “Not signed in” and “Not found”. Then send a wrong type and an extra field, and loop the expensive ones.

On the live site, stick to the two-account test in the browser: sign in as B and try to reach A’s things through the app’s own screens. Then use the app normally as A for a minute, because a check that’s too strict breaks your own pages first. Re-run the code search from check 2 after every big change. A new screen usually means a new action, and the new action copies the shape of an old one, checks and all, or without them.

What a clean result means

Every action that isn’t public on purpose asks who is calling in its first lines, validates its arguments with a schema, looks records up with the caller’s id, returns only what the page shows, and the ones that cost you something have a limit. Next.js is on a patched version. That still says nothing about your API routes, your database rules for the browser, keys in your JavaScript or your headers. Those are on the checklist, and API routes have their own guide.

Where LockShip fits

We built LockShip to read your app from the outside, the way a stranger would, and Server Actions are a place where we’re careful about what that can and can’t tell you. The scan reads your homepage’s scripts, the scripts of a few pages it finds linked from it, and the chunks those load later. In that code it counts the action references, the same createServerReference pattern as the one-liner in check 2, and lists them under “What this scan did not test” as “Server Actions your pages can call,” with up to eight names when the build keeps them. It never calls them, because that would run them for real. The note links to this page.

What it doesn’t do: it never signs in, so actions on pages behind a login usually aren’t in what it can see. On our lab it counted one action, the public subscribe button, out of the sixteen in its code. Inline actions in Server Components don’t show up in scripts at all. It can’t tell whether an action checks who is calling, because that’s in your server code. What it can see from outside is your Next.js version, and it flags the versions in CVE-2025-55182 and CVE-2025-29927. Apart from its CORS preflights, the scan only sends GET and HEAD requests, and it never writes anything. A clean result means “nothing obvious from the outside right now,” not “safe.”

The summary is free: a score and the single worst thing we found. The $39 Launch Safe certificate includes every finding with a fix prompt you can paste into your builder, a PDF, and seven days of re-scans while you fix things. Monitor, at $9 a month, re-runs the scan every week and emails you once when a new critical or high issue shows up.

Want to see what your app shows a stranger?

Paste your app’s address, prove you own it, and see the worst thing we find. The summary is free.

Run a free scan

Before you rely on a result, read the disclaimer.

Questions people ask

My page already redirects people who aren’t signed in. Isn’t the action behind it safe?

No. The redirect decides what the page shows, not who can call the action. Next.js’s data security guide says “A page-level authentication check does not extend to the Server Actions defined within it.” In our lab the dashboard checked the login, and the action on it still deleted another user’s note for a request that came from a terminal.

Next.js encrypts action IDs. Doesn’t that mean nobody can call them?

No. The ID has to be in your page’s JavaScript for your own button to work, so anyone who loads the page can read it. Our one-liner in check 2 prints every ID with its function name. What Next.js does do is leave unused actions out of the build and change the IDs when the build cache changes. That helps with forgotten code. It doesn’t replace a check.

Do I need zod, or is TypeScript enough?

TypeScript types disappear when the code is built, so they don’t check anything at runtime. An action typed as taking a number will happily receive a string or an object from a curl request. Use zod or a similar library to check the shape on the server. Then still check ownership, because a well-formed id can belong to somebody else.

Does Next.js’s CSRF protection stop strangers calling my actions?

It stops other websites from making your users’ browsers call them. Next.js compares the Origin header with the Host and aborts the action when they don’t match; we saw that refuse a request from https://evil.example. A script outside a browser simply sends no Origin header, and that request went through. It protects your users from other sites, not your actions from people.

Is it safe to test my actions like this on the live site?

No. An action does real work when it runs, so a test from outside really deletes or changes something. Do the curl tests on localhost or a preview with test data, read the code for the rest, and on the live site stick to the two-account test in the browser with your own test accounts.

Keep reading

Sources

We read each of these on 26 October 2026. Frameworks change their examples, so if something here disagrees with their docs, trust the docs and tell us at hi@lockship.dev. The lab results are our own, from test apps with made-up users on our own machine. We didn’t test on any host’s account or against a hosted Supabase project, and we didn’t run any of this against anyone else’s app.