Server Actions in Next.js: authorization and validation inside each action
Server Action is a public POST endpoint
The function with "use server" looks like a normal call from a component, and this is deceptive. Next.js registers an ID for it, and the browser calls it with a POST request to the page URL with the title Next-Action. Anyone who opened the page sees this ID in network requests and can retry the call with any arguments via curl.
Hence two rules that do not depend on anything else:
- 1.Each action itself checks who calls it and whether it has the right to perform this action.
- 2.Each action itself checks the input data. The TypeScript type of a parameter does not guarantee anything at runtime.
The fact that the delete button is visible only to the administrator, or that the page is closed by middleware, is not protection. In March 2025, the CVE-2025-29927 vulnerability was fixed: a special header allowed middleware to be skipped entirely. Applications whose authorization lived only there were open.
Session access layer
// lib/auth/session.ts
import "server-only";
import { cookies } from "next/headers";
import { cache } from "react";
import { db } from "@/lib/db";
export const getSession = cache(async () => {
const jar = await cookies(); // в Next.js 15 cookies() асинхронна
const token = jar.get("__Host-session")?.value;
if (!token) return null;
return db.session.findValid(token); // { userId, role } или null
});
export async function requireUser() {
const s = await getSession();
if (!s) throw new Error("unauthenticated");
return s;
}Importing server-only will turn accidentally importing this module into a client component into a build error. cache from React deduplicates session reading within a single request.
Wrapper for action
// lib/actions/safe-action.ts
import "server-only";
import { z } from "zod";
import { requireUser } from "@/lib/auth/session";
export type ActionResult<T> = { ok: true; data: T } | { ok: false; error: string };
export function authedAction<S extends z.ZodTypeAny, T>(
schema: S,
handler: (input: z.infer<S>, user: { userId: string; role: string }) => Promise<T>
) {
return async (raw: unknown): Promise<ActionResult<T>> => {
const user = await requireUser().catch(() => null);
if (!user) return { ok: false, error: "Нужно войти" };
const parsed = schema.safeParse(raw);
if (!parsed.success) return { ok: false, error: "Некорректные данные" };
return { ok: true, data: await handler(parsed.data, user) };
};
}Application: checking ownership, not just login
// app/threads/[id]/actions.ts
"use server";
import { z } from "zod";
import { revalidatePath } from "next/cache";
import { authedAction } from "@/lib/actions/safe-action";
import { db } from "@/lib/db";
const EditInput = z.object({
threadId: z.string().uuid(),
body: z.string().trim().min(1).max(20_000),
});
export const editThread = authedAction(EditInput, async ({ threadId, body }, user) => {
const updated = await db.query(
`UPDATE threads SET body = $1, updated_at = now()
WHERE id = $2 AND (author_id = $3 OR $4 = 'moderator')
RETURNING id`,
[body, threadId, user.userId, user.role]
);
if (updated.rowCount === 0) throw new Error("not found or forbidden");
revalidatePath(`/threads/${threadId}`);
return { id: threadId };
});Ownership check is built into WHERE: you cannot edit someone else's branch by substituting threadId. This is a classic IDOR vulnerability, and it is especially common in Server Actions because the ID comes “from its own component.” Any arguments - passed directly, through .bind or hidden form fields - come from the client and can be replaced.
Forms and useActionState
"use client";
import { useActionState } from "react";
import { editThreadForm } from "./actions";
export function EditForm({ threadId }: { threadId: string }) {
const [state, action, pending] = useActionState(editThreadForm, null);
return (
<form action={action}>
<input type="hidden" name="threadId" value={threadId} />
<textarea name="body" required maxLength={20000} />
<button disabled={pending}>Сохранить</button>
{state && !state.ok && <p role="alert">{state.error}</p>}
</form>
);
}Action for the form gets (prevState, formData). Make a thin adapter that turns FormData into an object via Object.fromEntries(formData) and passes it to the same Zod schema. required and maxLength in markup are user convenience, not validation.
What else to consider
- Returned data. Everything that the action returns goes to the browser. Do not return the entire record from the database: it contains hashes of passwords, emails of other users, and service fields.
- Errors. In production, Next.js replaces the text of the thrown error with the common one with
digest, so that the details do not leak, but the user will not understand anything. Return expected errors as the value{ ok: false }, unexpected errors - throw and log. - CSRF. Next.js accepts actions only using the POST method and compares the
Originheader with the host. If the site is behind a proxy with a different domain, allowed sources are set inexperimental.serverActions.allowedOrigins. There is no need to disable this check. - Body size. By default limited to 1 MB, changes via
experimental.serverActions.bodySizeLimit. Don't raise it unnecessarily: it is better to upload files through signed storage URLs. - Frequency. An action that sends emails or creates posts needs a limit just like a regular API.
How to check your actions
Open DevTools, perform the action and copy the request as cURL. Repeat it from the terminal: without a session cookie, with another user's cookie, with someone else's threadId, with a body of 10,000 characters over the limit. Each option should result in a failure, not a change in data.
When actions are not appropriate
For a public API, mobile client or webhooks, use Route Handlers: they have a stable URL, an explicit method and a clear contract. Server Actions are convenient for mutations from their own interface, but the verification rules for them are not softer, but stricter - they are easier to forget.