Thuta Learning
Next.js
AdvancedWeb DevelopmentIntermediate

Server Actions, Forms, and Validation

Next.jsLesson 1840 min

What you'll walk away with

  • Write a "use server" function that receives FormData and returns a typed result state
  • Validate every field on the server with a schema, even when the form already has HTML validation
  • Check authentication and authorization inside every action that changes data
  • Show errors and pending state with useActionState and revalidate cached data afterwards

Explain it simply

Server Actions in plain language

A Server Action is like a letterbox slot in the server's door. The form drops an envelope in and the server opens it. Next.js cuts the slot for you, creating the endpoint and the request, so you only pass a function to the form's action prop.

But anyone can push any envelope through that slot. So the server does not trust the label on the envelope; it reads the letter and checks the sender.

Problem → Why → Solution

The problem: an action that trusts the browser

A developer adds required minLength={3} to the title input and shows the Delete button only to the note's owner, and considers the job done. But devtools can remove attributes, and a Server Action is a public endpoint the browser calls with a POST request. A signed-in member who sends someone else's note id gets that note deleted, because the code below checks nothing.

app/notes/actions.ts
"use server";
export async function deleteNote(formData: FormData) {
  const id = formData.get("id") as string; // whatever the browser sent
  await db.note.delete({ where: { id } }); // no login check, no owner check
  revalidatePath("/notes");
}

Written like a function, defended like an endpoint

Because you import and call it, a Server Action feels like an ordinary function. In reality its arguments arrive over the network and TypeScript types check nothing at runtime. Browser validation is a convenience for the user; the security lives inside the action.

Core concept: a function you write like a public endpoint

A Server Action is an async function with the "use server" directive. Written at the top of a file, it makes every exported function in that file an action; it can also be written inside a function body in a Server Component. Pass it to <form action={fn}> and React sends the form data to the server with a POST. When the form lives in a Server Component, it can submit even before JavaScript has loaded (progressive enhancement).

The most important idea is to treat the action as a public HTTP endpoint. FormData values are string, File or null, and the client can send anything. Every action that changes data should follow the same order: (1) authenticate the user from the session, (2) parse the fields with a schema, (3) authorise this user for this record, (4) save through the data layer, (5) revalidate caches, (6) return state or redirect.

In a Client Component, useActionState(action, initialState) returns [state, formAction, isPending], and the action then receives two arguments: (prevState, formData). Return expected errors, such as a title that is too short, as state and show them next to the form; let unexpected failures, such as the database being down, throw to an error boundary.

What Next.js protects, and what it does not

Server Actions can only be invoked with POST, and Next.js compares the Origin header with the Host header to block calls from other sites. The body size is also capped, by default at 1 MB (serverActions.bodySizeLimit). None of this checks who the caller is or what they may do; that part is your job.

The checkpoints inside one action
  1. Form posts FormData to the action
  2. Who is calling? Check the session
  3. Parse the fields with a schema
  4. May this user change this record?
  5. Save, revalidate, return state

Hiding a button or adding required in the UI never replaces any of these checkpoints.

General pattern

tsx
"use server";
export async function actionName(prev: State, formData: FormData): Promise<State> {
  const user = await requireUser();                         // 1. authenticate
  const parsed = Schema.safeParse(Object.fromEntries(formData)); // 2. validate
  if (!parsed.success) return { error: firstMessage(parsed.error) };
  if (!(await canChange(user, parsed.data))) return { error: "Not allowed" }; // 3.
  await saveThing(parsed.data);                             // 4. mutate
  revalidatePath("/things");                                // 5. refresh caches
  return { ok: true };                                      // 6. report back
}

Authenticate, validate, authorise, mutate, revalidate, report: the order is the same in every action; only the schema and the permission rule change.

Worked example: creating a note for the signed-in user

Validating the input is not enough on its own: a Server Action is a public endpoint, so it must also check who is calling. This action checks the session first, validates with zod, and takes ownerId from the session rather than the form. It uses revalidatePath, which works across Next.js versions (updateTag exists only in Next.js 16), and the form shows errors and pending state with useActionState.

app/notes/actions.ts
// app/notes/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { getCurrentUser } from "@/lib/auth";
import { createNote } from "@/lib/data/notes";

export type FormState = { error?: string; ok?: boolean };

const NoteInput = z.object({
  title: z.string().trim().min(3, "Enter a title with at least 3 characters").max(120),
});

