Skip to content
Napatdev
HomeProjectsNotesAI SkillsAboutContact
Menu
Napatdev
HomeProjectsNotesAI SkillsAboutContact

LanguageENTH

Get in touch

[email protected]
TH
All notes
ENTH

Next.js Server Actions explained: when to use them vs Route Handlers

Written byNapat Pamornsut·~2 min read·Published Sep 14, 2026
On this page
  • Environment
  • Example: contact form with no API route
  • Server Actions vs Route Handlers: how to choose
  • Why server-side validation is non-negotiable
  • Common mistakes
  • References
  • Related notes

Short answer: Server Actions are "use server" functions that run on the server but can be called directly from <form action={...}> or event handlers — no API route needed. Use them for UI-bound mutations (forms, saves, deletes). Route Handlers fit endpoints called from outside (webhooks, a REST API for a mobile app).

Environment

  • Next.js 14+ (App Router)
  • Same pattern on React 19 / Next.js 16
  • Any database; this example uses Prisma

Example: contact form with no API route

app/contact/actions.ts:

ts
'use server';

import { z } from 'zod';
import { prisma } from '@/server/db';

const contactSchema = z.object({
  email: z.string().email('Invalid email format'),
  message: z.string().min(10, 'Message must be at least 10 characters'),
});

export async function submitContact(formData: FormData) {
  const parsed = contactSchema.safeParse({
    email: formData.get('email'),
    message: formData.get('message'),
  });
  if (!parsed.success) {
    return { ok: false, error: parsed.error.issues[0].message };
  }
  await prisma.contactMessage.create({ data: parsed.data });
  return { ok: true };
}

app/contact/form.tsx:

tsx
'use client';

import { useActionState } from 'react';
import { submitContact } from './actions';

export function ContactForm() {
  const [state, submit] = useActionState(
    async (_prev: unknown, formData: FormData) => submitContact(formData),
    null,
  );
  return (
    <form action={submit}>
      <input name="email" type="email" required />
      <textarea name="message" required minLength={10} />
      <button type="submit">Send message</button>
      {state && !state.ok && <p role="alert">{state.error}</p>}
    </form>
  );
}

No fetch, no /api/contact — Next.js transports the data and invokes the server function for you.

Server Actions vs Route Handlers: how to choose

CriterionServer ActionsRoute Handler (route.ts)
Called from your own app's form/eventIdealPossible but hand-write fetch
Called from outside (webhooks, mobile apps)Not possibleIdeal
Custom HTTP methods/status/cache headersNot availableFull control
Validation + direct DB writesYesYes
Progressive enhancement (works with JS off)YesDIY

Rule of thumb: UI-bound mutations → Server Actions; system-facing endpoints → Route Handlers.

Why server-side validation is non-negotiable

HTML required and minLength help UX, not security — anyone can POST directly, bypassing your form. The zod.safeParse in the action is the only gate that counts. See the full checklist in Next.js Server Actions Security.

Common mistakes

  1. Trusting client data — skipping server validation lets junk or malicious data into the database.
  2. Throwing raw errors — stack traces leak to users; return a controlled { ok: false, error } instead.
  3. Forgetting revalidation after mutation — fresh data never shows because of stale cache; call revalidatePath/revalidateTag after successful writes.
  4. One fat action — actions should stay thin (validate > authorize > write); extract complex logic into service functions you can test separately.

References

  • Next.js Server Actions / Updating Data: https://nextjs.org/docs/app/getting-started/updating-data
  • Prisma + Next.js: https://docs.prisma.io/docs/guides/v8/frameworks/nextjs

Related notes

  • Next.js Server Actions Security: validation, authorization and CSRF
  • Next.js Server Actions + Prisma Transaction: atomic mutations
  • All Next.js notes

Author: Napat Pamornsut — About · Projects · All notes

Next note →Next.js Server Actions Security: validation, authorization and CSRF
N

Napat Pamornsut

Web Developer / Software Tester

AboutProjectsAll notes

Related projects

  • Shop Inventory & Sales Management System
  • Clean Water Monitoring
  • JodBill — Smart Expense Tracker

On this page

  • Environment
  • Example: contact form with no API route
  • Server Actions vs Route Handlers: how to choose
  • Why server-side validation is non-negotiable
  • Common mistakes
  • References
  • Related notes

All notes

  • Next.js Server Actions explained: when to use them vs Route Handlers
  • Next.js Server Actions Security: validation, authorization and CSRF
  • Odoo 19 Certification study guide: exam structure and reading plan
  • Odoo Automated Action: why imports fail and how to fix IMPORTNAME
  • Odoo Automated Action: Fix forbidden opcode STOREATTR with record.write
  • Odoo QWeb: fixing PDF page breaks with real examples
  • Odoo QWeb Table Border: controlling PDF table lines on every page
  • Playwright Page Object Model: a test structure that stays maintainable
  • What is Playwright? Start E2E testing with TypeScript for real projects
  • Next.js Server Actions + Prisma Transaction: atomic mutations

Napat Pamornsut

ณภัทร ภมรสูตร

Web development & software testing

ProjectsNotesAI SkillsAboutContactSearch

© 2026 Napatdev

Back to top