Server Actions
Server Actions are async functions marked with "use server" that a form (or event handler) can call directly on the server. They replace the client fetch + API route + manual refresh boilerplate and work even before JavaScript loads.
65.1 Problem: the old way
- A Client Component just to save one todo: preventDefault, build FormData, POST to an API route with fetch, then router.refresh().
- You also need a separate API route file.
- Biggest problem: the form does not work at all until JavaScript loads.
React (TSX)
"use client";import type { FormEvent } from "react";import { useRouter } from "next/navigation";export function NewTodo() { const router = useRouter(); async function save(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const body = new FormData(e.currentTarget); await fetch("/api/todos", { method: "POST", body }); router.refresh(); } return ( <form onSubmit={save}><input name="title" /></form> );}- Step 1
1.Client: preventDefault + new FormData
- Step 2
2.fetch POST /api/todos
- Step 3
3.Separate API route file saves to DB
- Step 4
4.router.refresh() to update the list by hand
Same boilerplate repeats for every form
65.2 Fix: our first Server Action
- "use server" at the top of actions.ts: every exported function runs only on the server; the browser gets only a reference.
- addTodo is a normal async function that takes FormData, reads title and saves it to the DB.
- revalidatePath("/todos") clears the old cache of the todos page (previous video).
TypeScript
// app/actions.ts"use server"; import { revalidatePath } from "next/cache";import { createTodo } from "@/lib/db"; export async function addTodo(formData: FormData) { const title = String(formData.get("title")); await createTodo(title); revalidatePath("/todos");}65.3 Form action: pass the Server Action
- The page is a Server Component; pass addTodo straight into the form's action prop.
- No fetch, no API route, no preventDefault.
- It is a normal HTML form submit, so it works even before JS loads (progressive enhancement).
React (TSX)
// app/todos/page.tsx (Server Component)import { addTodo } from "../actions";import { getTodos } from "@/lib/db"; export default async function TodosPage() { const todos = await getTodos(); return ( <form action={addTodo}> {todos.map((t) => <p key={t.id}>{t.title}</p>)} <input name="title" /> <button>Add</button> </form> );}Output
Learn Next.js[button] Add (type "Buy milk", press Add)Learn Next.jsBuy milk[button] Add- Step 1
1.Form submit: browser sends POST with action ID + form data
- Step 2
2.Next.js finds addTodo from that ID and runs it on the server
- Step 3
3.revalidatePath makes the page render fresh
- Step 4
4.Updated UI comes back in the same response, no separate refresh
65.4 Validation with Zod
- Users can send an empty or two-letter title, so validate on the server.
- Title schema: trim and at least 3 letters.
- With useActionState the signature becomes (prev, formData): prev is the previous state.
- If safeParse fails, return the first error message; otherwise save and return "Todo added".
TypeScript
"use server";import { revalidatePath } from "next/cache";import { z } from "zod";import { createTodo } from "@/lib/db"; const Title = z.string().trim().min(3, "Min 3 letters"); export async function addTodo( prev: string, data: FormData) { const res = Title.safeParse(data.get("title")); if (!res.success) return res.error.issues[0].message; await createTodo(res.data); revalidatePath("/todos"); return "Todo added";}65.5 useActionState: message + pending
- A small Client Component calls useActionState(addTodo, "") and gets [msg, formAction, pending].
- While pending is true the button is disabled, so there is no double submit.
- "Hi" shows Min 3 letters; "Buy milk" updates the list and shows Todo added.
React (TSX)
"use client";import { useActionState } from "react";import { addTodo } from "../actions"; export function TodoForm() { const [msg, formAction, pending] = useActionState(addTodo, ""); return ( <form action={formAction}> <input name="title" /> <button disabled={pending}>Add</button> <p>{msg}</p> </form> );}Output
Learn Next.js[button] Add (type "Hi", press Add)Learn Next.js[button] AddMin 3 letters (type "Buy milk", press Add)Learn Next.jsBuy milk[button] AddTodo added65.6 Checkpoint: will the list update without revalidatePath?
- The todo IS saved in the database, but the list does not update.
- The todos page was made static at build and nobody told Next.js the data changed, so even a reload shows the old list.
TypeScript
"use server"; import { createTodo } from "@/lib/db"; export async function addTodo(formData: FormData) { const title = String(formData.get("title")); await createTodo(title);}Output
Learn Next.js[button] Add (after Add, even after reload)Learn Next.js[button] Add65.7 Comparison: API route + fetch vs Server Action
| Point | API route + fetch | Server Action |
|---|---|---|
| Files | Client component + API route | One "use server" function |
| Wiring | preventDefault, FormData, fetch by hand | <form action={addTodo}> |
| Works before JS loads | No | Yes (progressive enhancement) |
| Refreshing UI | router.refresh() by hand | revalidatePath, same response |
| Security | Endpoint is public | Also a public POST endpoint: still check auth |
65.8 Common mistakes
- Most dangerous: deleteTodo with no auth check because "only admins see the button". Every Server Action is a public POST endpoint anyone can call.
- Fix: check the user inside the action and throw if not an admin, then delete.
- Forgetting revalidatePath / redirect after a mutation: data saved, page stale.
- Myth: actions only work with forms. You can call them from onClick too, inside startTransition for a pending state.
- Myth: actions are the best way to read data. Read in a Server Component; actions are for mutations and the client runs one action at a time.
TypeScript
// Wrong: anyone can call it and delete"use server";import { revalidatePath } from "next/cache";import { removeTodo } from "@/lib/db"; export async function deleteTodo(id: number) { await removeTodo(id); revalidatePath("/todos");}TypeScript
// Right: auth check inside the action"use server";import { revalidatePath } from "next/cache";import { removeTodo } from "@/lib/db";import { getUser } from "@/lib/auth"; export async function deleteTodo(id: number) { const user = await getUser(); if (user?.role !== "admin") { throw new Error("Unauthorized"); } await removeTodo(id); revalidatePath("/todos");}65.9 Best practices
- Validate every action's input with Zod; never trust client data.
- Check auth and permissions inside every action.
- After changing data, call revalidatePath or redirect.
- Return expected errors in state instead of throwing; disable the button while pending.
65.10 Interview tips
- Server Actions are async functions marked "use server" that always run on the server.
- Called from a form's action prop or an event handler; under the hood Next.js sends a POST request.
- They support progressive enhancement and, with revalidatePath, return the updated UI in one round trip.
- Every action is a public endpoint, so validation and the auth check must happen inside it.