export async function createNoteAction(
  _prev: FormState,
  formData: FormData,
): Promise<FormState> {
  const user = await getCurrentUser();
  if (!user) return { error: "Please sign in first" };

  const parsed = NoteInput.safeParse({ title: formData.get("title") ?? "" });
  if (!parsed.success) return { error: parsed.error.issues[0].message };

  await createNote({ title: parsed.data.title, ownerId: user.id });
  revalidatePath("/notes");
  return { ok: true };
}

// app/notes/new/note-form.tsx
"use client";
import { useActionState } from "react";
import { createNoteAction } from "../actions";

export function NoteForm() {
  const [state, formAction, pending] = useActionState(createNoteAction, {});
  return (
    <form action={formAction}>
      <label htmlFor="title">Title</label>
      <input id="title" name="title" required minLength={3} />
      <button type="submit" disabled={pending}>
        {pending ? "Saving..." : "Save"}
      </button>
      {state.error && <p role="alert">{state.error}</p>}
      {state.ok && <p>Saved.</p>}
    </form>
  );
}

Code breakdown

  1. Authenticate firstif (!user) return { error: "Please sign in first" };

    Whoever submitted the form, nothing happens without a session.

  2. Validate on the serverconst parsed = NoteInput.safeParse({ title: formData.get("title") ?? "" });

    formData.get() may return null, so it becomes an empty string; the schema then trims and enforces 3 to 120 characters, catching requests that bypassed the browser's minLength.

  3. Owner from the sessionawait createNote({ title: parsed.data.title, ownerId: user.id });

    ownerId never comes from a hidden input, so nobody can create notes in someone else's name.

  4. Refresh the listrevalidatePath("/notes");

    After saving, it marks the /notes cache as stale, so the list shows the new note.

  5. State and pending in the formconst [state, formAction, pending] = useActionState(createNoteAction, {});

    state is the last object the action returned, and pending is true while it runs, which disables the button and prevents double submits.

You should see
Submitting "Hi" shows "Enter a title with at least 3 characters" under the form, and a signed-out visitor sees "Please sign in first". A valid title is saved with the signed-in user as owner, Saved. appears, and the /notes list includes the new note.

redirect, try/catch and extra arguments

redirect() works by throwing a special error, so calling it inside try/catch lets the catch swallow it and the redirect never happens. Keep the save inside try, and call revalidate and redirect after the try/catch, at the end. You can pass extra arguments such as a note id with action.bind(null, id), but that id also travels through the client, so it still needs an authorization check.

app/notes/actions.ts
export async function publishNote(noteId: string) {
  const user = await requireUser();
  try {
    await markPublished({ noteId, userId: user.id }); // checks ownership inside
  } catch {
    return { error: "Could not publish. Please try again." };
  }
  revalidatePath("/notes");
  redirect(`/notes/${noteId}`); // outside try/catch: redirect works by throwing
}

// in a Server Component: <form action={publishNote.bind(null, note.id)}>

In real projects

In real projects

For most forms in your own UI, a Server Action is less code than writing an API endpoint by hand. To keep actions safe in production, teams follow one shared pattern.

  • Settings pages: the update-profile action takes the user id from the session, so the form has no id field at all.
  • Admin publish buttons: the action checks the editor role itself and revalidates the blog list tag after publishing.
  • Comment forms: zod checks the length, and a rate limit caps how many posts one user can make per minute.
  • Helpers such as requireUser and requireRole are written once in lib/auth.ts and called on the first line of every action.

Common mistakes

Common Server Action mistakes

Skipping server validation because the browser validates

required, minLength and type="email" can be removed in devtools, and a script can post FormData directly. Keep HTML validation for UX and always run schema validation inside the action.

Leaving update and delete actions without authorization

Even if the page checked the login, the action can be called on its own. Every action must read the session again and check the record's owner or the user's role itself.

Taking ownerId, role or price from FormData

A hidden input is still user input. Derive such values on the server from the session or the database.

Calling redirect inside try/catch

The catch swallows the redirect error, so the user stays on the page and sees an error message. Call redirect outside the try/catch.

Best practices

Best practices

  • Keep actions in a dedicated "use server" file such as actions.ts, so Client Components can import them without mixing in other server code.
  • Share one schema between the form and the action if you like, but only trust the parse that runs on the server.
  • Give every action's returned state one shape, such as { ok, message } or a map of field errors.
  • Never put database error messages or stack traces into the state; log them on the server and show the user a general message.
  • Write one security test per action: calls from a signed-out user and from a non-owner must be refused.

Mini challenge

Mini challenge: a safe updateNoteAction

Write updateNoteAction(prevState, formData) using a fake session and database so it runs without Next.js. It must go through authenticate, validate, not-found, authorise and save, in that order.

  • No session returns { ok: false, message: "Sign in first" }
  • Validate trimmed id, title (3-80) and body (10-2000) with zod, returning the first error message
  • Return "Note not found" for an unknown note and "Not allowed" unless the user is the owner or an editor
  • On success, save and return { ok: true, message: "Saved" }
  • Call it as several different users and print every result
