AleannLab

Server Actions With No Auth Check: Every Action Is a Public Endpoint

AleannLab team3 min read

A Server Action looks like a function call, but Next.js turns it into an HTTP POST endpoint. Anyone can send that POST with any arguments, without ever opening the page the action lives on. Protecting the page does not protect the action. Each action has to check the session, check permission, and validate its input, the same way an API route would.

On this page
  1. The pattern
  2. What every action needs
  3. Hidden inputs and bound arguments are client input
  4. Watch what the action returns
  5. Find unprotected actions
  6. Make the safe path the short one

Server Actions remove the boilerplate of writing API routes. They also remove the visual reminder that you are writing an API route. That is why AI-generated actions so often look like this.

The pattern

TypeScript
// app/admin/actions.ts
'use server';

import { db } from '@/lib/db';

export async function deleteUser(userId: string) {
  await db.user.delete({ where: { id: userId } });
}

export async function setPlan(userId: string, plan: string) {
  await db.user.update({ where: { id: userId }, data: { plan } });
}

The /admin page checks that the visitor is an admin before rendering. The reasoning goes: only admins can see the page, so only admins can trigger the action.

The action does not know which page called it. Next.js gives it an ID and accepts a POST with a Next-Action header carrying that ID. The ID is in the JavaScript sent to browsers that load the form. A user who has it can call setPlan with their own ID and "enterprise".

Next.js does add some protection. Action IDs are unguessable and change between builds, unused actions are removed from the bundle, and there is an origin check against cross-site requests. These make actions harder to find. They do not decide who may run them. The Next.js documentation says to treat Server Actions like public-facing API endpoints, and that is the right mental model.

What every action needs

1. Who is calling. Read the session inside the action.

2. Are they allowed. Role for admin actions, ownership for user data.

3. Is the input what you expect. TypeScript types disappear at runtime. The argument typed string can arrive as an object, an array or a 5 MB blob.

TypeScript
'use server';

import { z } from 'zod';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';

const SetPlanInput = z.object({
  userId: z.string().uuid(),
  plan: z.enum(['free', 'pro']),
});

export async function setPlan(input: unknown) {
  const session = await auth();
  if (!session) throw new Error('Unauthorized');
  if (session.user.role !== 'admin') throw new Error('Forbidden');

  const { userId, plan } = SetPlanInput.parse(input);

  await db.user.update({ where: { id: userId }, data: { plan } });
}

For actions on the caller's own data, do not accept a user ID at all:

TypeScript
export async function updateDisplayName(input: unknown) {
  const session = await auth();
  if (!session) throw new Error('Unauthorized');

  const { name } = z.object({ name: z.string().min(1).max(80) }).parse(input);

  await db.user.update({
    where: { id: session.user.id },   // from the session, not from the client
    data: { name },
  });
}

Hidden inputs and bound arguments are client input

A form with <input type="hidden" name="orderId" value="123"> sends whatever the user edits it to. Same for IDs passed with .bind(null, orderId): Next.js encrypts values captured in a closure, but arguments passed with .bind are sent as plain data. Either way, check that the order belongs to the caller. The safe habit is simple. Any ID that arrives in an action gets an ownership check:

TypeScript
const order = await db.order.findFirst({
  where: { id: orderId, userId: session.user.id },
});
if (!order) throw new Error('Not found');

Watch what the action returns

Whatever an action returns is serialised and sent to the browser. return user after an update ships the whole row, including passwordHash or stripeCustomerId if they are on it. Return the fields the UI needs.

Find unprotected actions

List the files:

bash
grep -rl "'use server'\|\"use server\"" app src 2>/dev/null

Open each one and check every exported async function for the three steps above. Inline actions (a 'use server' line inside a function in a component file) are easy to miss, so search for the directive, not for file names.

Then test one for real. Submit the form with the network tab open, copy the request as cURL, remove the cookie header and send it again. Then send it with a normal user's cookie and someone else's ID. You should get an error both times.

Make the safe path the short one

A small wrapper keeps the checks from being forgotten:

TypeScript
export function adminAction<T>(schema: z.ZodType<T>, fn: (input: T, admin: User) => Promise<unknown>) {
  return async (raw: unknown) => {
    const session = await auth();
    if (!session) throw new Error('Unauthorized');
    if (session.user.role !== 'admin') throw new Error('Forbidden');
    return fn(schema.parse(raw), session.user);
  };
}

Libraries such as next-safe-action provide the same pattern. Add a line to your agent rules file: "Every Server Action starts with an auth check and parses input with zod."

Related: auth checked only in the UI and middleware that skips API routes. This is check 1 in our security checklist for vibe-coded apps, and a standard part of our app rescue and security audit.

All articles →

Gotowy, aby omówić swój projekt z nami?

idea
*
*
*
Interesuje mnie...
Tworzenie stron internetowych
Tworzenie aplikacji
Projektowanie UX/UI
DevOps
Sztuczna inteligencja i uczenie maszynowe
Testowanie QA
Tworzenie aplikacji mobilnych
Konsultacja
Outsourcing
Budżet projektu (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Prześlij plik