Skip to content
Visual explainer 4h to learn 5 steps

Server actions & forms

Handle form submissions and mutations with server actions and validation.

By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.

Topic 23 of 36

In short

Server actions are async functions marked 'use server' that run on the server but can be called from forms and client code. They handle mutations without writing a separate API endpoint.

Explained simply

Most apps need to change data: add a todo, save a profile, delete a comment. Traditionally you would write an API endpoint and then call it with fetch from the browser. Server actions skip that extra layer.

A server action is an async function marked with "use server". It always runs on the server, so it can talk to the database. But you can pass it to a form's action, or call it from a button, as if it were a normal function.

Behind the scenes, Next.js turns each action into a POST request. That means anyone could call it with their own data, not just your form. So every action must check who the user is and validate the input, usually with a library like Zod.

After saving, you tell Next.js which pages now show old data, with revalidatePath or revalidateTag. The form can show a pending state while it waits and an error message if something is wrong.

Press Play on a diagram to walk through it one step at a time.

SequenceSubmitting a form to a server action
Browser form
Server action
Database
  1. 1POST FormData
    Browser form to Server action: POST FormData
  2. 2Check auth, validate with Zod
    Server action to Server action: Check auth, validate with Zod
  3. 3Insert row
    Server action to Database: Insert row
  4. 4Saved
    Database to Server action: Saved
  5. 5revalidatePath('/todos')
    Server action to Server action: revalidatePath('/todos')
  6. 6Return state, fresh UI
    Server action to Browser form: Return state, fresh UI
CompareServer action vs route handler for a mutation
Server action
  • Called from your own forms and components
  • No URL or fetch code to write
  • Typed arguments and return value
  • Refreshes the page in one round trip
Route handler
  • Public URL like /api/todos
  • Any client: mobile apps, webhooks, scripts
  • You choose method, headers, status codes
  • Better for third-party integrations

In depth

How a server action call really works

When you mark a function with "use server", the build replaces it in client code with a reference: an encrypted id. Calling it sends a POST request to the current page with that id and the arguments, serialized like props. On the server, Next.js finds the function, runs it, and returns the result, along with an updated page payload if you revalidated something, all in one round trip.

You can define actions in a separate file with "use server" at the top, which is the cleanest choice and the only one usable from client components, or inline inside a server component function. Inline actions can close over variables; Next.js encrypts those values so the client cannot read them, but do not rely on that for secrets. Actions run one at a time per client, so they are made for mutations, not for fetching data.

SequenceOne action call, one round trip
Client component
Next.js server
Database
  1. 1POST with action id + FormData
    Client component to Next.js server: POST with action id + FormData
  2. 2auth check, Zod validation
    Next.js server to Next.js server: auth check, Zod validation
  3. 3INSERT ... for this user
    Next.js server to Database: INSERT ... for this user
  4. 4revalidatePath("/todos")
    Next.js server to Next.js server: revalidatePath("/todos")
  5. 5return value + fresh page payload
    Next.js server to Client component: return value + fresh page payload

Validating input with Zod

FormData values are strings or files, and anyone can send anything. Define a schema that describes valid input and parse it at the top of the action. z.coerce.number() turns "3" into 3, .min() and .max() limit lengths, and z.email() checks the format in Zod 4. Use safeParse, which returns success or error instead of throwing, so you can send field errors back to the form.

In Zod 4, z.flattenError(result.error).fieldErrors gives an object like { title: ["Too short"] }, which maps straight onto messages under each input. Return the user's previous values too, so a failed submit does not wipe the form. Never trust hidden inputs either: a userId in a hidden field can be edited in DevTools, so read the user from the session.

  • safeParse returns { success, data } or { success, error }
  • z.coerce.number() for numeric fields
  • z.flattenError(error).fieldErrors for per-field messages
  • Take the userId from the session, never from the form

Pending, errors and optimistic updates

Pass the action to useActionState in a client component. The action then receives the previous state as its first argument and returns the next one, for example { errors } or { ok: true }. The hook gives you that state, the formAction for the form, and isPending for disabling the button. useFormStatus works for a submit button deep inside the form.

For instant feedback, useOptimistic shows the expected result before the server answers, such as adding the todo to the list at once. When the action finishes and the page revalidates, the real data replaces the optimistic version; if it failed, the optimistic item disappears. Forms that pass an action straight to the action prop also work before JavaScript has loaded, which is called progressive enhancement.

After the mutation: revalidate and redirect

Changing the database does not change cached pages. Call revalidatePath("/todos") for one route or revalidateTag("todos") for all data with that tag. Because the response from an action includes the refreshed payload, the user sees the new data without a second request.

To send the user elsewhere, such as from a create form to the new item, call redirect("/todos/" + id) from next/navigation. redirect works by throwing a special error, so call it after your try/catch block, not inside it, or your catch will swallow it. Server actions have a default body size limit of 1 MB, which you can raise with serverActions.bodySizeLimit in next.config if you accept file uploads.

