Skip to content
All articles
7 min read

Next.js Server Actions vs Route Handlers: When to Use Each

Server Actions and Route Handlers both run code on the server in Next.js, but they solve different problems. A practical guide to picking the right one, with real production code.

Gusti Randa

Flutter & Full-Stack Developer

The short answer

If a user clicks a button or submits a form in your app, reach for a Server Action. If something outside your app needs to call your server — a webhook, a mobile client, a third-party service — reach for a Route Handler. That one sentence covers most real decisions. The rest of this post is about the cases where it doesn't.

Both run on the server. Both let you touch your database directly. But they are designed for different callers, and picking the wrong one creates work you will feel for months: duplicated validation, awkward error handling, or an endpoint that exists only because a form needed somewhere to post to.

What each one actually is

A Server Action is a function marked with 'use server' that a Client Component can call directly, as if it were a local function. Next.js handles the network round trip for you — no fetch, no URL, no manual serialization.

// app/actions.ts
'use server'

import { revalidatePath } from 'next/cache'

export async function createTodo(formData: FormData) {
  const title = formData.get('title')
  if (typeof title !== 'string' || title.trim().length === 0) {
    return { error: 'Title is required' }
  }
  await db.todo.create({ data: { title: title.trim() } })
  revalidatePath('/todos')
  return { ok: true }
}
// app/todos/page.tsx
import { createTodo } from '@/app/actions'

export default function TodosPage() {
  return (
    <form action={createTodo}>
      <input name="title" placeholder="What needs doing?" />
      <button type="submit">Add</button>
    </form>
  )
}

No useState, no onSubmit, no loading spinner wired by hand. The form posts, the server runs the function, the page revalidates. For mutations triggered by your own UI, this is the least code that could possibly work — and in production, least code usually means fewest bugs.

A Route Handler is an HTTP endpoint: a route.ts file that exports GET, POST, PUT, or DELETE and returns a Response. It is the App Router replacement for the old pages/api routes.

// app/api/todos/route.ts
import { NextResponse } from 'next/server'

export async function POST(request: Request) {
  const body = await request.json()
  if (typeof body.title !== 'string' || body.title.trim().length === 0) {
    return NextResponse.json({ error: 'Title is required' }, { status: 400 })
  }
  const todo = await db.todo.create({ data: { title: body.title.trim() } })
  return NextResponse.json(todo, { status: 201 })
}

Same database call, completely different contract: this one speaks HTTP, so anything that can send an HTTP request can use it.

The decision framework I use in production

1. Who is calling?

This is the question that settles 90% of cases.

  • Your own UI (a form, a button, a drag-and-drop reorder) → Server Action. The caller is a React component, and Server Actions are built for exactly that. You get progressive enhancement for free: the form still works with JavaScript disabled.
  • Anything else (a Stripe webhook, a Flutter app, a cron job, another service) → Route Handler. Server Actions are not callable over plain HTTP with a stable contract, and they were never meant to be. Don't bend them into an API.

2. Do you need an HTTP response?

Route Handlers give you full control over status codes, headers, and response bodies. That matters when the caller checks response.status === 201, needs a Content-Type: application/json, or expects a redirect with a specific header.

Server Actions return plain serializable values — objects, strings, numbers. They can't set a status code or return a streamed file. If the caller needs HTTP semantics, you need a Route Handler.

3. Is the work a mutation or a read?

Server Actions are designed for mutations: create, update, delete. You can call them to read data, but you shouldn't — a Server Component can read the database directly, and a Client Component that needs fresh data should use a Route Handler or a server-rendered page instead. Using Server Actions as a read API adds a round trip where none is needed.

Route Handlers handle both reads and writes, but for reads inside your own app they are usually the wrong tool too: fetch the data in a Server Component and render it. Save the endpoint for callers that can't do that.

4. How does the error reach the user?

With a Server Action, the error is a return value. Your component reads result.error and renders it next to the field that caused it. This maps naturally onto form UX.

With a Route Handler, the error is an HTTP status plus a JSON body. Your client code has to parse it, map it to fields, and decide what to show. That's fine for an API consumer — a mobile app expects exactly this — but it's extra plumbing for a form that lives ten lines away from the server code.

Where Server Actions shine

Forms, obviously. The action prop plus useFormStatus gives you pending states and field-level errors with almost no client code:

'use client'

import { useFormStatus } from 'react-dom'

function SubmitButton() {
  const { pending } = useFormStatus()
  return (
    <button type="submit" disabled={pending}>
      {pending ? 'Saving…' : 'Add'}
    </button>
  )
}

Mutations that end with a revalidation. After a Server Action changes data, revalidatePath or revalidateTag refreshes the affected pages on the next request. No cache keys to manage by hand, no stale list after a delete.

Optimistic updates. Pair a Server Action with useOptimistic and the UI updates instantly, rolling back automatically if the server rejects the change. This used to be a hand-rolled state machine; now it's a hook.

Where Route Handlers are non-negotiable

Webhooks. Stripe, GitHub, and every other service that notifies you over HTTP needs a stable URL. A Route Handler is the only answer here — and remember to verify the signature before trusting the payload:

// app/api/webhooks/stripe/route.ts
import { headers } from 'next/headers'
import Stripe from 'stripe'

export async function POST(request: Request) {
  const body = await request.text()
  const signature = headers().get('stripe-signature')
  const event = stripe.webhooks.constructEvent(
    body,
    signature!,
    process.env.STRIPE_WEBHOOK_SECRET!
  )
  if (event.type === 'checkout.session.completed') {
    await fulfillOrder(event.data.object)
  }
  return new Response(null, { status: 200 })
}

Non-Next.js clients. Your Flutter app, your public API consumers, your Zapier automation — none of them can call a Server Action. They need HTTP, so they need Route Handlers.

File downloads and non-JSON responses. Returning a PDF, a CSV export, or an image? A Route Handler can stream any Response body. A Server Action cannot.

The traps I've actually hit

Don't put business logic in two places. If both your form and your mobile app create the same resource, extract the core logic into a shared function and call it from both the Server Action and the Route Handler. The moment the validation rules drift apart, one client starts creating records the other one rejects.

// lib/todos.ts — one source of truth
export async function createTodoRecord(title: string) {
  if (title.trim().length === 0) throw new Error('Title is required')
  return db.todo.create({ data: { title: title.trim() } })
}

Don't forget auth in Route Handlers. Server Actions run inside your app's session context, so it's easy to remember the auth check. Route Handlers are public URLs — anyone can curl them. Every Route Handler that touches user data needs an explicit auth check at the top, before anything else runs.

Don't use Server Actions for third-party callbacks. I've seen teams try to point a payment provider at a Server Action URL. It doesn't work — the URL is internal to Next.js and the payload format is not a public API. Use a Route Handler and move on.

A simple rule to take with you

Ask one question: who calls this? If the answer is "my own UI", write a Server Action. If the answer is anything else, write a Route Handler. When both call the same thing, put the logic in a shared function and let each entry point be a thin wrapper.

That rule has kept every Next.js codebase I've shipped in production free of the two most common messes: forms posting to API routes that only exist for the form, and external integrations duct-taped onto functions that were never designed to be called over HTTP.

  • #Next.js
  • #React
  • #TypeScript
  • #Backend