Nextjs Fundamentals · Server Functions & Mutations

Authorizing Server Actions

authz inside every action

Authorizing Server Actions

Every Server Function you export is a public HTTP endpoint. Next.js creates a secure ID so the client can call it, but it is still reachable by a direct POST request — even if no component imports it. So you must never assume a request came from your own UI.

In particular, a page-level check does not protect the actions defined in that page. The page guard controls which UI renders; the action is a separate entry point and must verify the caller itself:

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

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

export async function deletePost(postId: string) {
  const session = await auth();
  if (!session?.user) throw new Error('Unauthorized');

  const post = await db.post.findUnique({ where: { id: postId } });
  if (post.authorId !== session.user.id) throw new Error('Forbidden');

  await db.post.delete({ where: { id: postId } });
}

Authentication asks is the user logged in? Authorization asks may this user act on this specific resource? Checking both inside every action prevents insecure direct object reference (IDOR). Treat the client's input as untrusted, and return only the fields the UI needs. Many teams centralise these checks in a server-only Data Access Layer and keep the 'use server' action thin.

You are about to answer a short quiz on authz inside every action.

  1. A Server Action is reachable by a direct POST request, even if no component imports it.
  2. A page-level auth check also protects the Server Actions defined in that page.
  3. Authentication asks whether the user is logged in; ___ asks whether they may act on this resource.
  4. You should verify authentication and authorization inside every Server Action.
  5. Checking that the user owns the record they are deleting prevents ___ vulnerabilities.