Server Actions vs API routes in Next.js: which to use
IntermediateNext.js interview questionBy UIRound, updated 3 December 2026
Short answer
A Server Action is an async function marked 'use server' that your own React UI calls like a function, usually from a form, to change data. It can return fresh UI in the same response. A Route Handler, a route.ts file and the App Router's version of API routes, is a public HTTP endpoint any client can call. Use Server Actions for your app's own mutations, and Route Handlers for webhooks, other clients and data read over HTTP.
The difference in one table
| Server Action | Route Handler (app/**/route.ts) |
|
|---|---|---|
| Defined with | 'use server' on a function or file |
Exported GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS functions |
| HTTP method | POST only |
Any of those methods |
| Called by | Your React components, as a function | Anything that speaks HTTP |
| Address | An encrypted action ID that can change between deploys | A fixed URL you choose |
| Input | Arguments, or FormData from a form |
A Web Request |
| Output | The return value, plus a new RSC Payload when it revalidates or redirects | Any Response: JSON, a file, a stream, a redirect |
| Caching | Not cached | Not cached by default; GET can opt in |
| Several calls at once | Sent one at a time per client | Run in parallel |
| Works before JavaScript loads | Yes, for forms in Server Components | Only as a plain HTML form action URL |
| Built-in CSRF check | Yes, Origin compared to Host |
None documented, add your own |
The Pages Router equivalent of a Route Handler is an API route in pages/api. The docs note you do not need both in the same app.
The same mutation both ways
A Server Action:
// app/posts/actions.ts
"use server";
import { revalidatePath } from "next/cache";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
export async function createPost(formData: FormData) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
await db.post.create({
data: { title: String(formData.get("title")), authorId: session.user.id },
});
revalidatePath("/posts");
}// app/posts/new/page.tsx
import { createPost } from "../actions";
export default function NewPost() {
return (
<form action={createPost}>
<input name="title" required />
<button>Publish</button>
</form>
);
}The same as a Route Handler:
// app/api/posts/route.ts
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
export async function POST(request: Request) {
const session = await auth();
if (!session?.user) return Response.json({ error: "Unauthorized" }, { status: 401 });
const { title } = await request.json();
const post = await db.post.create({ data: { title: String(title), authorId: session.user.id } });
return Response.json(post, { status: 201 });
}With the Route Handler, the client also needs a fetch call, its own pending and error state, and a way to refresh the list afterwards. With the Server Action, the form works before hydration, and because the action calls revalidatePath, Next.js runs the mutation, invalidates the cache and sends the re-rendered page in one round trip. No follow-up fetch is needed.
When a Server Action is the right choice
- Forms and mutations from your own pages: create, update, delete, toggle, sign out.
- When the page should update right after the write:
revalidatePath,updateTag,refresh, a cookie change orredirectinside the action make the response carry the new UI. - Progressive enhancement: a
<form action={serverAction}>in a Server Component submits even if JavaScript has not loaded. - With React 19 hooks:
useActionStatefor returned errors and pending state,useOptimisticfor instant feedback.
When a Route Handler is the right choice
- Webhooks and callback URLs. Stripe, GitHub or an OAuth provider needs a fixed URL that accepts its request format. The backend-for-frontend guide uses Route Handlers for exactly this.
- Other clients. A mobile app, a browser extension or a partner calling your API needs a stable URL and contract. Action IDs change with deployments (Next.js rotates them at most every 14 days even without code changes), so they are not an API.
- Data the browser fetches over HTTP. Polling, infinite scroll with TanStack Query or SWR, or anything read in parallel. Server Actions are dispatched one at a time per client, so using them for reads makes requests queue behind each other.
- Non-HTML responses. CSV exports, images, RSS, streamed text.
- Static exports. With
output: 'export', onlyGETRoute Handlers withdynamic = 'force-static'work, and there is no server to run actions.
The caveat for Server Components
Do not fetch your own Route Handlers from Server Components. The docs explain that this adds an extra HTTP round trip at request time, and that at build time there is no server listening, so prerendering fails. Call the data function directly instead. Route Handlers are for clients outside the server render.
Security is the same job in both
A Server Action has no URL you chose, but it is not private. The docs warn that Server Functions are reachable by direct POST requests, not just through your UI. Next.js adds protections: an Origin check against Host for CSRF, a 1 MB default body limit (serverActions.bodySizeLimit), encrypted action IDs and removal of unused actions from client bundles. None of that replaces your own checks. In both a Server Action and a Route Handler: authenticate, authorize the specific record, validate the input and return only what the UI needs. The docs describe the Origin check for Server Actions only, so give cookie-authenticated POST Route Handlers their own Origin or token check; see Protect a web app from CSRF.
To practise, build a sign-up form with useActionState on top of an action, then design the HTTP side in a backend-for-frontend for a page that calls nine services. The basics of actions, including pending states and redirects, are in What are Server Actions in Next.js?.
Common follow-up questions
Can I use a Server Action to fetch data?
You can, but the docs advise against it. Actions are queued one at a time per client, so reads become sequential. Fetch in Server Components, or use a Route Handler for client-side reads.
Can a mobile app call my Server Actions?
Not reliably. Actions are addressed by build-generated IDs that change across deployments, and their wire format belongs to React. Expose a Route Handler with a documented contract instead.
Do Server Actions replace API routes?
For mutations triggered by your own Next.js UI, mostly yes. For webhooks, public APIs, non-HTML responses and parallel client reads, no. Most real apps have both.
Why does a Route Handler return 405?
The file does not export a function for that HTTP method. Next.js answers unsupported methods with 405 Method Not Allowed.
Can I have route.ts and page.tsx in the same folder?
No. A route.js and a page.js cannot sit at the same route segment, because each takes over every HTTP method for that path. Put the handler under a different segment, such as app/api/....
Mistakes to avoid
Skipping authentication in a Server Action because "it has no URL"
Exposing Server Actions to third parties or mobile apps as if they were an API
Fetching your own Route Handler from a Server Component instead of calling the data layer directly
Using Server Actions for parallel or polled reads and getting a queue
Forgetting a CSRF defence on cookie-authenticated Route Handlers
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Build a sign-up form with
useActionState: field errors, kept values, pending and successMedium35 min - Decide the server/client component boundary for a Next.js product pageHard45 min
- Protect a web app from CSRF with signed tokens, Origin checks and SameSite cookiesMedium40 min
- Design a backend-for-frontend (BFF) for a page that calls nine servicesHard45 min
- Fix a Next.js page that shows stale data, layer by layer through its cachesHard45 min
- Diagnose a failing CORS preflight and write the server's CORS handlerMedium35 min