Skip to content
Back to skills

Nextjs Server Action Rules

ASecurity

Team conventions for Next.js server actions: auth and permission checks inside every action, Zod validation with coerced FormData, the shared ActionResponse<T> result, revalidation, business logic kept in services, and how forms call actions. Use when writing, fixing or reviewing a server action or a form that submits to one. Background knowledge that agents preload or load on demand; not a command.

  • 2 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added December 1, 2026
developmenttypescriptrustgoreactnextjs

Works with

  • cli

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add JanSzewczyk/claude-plugins --skill nextjs-server-action-rules --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Nextjs Server Action Rules?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Nextjs Server Action Rules
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/janszewczyk-nextjs-server-action-rules/badge)](https://www.skillsdirectory.com/skills/janszewczyk-nextjs-server-action-rules)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: nextjs-server-action-rules
description: "Team conventions for Next.js server actions: auth and permission checks inside every action, Zod validation with coerced FormData, the shared ActionResponse<T> result, revalidation, business logic kept in services, and how forms call actions. Use when writing, fixing or reviewing a server action or a form that submits to one. Background knowledge that agents preload or load on demand; not a command."
user-invocable: false
---

<!-- generated by knowledge.mjs from 14 note(s) (sha256 bd5bdd76cb11); edit the notes in knowledge/, then run build -->

# Next.js server action rules

Apply these rules to every server action and every form that calls one. Pages, layouts and errors are in `nextjs-rules`, logging in `loglayer-rules`. The first section is always in force; open a rule from the table when the task touches it.

## Always apply (critical, high)

### Check the session and the right to the resource inside every server action

_critical · typescript, react, nextjs_

**Rule.** Start every server action by reading the session on the server and calling `unauthorized()` when there is none, then run the feature's `canX` check from `permissions.ts` and call `forbidden()` when it fails. Do this in the action itself, even when the page already checked. The service runs the same check in its own guard chain, because routes and jobs call it too.

**Why.** Anyone can call an exported action directly with a crafted POST, so an action that relies on the page's guard lets a signed-out user, or another user, change data they do not own.

**Incorrect:**

```ts
export async function deleteBudget(budgetId: string): ActionResponse<null> {
  const [error] = await removeBudget(budgetId); // the page checked the session
  return error ? { success: false, error: "Could not delete" } : { success: true, data: null };
}
```

**Correct:**

```ts
export async function deleteBudget(budgetId: string): ActionResponse<null> {
  const { isAuthenticated, userId } = await auth();
  if (!isAuthenticated) unauthorized();
  const [permissionError] = await canEditBudget(userId, budgetId);
  if (permissionError) forbidden();
  const [error] = await removeBudget({ userId, budgetId });
  return error ? { success: false, error: "Could not delete" } : { success: true, data: null };
}
```

**Exceptions.** Without `experimental.authInterrupts`, redirect to sign-in instead of `unauthorized()` and call `notFound()` instead of `forbidden()`.

### Re-validate every action input with the schema's safeParse and return its fieldErrors

_critical · typescript, react, nextjs, zod@>=4_

**Rule.** Parse every action argument with the feature's Zod schema using `safeParse`, use only `parsed.data` afterwards, and on failure return `{ success: false, error, fieldErrors: z.flattenError(parsed.error).fieldErrors }`. Do this even when the form already validated with the same schema.

**Why.** A TypeScript parameter type is erased at runtime, so an action that trusts it writes whatever a crafted request sends: a negative amount, another user's id, or a 10 MB string.

**Incorrect:**

```ts
export async function createBudget(input: BudgetInput): ActionResponse<Budget> {
  const [error, budget] = await insertBudget(input); // validated only in the browser
  ...
```

**Correct:**

```ts
export async function createBudget(input: BudgetInput): ActionResponse<Budget> {
  const parsed = budgetSchema.safeParse(input);
  if (!parsed.success) {
    return { success: false, error: "Check the form", fieldErrors: z.flattenError(parsed.error).fieldErrors };
  }
  const [error, budget] = await insertBudget(parsed.data);
  ...
```

**Exceptions.** On Zod 3, use `parsed.error.flatten().fieldErrors`.

### Keep queries and domain rules in the service layer, not in the server action

_high · typescript, react, nextjs_

**Rule.** Let a server action orchestrate only: auth, validation, one call to a service function that returns `[error, data]`, revalidation and the response. Put queries, limits and other domain rules in that service function.

**Why.** A rule written in an action (a 20-budget limit, a uniqueness check) is copied into the next action and the route handler that does the same job, and it cannot be tested without mocking the request.

**Correct:**

```ts
const [error, budget] = await createBudgetForUser(session.userId, parsed.data); // limit checked inside
if (error) return { success: false, error: error.code === ServiceErrorCode.VALIDATION ? error.message : "Could not create the budget" };
```

### Type every server action as the shared ActionResponse<T> or RedirectAction

_high · typescript, react, nextjs_

**Rule.** Declare each action's return type as `ActionResponse<T>` when it returns data, or `RedirectAction` when it ends in `redirect()`, both imported from `~/lib/action-types`. Return `{ success: false, error, fieldErrors? }` for every expected failure; never throw, never return bare data, and never declare a local result type.

**Why.** When one action throws, another returns raw data and a third its own `{ ok, msg }`, every form needs its own handling, and a thrown error reaches the client as an opaque message the form cannot show.

**Correct:**

```ts
import type { ActionResponse } from "~/lib/action-types";

export async function createBudget(input: BudgetInput): ActionResponse<Budget> {
  const [error, budget] = await insertBudget(input);
  if (error) return { success: false, error: "Could not create the budget" };
  return { success: true, data: budget, message: "Budget created" };
}
```

### Run a server action as authenticate, authorize, validate, mutate, revalidate, return

_high · typescript, react, nextjs_

**Rule.** Write every action body in this order: authenticate, authorize, validate input, call the service that mutates, revalidate the affected cache, return the result. Stop at the first step that fails.

**Why.** An ownership check placed after the write runs too late to stop it, and validation placed before authentication tells an anonymous caller which inputs the action accepts.

**Correct:**

```ts
const { isAuthenticated, userId } = await auth();
if (!isAuthenticated) unauthorized();
const [permissionError] = await canEditBudget(userId, id);
if (permissionError) forbidden();
const parsed = budgetSchema.safeParse(input);
if (!parsed.success) return { success: false, error: "Check the form", fieldErrors: z.flattenError(parsed.error).fieldErrors };
const [error, budget] = await updateBudget(id, parsed.data);
if (error) return { success: false, error: "Could not save the budget" };
revalidatePath(`/budgets/${id}`);
return { success: true, data: budget };
```

### Set the toast cookie only when the action redirects; otherwise toast from the result

_high · typescript, react, nextjs, sonner_

**Rule.** Call `setToastCookie(message, type)` immediately before `redirect()` and nowhere else. When the action returns a result, the calling component shows it with sonner: `toast.success(result.message)` or `toast.error(result.error)`.

**Why.** A cookie set on a branch that returns is read only on the next navigation, so the toast appears late on another page, or is overwritten by the next action's cookie; a cookie set after `redirect()` never runs.

**Correct:**

```ts
if (error) return { success: false, error: "Failed to update the budget" }; // client toasts it
await setToastCookie("Budget deleted", "success");
redirect("/budgets");
```

## Read when the task touches it

| Impact | Rule | Applies to |
| --- | --- | --- |
| medium | [Coerce FormData strings to their types in the schema with z.coerce](references/rules.md#coerce-formdata-strings-to-their-types-in-the-schema-with-zcoerce) — Every FormData value is a string or File; the schema converts it, not hand-written parsing in the action. | typescript, react, nextjs, zod |
| medium | [Map an action's fieldErrors onto React Hook Form fields with setError](references/rules.md#map-an-actions-fielderrors-onto-react-hook-form-fields-with-seterror) — Each server field error becomes setError(field, { type: "server" }); an error without fields goes to root. | typescript, react, nextjs, react-hook-form |
| medium | [Pick the client hook by how the action is triggered](references/rules.md#pick-the-client-hook-by-how-the-action-is-triggered) — useActionState for a native form, React Hook Form plus useTransition for a rich one, useOptimistic for instant feedback. | typescript, react, nextjs, react-hook-form |
| medium | [Put each server action in its own verb-named file that starts with "use server"](references/rules.md#put-each-server-action-in-its-own-verb-named-file-that-starts-with-use-server) — features/<feature>/server/actions/create-budget.action.ts holds one action under a file-level "use server" directive. | typescript, react, nextjs |
| medium | [Call useFormStatus in a component rendered inside the form](references/rules.md#call-useformstatus-in-a-component-rendered-inside-the-form) — useFormStatus reads the parent form; called in the component that renders the form it is always idle. | typescript, react, nextjs |
| medium | [Revalidate only after a successful mutation, and only the paths or tags it changed](references/rules.md#revalidate-only-after-a-successful-mutation-and-only-the-paths-or-tags-it-changed) — Call revalidatePath or updateTag on the success branch for the affected routes; never revalidatePath("/"). | typescript, react, nextjs |
| medium | [Show validation errors next to their fields, never in a toast](references/rules.md#show-validation-errors-next-to-their-fields-never-in-a-toast) — fieldErrors render inline under each input with aria-invalid; toasts are for page-level outcomes. | typescript, react, nextjs, sonner |
| medium | [Infer input types and derive variant schemas from one Zod schema per entity](references/rules.md#infer-input-types-and-derive-variant-schemas-from-one-zod-schema-per-entity) — z.infer gives the type, .partial / .pick / .extend give update and subset schemas; nothing is declared twice. | typescript, zod |

Files in this skill

  • SKILL.md9.9 KB
  • references/rules.md10 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.