update-note-action.ts
import { z } from "zod";

type User = { id: string; role: "member" | "editor" };
type Note = { id: string; ownerId: string; title: string; body: string };
type State = { ok: boolean; message: string };

// Fake session and database so the action runs outside Next.js.
let session: { user: User } | null = null;
const notes = new Map<string, Note>(/* TODO: one note owned by "u1" */);

const UpdateInput = z.object({
  // TODO: id, title (3-80) and body (10-2000), all trimmed, with messages
});

async function updateNoteAction(_prev: State, formData: FormData): Promise<State> {
  // TODO 1: authenticate
  // TODO 2: validate Object.fromEntries(formData)
  // TODO 3: not found
  // TODO 4: authorize (owner or editor)
  // TODO 5: save and report
}

// TODO: build FormData objects and call the action as different users

Expected: A signed-out call gets Sign in first, a short title gets Title must be 3-80 characters, the owner and the editor get Saved, another member gets Not allowed, an unknown id gets Note not found, and the final title is Polished by editor.

Show hint

new FormData() is a global in Node 22. When validation fails, parsed.error.issues[0].message gives the message you wrote in the schema. Reassign the session variable before each call to simulate different users.

Show solution
update-note-action.ts
import { z } from "zod";

type User = { id: string; role: "member" | "editor" };
type Note = { id: string; ownerId: string; title: string; body: string };
type State = { ok: boolean; message: string };

let session: { user: User } | null = null;
const notes = new Map<string, Note>([
  ["n1", { id: "n1", ownerId: "u1", title: "Draft", body: "First version of the note" }],
]);

const TITLE = "Title must be 3-80 characters";
const BODY = "Body must be 10-2000 characters";
const UpdateInput = z.object({
  id: z.string().trim().min(1, "Missing note id"),
  title: z.string().trim().min(3, TITLE).max(80, TITLE),
  body: z.string().trim().min(10, BODY).max(2000, BODY),
});

async function updateNoteAction(_prev: State, formData: FormData): Promise<State> {
  const user = session?.user;
  if (!user) return { ok: false, message: "Sign in first" };

  const parsed = UpdateInput.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { ok: false, message: parsed.error.issues[0].message };

  const note = notes.get(parsed.data.id);
  if (!note) return { ok: false, message: "Note not found" };
  if (note.ownerId !== user.id && user.role !== "editor") {
    return { ok: false, message: "Not allowed" };
  }

  notes.set(note.id, { ...note, title: parsed.data.title, body: parsed.data.body });
  return { ok: true, message: "Saved" };
}

function form(id: string, title: string, body = "A long enough body text") {
  const data = new FormData();
  data.set("id", id);
  data.set("title", title);
  data.set("body", body);
  return data;
}

const initial: State = { ok: false, message: "" };
const owner: User = { id: "u1", role: "member" };
const other: User = { id: "u2", role: "member" };
const editor: User = { id: "u3", role: "editor" };

const cases: [string, User | null, FormData][] = [
  ["signed out", null, form("n1", "New title")],
  ["owner, short title", owner, form("n1", "Hi")],
  ["owner, valid", owner, form("n1", "  Owner edit  ")],
  ["other member", other, form("n1", "Hijacked title")],
  ["editor, valid", editor, form("n1", "Polished by editor")],
  ["missing note", owner, form("n404", "Valid title")],
];

async function main() {
  for (const [label, user, data] of cases) {
    session = user ? { user } : null;
    const state = await updateNoteAction(initial, data);
    console.log(`${label.padEnd(19)} -> ${state.ok} ${state.message}`);
  }
  console.log("final title:", notes.get("n1")?.title);
}

main();

Quick quiz 1 / 3

The title input already has required minLength={3}. Does the Server Action still need to check the title?

Quick quiz 2 / 3

In a create-note action, where should ownerId come from?

Quick quiz 3 / 3

try { await save(); redirect("/notes"); } catch { return { error: "Failed" }; } — what happens when save succeeds?

What to remember

  • A Server Action is an async "use server" function; treat it as a public endpoint the browser calls with POST.
  • Follow authenticate, validate, authorise, save, revalidate, report in every action.
  • Take values such as ownerId from the session, never from FormData.
  • useActionState provides error state and pending, and redirect must be called outside try/catch.

Next.js — Mutating Data — Next.js

Next.js — Mutating Data — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Server Actions, Forms, and Validation | Thuta Learning