Securing Next.js Server Actions: Common AI-Generated Vulnerabilities and Fixes
Why 'use server' is a public API endpoint and how to prevent authentication bypass and IDOR in Server Actions.
Table of Contents7 sections
Next.js introduced Server Actions to simplify calling backend logic directly from React components without writing manual fetch() handlers or separate REST endpoints. When you add "use server" to the top of an async function, Next.js compiles it into an endpoint automatically.
However, in AI-generated codebases written by tools like Cursor, Claude, or v0, Server Actions are the #1 source of critical authorization vulnerabilities.
AI models frequently treat Server Actions as if they are private internal function calls protected by the surrounding UI. In reality, every Server Action is a public HTTP POST endpoint callable by anyone with a curl command.
The Myth of Private Server Actions
Consider this innocent-looking component generated by an AI assistant:
// app/documents/page.tsx
import { deleteDocumentAction } from "./actions";
export default function DocumentPage({ document, currentUser }) {
return (
<div>
<h1>{document.title}</h1>
{currentUser.isAdmin && (
<button onClick={() => deleteDocumentAction(document.id)}>
Delete Document
</button>
)}
</div>
);
}The AI hid the delete button behind currentUser.isAdmin. In the browser, a regular user will never see the button.
Now look at the server action the AI wrote in actions.ts:
// app/documents/actions.ts
"use server";
import { db } from "@/server/db";
import { documents } from "@/drizzle/schema";
import { eq } from "drizzle-orm";
export async function deleteDocumentAction(documentId: string) {
// BUG: No session check, no role check!
await db.delete(documents).where(eq(documents.id, documentId));
return { success: true };
}Because this Server Action is compiled into an HTTP POST request, any user—even someone who is completely logged out—can invoke deleteDocumentAction directly using a browser console script or curl with any document ID they want:
curl -X POST 'https://your-app.com/documents' \
-H 'Next-Action: 8f9b23...' \
-H 'Content-Type: text/plain' \
-d '["doc-999"]'The database deletes the document without hesitation. Hiding a button in React is not security.
Vulnerability 1: Missing Session Verification
In a secure application, every single Server Action must authenticate the caller on the server before doing anything else.
Never trust that because a user is on an authenticated page, the Server Action is safe. Validate the session right inside the action:
import { auth } from "@/server/auth";
import { headers } from "next/headers";
export async function updateOrganizationName(orgId: string, newName: string) {
"use server";
// 1. Authenticate the caller
const session = await auth.api.getSession({
headers: await headers(),
});
if (!session?.user) {
throw new Error("Unauthorized: You must be logged in.");
}
// Continue with authorized logic...
}Vulnerability 2: IDOR / Broken Object-Level Authorization
Even if a user is logged in, you must verify that they have permission to modify that specific object.
Here is a common flaw AI generates:
// VULNERABLE CODE:
export async function updateNoteAction(noteId: string, content: string) {
"use server";
const session = await requireAuth();
// The user is logged in, but do they OWN this note?
// If User A passes noteId="123" belonging to User B, it updates User B's note!
await db
.update(notes)
.set({ content })
.where(eq(notes.id, noteId));
}The Fix: Always include the authenticated user's ID or organization ID in the where clause:
// SECURE CODE:
export async function updateNoteAction(noteId: string, content: string) {
"use server";
const session = await requireAuth();
const [updatedNote] = await db
.update(notes)
.set({ content, updatedAt: new Date() })
.where(
and(
eq(notes.id, noteId),
eq(notes.userId, session.user.id) // Enforce tenant isolation!
)
)
.returning();
if (!updatedNote) {
throw new Error("Note not found or you do not have permission to edit it.");
}
return updatedNote;
}Vulnerability 3: Unvalidated Inputs and Type Confusion
TypeScript types disappear at runtime. When an AI writes async function createProject(name: string, budget: number), an attacker can send an object, a 10MB payload, or special characters.
Always validate inputs with Zod at the boundary of your Server Action:
import { z } from "zod";
const createProjectSchema = z.object({
name: z.string().trim().min(3).max(80),
budget: z.number().int().positive().max(1_000_000),
isPublic: z.boolean().default(false),
});
export async function createProjectAction(rawInput: unknown) {
"use server";
const session = await requireAuth();
// Runtime Zod validation
const parsed = createProjectSchema.safeParse(rawInput);
if (!parsed.success) {
return {
success: false,
error: "Invalid input. Please check your submission.",
};
}
const { name, budget, isPublic } = parsed.data;
// Insert safely
await db.insert(projects).values({
name,
budget,
isPublic,
userId: session.user.id,
});
return { success: true };
}The Production-Safe Server Action Pattern
To prevent bugs across your entire engineering team, build a reusable action wrapper that handles authentication, authorization, and Zod parsing consistently:
// lib/safe-action.ts
import { auth } from "@/server/auth";
import { headers } from "next/headers";
import { z } from "zod";
export function createProtectedAction<TInput, TOutput>(
schema: z.ZodSchema<TInput>,
handler: (input: TInput, ctx: { userId: string; userEmail: string }) => Promise<TOutput>
) {
return async (rawInput: unknown): Promise<{ success: boolean; data?: TOutput; error?: string }> => {
try {
const session = await auth.api.getSession({ headers: await headers() });
if (!session?.user) {
return { success: false, error: "Please sign in to continue." };
}
const parsed = schema.safeParse(rawInput);
if (!parsed.success) {
return { success: false, error: "Validation failed." };
}
const result = await handler(parsed.data, {
userId: session.user.id,
userEmail: session.user.email,
});
return { success: true, data: result };
} catch (err) {
console.error("Action error:", err);
return { success: false, error: "An unexpected error occurred. Please try again." };
}
};
}Server Actions Security Checklist
- ☐Every Server Action verifies
session?.useron the server before mutating or reading data. - ☐Database mutations always restrict queries with
and(eq(table.id, id), eq(table.userId, session.user.id)). - ☐Inputs are validated at runtime with Zod schemas.
- ☐Sensitive internal database error strings (e.g. Postgres constraint names) are caught and replaced with friendly error messages.
- ☐Rate limits are applied to expensive Server Actions (e.g., AI generations or emails) using Upstash Redis.
Need an Expert Security Review?
Server Actions vulnerabilities are subtle and can be easily missed during rapid vibe-coding sessions. vibesupport offers automated code scanning and human engineer PR reviews to ensure your Next.js application is watertight before launch day.
Don't let a hidden bug derail your launch.
vibesupport scans your AI-built codebase or live website for exposed secrets, missing database RLS, and broken access controls—then pairs you with senior engineers to fix them directly in GitHub.