Guides · Next.js

Server Actions vs. API routes

The Next.js App Router gives you two ways to run code on the server when something happens in the browser: Server Actions and Route Handlers. They overlap just enough to be confusing. Here's what each one is, when to use which, and the mistakes that bite with both.

10 min read

  • next.js
  • react
  • server actions
  • api

The short answer

  • Your own UI changes data (a form, a button, a toggle): use a Server Action.
  • Something other than your UI calls you (a webhook, a mobile app, another service, a cron job): use a Route Handler.
  • A Server Component needs data: use neither. Read it directly.

The rest of this post is the why, and the cases in between.

What each one is

Server Actions

A Server Action is an async function marked with "use server". You call it from your components as if it were a normal function, and Next.js turns the call into a request to the server for you.

ts
"use server";

import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";

export async function deleteTodo(id: string) {
await db.todo.delete({ where: { id } });
revalidatePath("/todos");
}

There's no URL to choose, no fetch to write and no JSON to parse. Arguments and return values are sent for you, and the types flow from server to client because it's the same function.

Route Handlers

A Route Handler is a route.ts file in the app folder that exports functions named after HTTP methods. It takes a standard Web Request and returns a Response.

ts
// app/api/posts/route.ts
import { db } from "@/lib/db";

export async function GET() {
const posts = await db.post.findMany({ where: { published: true } });
return Response.json(posts);
}

It has a real, stable URL (/api/posts), supports every HTTP method, and anyone who can make an HTTP request can call it. It's the App Router's version of the old pages/api routes.

Side by side

Server ActionRoute Handler
Called byYour own React componentsAnything that speaks HTTP
URLNone you control; Next.js generates an IDStable, one you choose
HTTP methodsPOST onlyGET, POST, PUT, PATCH, DELETE, …
Works without JavaScriptYes, when used as a form's actionOnly through a plain HTML form post
Types end to endYes, it's one functionNo, you type the JSON yourself
Updates the page afterBuilt in: revalidatePath, redirectYou refetch on the client
Response formatSerializable valuesAnything: JSON, files, streams, redirects
Good for reading dataNoYes

When to use a Server Action

Forms

This is what Server Actions were made for. Pass one to a form's action, and the form posts to the server even before your JavaScript has loaded:

tsx
// app/todos/page.tsx
import { createTodo } from "./actions";

export default function TodosPage() {
return (
<form action={createTodo}>
<input name="title" required />
<button type="submit">Add</button>
</form>
);
}

The action receives the form's FormData. To show errors and a pending state, wrap it in React's useActionState in a Client Component:

ts
// app/todos/actions.ts
"use server";

import { z } from "zod";
import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

const schema = z.object({ title: z.string().trim().min(1).max(200) });

export type FormState = { error: string | null };

export async function createTodo(_prev: FormState, formData: FormData): Promise<FormState> {
const session = await auth();
if (!session) return { error: "Please sign in." };

const parsed = schema.safeParse({ title: formData.get("title") });
if (!parsed.success) return { error: "Title must be 1–200 characters." };

await db.todo.create({ data: { title: parsed.data.title, userId: session.user.id } });
revalidatePath("/todos");
return { error: null };
}
tsx
// app/todos/todo-form.tsx
"use client";

import { useActionState } from "react";
import { createTodo, type FormState } from "./actions";

const initialState: FormState = { error: null };

export function TodoForm() {
const [state, formAction, pending] = useActionState(createTodo, initialState);

return (
<form action={formAction}>
<input name="title" required />
<button type="submit" disabled={pending}>
{pending ? "Saving…" : "Add"}
</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}

With useActionState, the action takes the previous state as its first argument, and whatever it returns becomes the new state.

Buttons and other events

Actions don't need a form. Call one from an event handler inside a transition, so React can track the pending state:

tsx
"use client";

import { useTransition } from "react";
import { deleteTodo } from "./actions";

export function DeleteButton({ id }: { id: string }) {
const [pending, startTransition] = useTransition();

return (
<button
disabled={pending}
onClick={() => startTransition(() => deleteTodo(id))}
>
Delete
</button>
);
}

For changes that should show up before the server confirms them, like a like count or a checked box, pair the action with useOptimistic.

Changes that should update the page

After a mutation, an action can tell Next.js what's out of date. revalidatePath("/todos") refreshes that page's data, and redirect("/todos/123") sends the user somewhere new, all in the same round trip. With a Route Handler, you'd return JSON and then refetch or navigate on the client yourself.

When to use a Route Handler

Webhooks

Stripe, GitHub, a payment gateway or a CMS needs a fixed URL to POST to, and it sends its own payload, not your form. That's a Route Handler. Read the raw body, check the signature, then act:

ts
// app/api/webhooks/payments/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";

export async function POST(request: Request) {
const body = await request.text();
const signature = request.headers.get("x-signature") ?? "";
const expected = createHmac("sha256", process.env.WEBHOOK_SECRET!)
.update(body)
.digest("hex");

const valid =
signature.length === expected.length &&
timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!valid) return new Response("Invalid signature", { status: 401 });

const event = JSON.parse(body);
await handlePaymentEvent(event);

return Response.json({ received: true });
}

