Next.jsMedium

What are Server Actions and how do they differ from API routes?

Server Actions (Server Functions) are "use server" functions you call directly from React, mainly for mutations from your own UI. Route Handlers and API routes are explicit HTTP endpoints you design and call with fetch. Actions trade HTTP control for tight React and caching integration.

Server Actions

  • Called like a function: <form action={createPost}> or await createPost(data) in a transition.
  • Always POST, with an encrypted, build-specific ID; no stable URL.
  • Progressive enhancement: forms work before JavaScript loads.
  • Return data and updated UI in one round-trip; integrate with updateTag, revalidateTag, refresh() and redirect().
  • Pair with useActionState, useFormStatus, useOptimistic.
  • Type-safe end to end with TypeScript.
  • Executed sequentially per client, so they are a poor fit for parallel reads.

Route Handlers / API routes

  • Explicit URL and HTTP method (GET /api/posts).
  • Full control of status codes, headers, streaming, content types and CORS.
  • Callable by anyone: mobile apps, webhooks, third parties, other services.
  • GET can be prerendered or cached.
  • You handle request parsing, validation and client-side fetching yourself.

Choosing

NeedUse
Form submit, button mutation in your appServer Action
Public or versioned API, mobile clientsRoute Handler
Webhook (Stripe, CMS)Route Handler
File download, RSS, streaming responseRoute Handler
Read data for a pageServer Component

Shared rule

Both are public network entry points. Authenticate, authorize and validate in each.

Code example

tsx
1// Server Action: called directly from the form
2// app/notes/actions.ts
3"use server";
4import { updateTag } from "next/cache";
5import { verifySession } from "@/lib/dal";
6import { db } from "@/lib/db";
7
8export async function addNote(formData: FormData) {
9 const { userId } = await verifySession();
10 await db.note.create({ data: { userId, text: String(formData.get("text")) } });
11 updateTag(`notes:${userId}`);
12}
13// <form action={addNote}><input name="text" /><button>Add</button></form>
14
15// Route Handler: explicit HTTP API for other clients
16// app/api/notes/route.ts
17// export async function POST(req: Request) {
18// const user = await authenticateBearer(req.headers.get("authorization"));
19// if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
20// const { text } = await req.json();
21// const note = await db.note.create({ data: { userId: user.id, text } });
22// return Response.json(note, { status: 201, headers: { Location: `/api/notes/${note.id}` } });
23// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app