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}>orawait 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()andredirect(). - 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.
GETcan be prerendered or cached.- You handle request parsing, validation and client-side fetching yourself.
Choosing
| Need | Use |
|---|---|
| Form submit, button mutation in your app | Server Action |
| Public or versioned API, mobile clients | Route Handler |
| Webhook (Stripe, CMS) | Route Handler |
| File download, RSS, streaming response | Route Handler |
| Read data for a page | Server 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 form2// app/notes/actions.ts3"use server";4import { updateTag } from "next/cache";5import { verifySession } from "@/lib/dal";6import { db } from "@/lib/db";78export 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>1415// Route Handler: explicit HTTP API for other clients16// app/api/notes/route.ts17// 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.