Check the provider's docs for its exact header and signing scheme. Most have an SDK helper that does this for you.

A public API or a mobile app

If an iOS app, a partner, or a script will call your backend, it needs URLs that don't change between deploys and normal HTTP semantics. A Server Action's ID is generated at build time and isn't meant to be called from outside your app.

Reading data on the client

Server Actions run one at a time and always use POST, so they're a poor fit for fetching. When a Client Component needs to load data (search as you type, infinite scroll, polling), give it a GET Route Handler and call it with fetch, SWR or TanStack Query:

ts
// app/api/search/route.ts
import { db } from "@/lib/db";

export async function GET(request: Request) {
const q = new URL(request.url).searchParams.get("q") ?? "";
const results = await db.post.findMany({
where: { title: { contains: q, mode: "insensitive" } },
take: 10,
});
return Response.json(results);
}

Files, streams and other responses

Downloading a CSV, serving a generated image, streaming a long response, redirecting an OAuth callback, or answering with a specific status code and headers: these all need full control of the Response, which only a Route Handler gives you.

Dynamic segments

Route Handlers use the same folder conventions as pages. In current Next.js, params is a promise:

ts
// app/api/posts/[id]/route.ts
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params;
const post = await db.post.findUnique({ where: { id } });
if (!post) return new Response("Not found", { status: 404 });
return Response.json(post);
}

When to use neither

A Server Component already runs on the server. It can read your database directly:

tsx
// app/todos/page.tsx
import { db } from "@/lib/db";

export default async function TodosPage() {
const todos = await db.todo.findMany();
return <TodoList todos={todos} />;
}

A common mistake is to have the page fetch("/api/todos") from its own Route Handler instead. That adds an HTTP round trip from your server to itself, loses the types, and breaks at build time, when there's no server running for the page to call. If a Client Component further down needs the data, pass it down as props.

Mistakes to avoid

Treating an action as private

A Server Action looks like a function, but it's a public endpoint. Anyone can find its ID in your JavaScript and POST to it with whatever arguments they like. So, in every action:

  • Check who's calling. Don't rely on the page being behind a login; the action can be called without ever loading the page.
  • Check they're allowed to touch that record. deleteTodo(id) must confirm the todo belongs to the user.
  • Validate the input. TypeScript types disappear at runtime. Parse with a schema library like Zod.

Route Handlers need exactly the same checks; the difference is that nobody forgets a Route Handler is public.

Keep the database and auth logic in a server-only module (add import "server-only" at the top), and have both your actions and your Route Handlers call it. Then the checks live in one place, and a module that holds secrets can never be bundled into client code by accident.

Returning things that can't be sent

An action's return value travels to the browser, so it must be serializable: plain objects, arrays, strings, numbers, dates, FormData. No class instances, no functions, and nothing you wouldn't want the user to see. Return { error: "…" } for problems the user can fix, and let unexpected errors throw to the nearest error.tsx.

Calling redirect inside try

redirect() works by throwing a special error. Inside a try block, your catch swallows it and the redirect never happens. Call it after the try:

ts
let id: string;
try {
id = await createPost(data);
} catch {
return { error: "Could not save the post." };
}
redirect(`/posts/${id}`);

Large uploads through an action

Action request bodies are limited to 1 MB by default. You can raise it with serverActions.bodySizeLimit under experimental in next.config, but for real file uploads it's usually better to upload straight to storage (S3, Supabase Storage, Vercel Blob) with a signed URL, and pass only the resulting path to your action.

Using actions to fetch

Because actions run one after another, several "get" actions fired at once queue up instead of running in parallel. Read data in Server Components, or through GET Route Handlers on the client.

How actions are protected from CSRF

Server Actions only accept POST, and Next.js compares the request's Origin header with its Host, rejecting calls from other sites. If your app sits behind a proxy or is called from another domain you trust, list it in serverActions.allowedOrigins. Route Handlers get no such check for free; if one changes data based on a cookie, add your own origin or token check.

Decision checklist

  1. Does something other than your own React UI call it? → Route Handler.
  2. Does it need GET, a fixed URL, custom headers or status codes, a file or a stream? → Route Handler.
  3. Is it a Server Component reading data? → Neither: query directly.
  4. Is it your UI changing data, from a form or an event? → Server Action.
  5. Do you need both? → Put the logic in a server-only module and expose it twice: an action for your UI, a Route Handler for everyone else.

The two aren't rivals. Server Actions are the shortest path from your UI to a change on the server, with types and page updates built in. Route Handlers are your app's public door to the rest of the internet. Most apps end up with both, each doing the job it's good at.