FlowA safe server action, top to bottom
  1. 1
    Authenticate

    Read the session; reject if missing

  2. 2
    Validate

    Zod safeParse on FormData

  3. 3
    Authorize

    Does this user own the record?

  4. 4
    Mutate

    Write to the database

  5. 5
    Revalidate

    revalidatePath or revalidateTag

  6. 6
    Return or redirect

    State for the form, or redirect()

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Write a server action~50m
  2. 2
    Submit a form to a server action~50m
  3. 3
    Validate input with Zod~50m
  4. 4
    Show pending and error states~50m
  5. 5
    Revalidate data after a mutation~50m

Key points

  • A server action is a public endpoint, so always check auth and validate input.
  • Forms can call actions directly via the action prop, even before JavaScript loads.
  • useActionState gives you the returned state and a pending flag.
  • Call revalidatePath or revalidateTag after a mutation so pages show fresh data.

Key terms

Tap a card to flip it. 0/5 known

Examples

tsx
// app/todos/actions.ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';

const Todo = z.object({ title: z.string().min(1).max(100) });

export async function addTodo(prev: { error?: string }, formData: FormData) {
  const parsed = Todo.safeParse({ title: formData.get('title') });
  if (!parsed.success) return { error: 'Title is required' };
  await db.todo.create({ data: parsed.data });
  revalidatePath('/todos');
  return {};
}

Validate, mutate, revalidate, return state for the form.

A validated create form with field errors

Step 1: define the schema and parse FormData with safeParse. Step 2: on failure, return field errors from z.flattenError. Step 3: on success, save the row for the signed-in user and revalidate. Step 4: in the client form, useActionState shows errors under each field and disables the button while pending.

ts
// app/todos/actions.ts
"use server";
import { z } from "zod";
import { revalidatePath } from "next/cache";
import { getSession } from "@/lib/auth";
import { db } from "@/lib/db";

const Todo = z.object({ title: z.string().trim().min(1, "Required").max(100), due: z.coerce.date().optional() });
export type FormState = { errors?: Record<string, string[] | undefined>; ok?: boolean };

export async function createTodo(_prev: FormState, formData: FormData): Promise<FormState> {
  const session = await getSession();
  if (!session) return { errors: { title: ["Please sign in"] } };
  const parsed = Todo.safeParse({ title: formData.get("title"), due: formData.get("due") || undefined });
  if (!parsed.success) return { errors: z.flattenError(parsed.error).fieldErrors };
  await db.todo.create({ data: { ...parsed.data, userId: session.user.id } });
  revalidatePath("/todos");
  return { ok: true };
}

An instant-feeling like button with useOptimistic

Step 1: the server action likePost increments the count and revalidates. Step 2: in the client button, useOptimistic starts from the real count. Step 3: on click, inside startTransition, add one optimistically and call the action. The number changes at once; when the server answers, the real count takes over.

tsx
"use client";
import { useOptimistic, startTransition } from "react";
import { likePost } from "./actions";

export function LikeButton({ postId, likes }: { postId: string; likes: number }) {
  const [optimistic, addLike] = useOptimistic(likes, (current: number) => current + 1);
  return (
    <button onClick={() => startTransition(async () => {
      addLike(null);
      await likePost(postId);
    })}>
      Like ({optimistic})
    </button>
  );
}

Quick reference

  • "use server" at the top of a file makes every export a server action
  • Every action is a public POST endpoint: authenticate and validate inside it
  • Read the user id from the session, never from FormData or hidden inputs
  • Zod: Schema.safeParse(data); field errors via z.flattenError(error).fieldErrors
  • useActionState gives [state, formAction, isPending] for a form
  • Call revalidatePath or revalidateTag after writes so pages show fresh data
  • redirect() throws on purpose: call it outside try/catch
  • Default body limit is 1 MB; raise serverActions.bodySizeLimit for uploads

Common mistakes

  • Trusting form data without validation because the form has required fields.
  • Forgetting to revalidate, so the page shows stale data after saving.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your form has a hidden userId input. Why is it wrong to use it in the action?

Question 2

2You call redirect("/done") inside a try block, and the catch logs "Unexpected error". Why?

Question 3

3After saving a new todo, the list page still shows the old list. What is missing?

Question 4

4Which React hook shows the expected result before the server action finishes?

Question 5

5When is a route handler a better choice than a server action?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a server action deleteNote(id: string) that deletes a note owned by the signed-in user and revalidates /notes.

  2. Exercise 2medium

    Write a Zod schema for a signup form: email (valid), password (12 to 72 chars), and age (number, at least 13, sent as a string from the form).

  3. Exercise 3hard

    Build a client form for createTodo (from the example) that shows field errors under the input, keeps the button disabled while saving, and clears the input after success.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are Next.js server actions secure?
They run on the server and Next.js checks the request origin, but each action is still a public endpoint. You must authenticate, validate and authorize inside every action.
Can I use server actions to fetch data?
You can, but it is not what they are for: actions are POST requests that run one at a time. Fetch data in server components or route handlers instead.
Do server actions work without JavaScript?
Yes, when a form passes the action to its action prop. The form submits as a normal POST, and JavaScript adds pending states and no-reload updates once it loads.

Go deeper

ShareXLinkedInWhatsApp