Skip to the content

Lesson 181 of 296

Route handlers and server actions

What you will learn

  • Route handlers (API endpoints) with route.ts
  • Reading requests and returning responses
  • Server actions with "use server"
  • Using server actions in forms with useActionState
  • Validation and security in server actions
  • When to use which
On this page

Route handlers

A route.ts file in the app folder creates an HTTP endpoint. Export a function named after each HTTP method (Part 15):

TSX
import { NextResponse, type NextRequest } from "next/server";
import { z } from "zod";

const NewsletterSchema = z.object({ email: z.email() });

export async function GET(request: NextRequest) {
  const search = request.nextUrl.searchParams.get("q") ?? "";
  return NextResponse.json({ query: search, results: [] });
}

export async function POST(request: NextRequest) {
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }
  const parsed = NewsletterSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: "Enter a valid email address" }, { status: 422 });
  }
  return NextResponse.json({ subscribed: parsed.data.email }, { status: 201 });
}
  • app/api/newsletter/route.ts serves /api/newsletter.
  • Dynamic segments work the same way: app/api/orders/[id]/route.ts receives { params } (a Promise) as the second argument.
  • A folder cannot contain both page.tsx and route.ts.
  • The handlers use the standard web Request and Response objects; NextRequest and NextResponse add helpers.

Use route handlers for: endpoints called by other clients (mobile apps, partners, webhooks such as Stripe), client-side fetching with TanStack Query, file downloads, and anything that needs full control of the HTTP response.

Server actions

A server action is an async function that runs on the server but can be called from the client, like a remote function call. Next.js creates the hidden endpoint for you. Mark it with "use server" (at the top of the function, or at the top of a file to make every export an action):

TSX
"use server";

import { z } from "zod";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

const ContactSchema = z.object({
  name: z.string().trim().min(1, "Enter your name"),
  email: z.email("Enter a valid email address"),
  message: z.string().trim().min(10, "Message must be at least 10 characters")
});

export type ContactState = {
  errors?: Partial<Record<"name" | "email" | "message", string>>;
  message?: string;
};

declare function saveMessage(data: z.infer<typeof ContactSchema>): Promise<void>;

export async function sendContact(_prev: ContactState, formData: FormData): Promise<ContactState> {
  const parsed = ContactSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) {
    const errors: ContactState["errors"] = {};
    for (const issue of parsed.error.issues) {
      const field = issue.path[0];
      if (field === "name" || field === "email" || field === "message") errors[field] ??= issue.message;
    }
    return { errors };
  }
  await saveMessage(parsed.data);
  revalidatePath("/admin/messages");
  redirect("/contact/thanks");
}

Using it in a form

TSX
"use client";

import { useActionState } from "react";
import { sendContact, type ContactState } from "./actions";

export function ContactForm() {
  const [state, formAction, pending] = useActionState<ContactState, FormData>(sendContact, {});
  return (
    <form action={formAction} noValidate>
      <label htmlFor="name">Name</label>
      <input id="name" name="name" aria-describedby="name-error" />
      {state.errors?.name && <p id="name-error" role="alert">{state.errors.name}</p>}

      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" aria-describedby="email-error" />
      {state.errors?.email && <p id="email-error" role="alert">{state.errors.email}</p>}

      <label htmlFor="message">Message</label>
      <textarea id="message" name="message" aria-describedby="message-error" />
      {state.errors?.message && <p id="message-error" role="alert">{state.errors.message}</p>}

      <button type="submit" disabled={pending}>{pending ? "Sending..." : "Send"}</button>
    </form>
  );
}
  • <form action={...}> sends the FormData to the action (React 19 form actions, Lesson 164).
  • useActionState keeps the returned state (errors) and gives a pending flag.
  • Progressive enhancement: when the form is rendered by a Server Component and passed the action directly, it can submit even before JavaScript loads.
  • After the change, the action revalidates cached data (Lesson 179) and may redirect.

Security: actions are public endpoints

This is the most important point about server actions, and a common interview question. Every server action becomes a public HTTP endpoint: anyone can call it with any data, even if the button is hidden in the UI. So inside every action:

  1. Validate the input with a schema (Zod). Never trust FormData types.
  2. Authenticate: check who the user is (read the session).
  3. Authorise: check that this user may do this to this record (Part 20: broken access control).
  4. Return safe, minimal data and generic error messages.

Next.js helps (actions only accept POST requests, check the Origin header against the host to stop CSRF, and use unguessable, encrypted action IDs), but the checks above are your job.

Which one to use?

Server actionRoute handler
Called fromYour own Next.js UI (forms, buttons)Anything: other apps, webhooks, scripts, client fetching
HTTP methodPOST onlyAny
IntegrationForm state, pending UI, revalidation, redirect built inManual
Good forMutations from your own pagesPublic APIs, webhooks, GET endpoints for client data

For a big separate back end (NestJS, Part 16), Next.js may only call it, and server actions become a thin layer that forwards requests.

How to say it in an interview

"Route handlers are route.ts files exporting GET, POST and so on with Web Request and Response objects; I use them for public APIs, webhooks and client-side fetching. Server actions are 'use server' functions that run on the server but are called from my UI, usually as a form action with useActionState for errors and pending state; they can revalidate and redirect. Every server action is a public POST endpoint, so I always validate input with Zod, authenticate and authorise inside it, and return minimal data."

Key words

WordMeaning
Route handlerAn HTTP endpoint defined in route.ts
Server actionA server function callable from client code, marked "use server"
useActionStateHook holding an action's returned state and pending flag
Progressive enhancementWorking without JavaScript, better with it
WebhookAn HTTP request another service sends to your app when something happens

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.