Server Actions and Route Handlers · Lesson 15 of 24
Next.js Route Handlers: Building APIs
Server Actions cover mutations from your own UI. When something else needs to talk to your app – a mobile app, a partner's system, a payment provider's webhook, a cron job – you build an HTTP endpoint. In the App Router that's a Route Handler: a route.ts file that exports functions named after HTTP methods and returns standard Web Response objects.
In this lesson
- A JSON API with
GETandPOST - Dynamic params and query strings
- Validating input and returning status codes
- Route Handlers vs Server Actions
GET and POST
// lib/courses.ts
export type Course = { slug: string; title: string; level: "beginner" | "intermediate" };
export const courses: Course[] = [
{ slug: "react", title: "React.js", level: "beginner" },
{ slug: "nextjs", title: "Next.js", level: "intermediate" },
];
// app/api/courses/route.ts
import { type NextRequest } from "next/server";
import { z } from "zod";
import { courses } from "@/lib/courses";
export async function GET(request: NextRequest) {
const level = request.nextUrl.searchParams.get("level"); // ?level=beginner
const list = level ? courses.filter((c) => c.level === level) : courses;
return Response.json({ count: list.length, courses: list });
}
const NewCourse = z.object({
title: z.string().min(3),
level: z.enum(["beginner", "intermediate"]),
});
export async function POST(request: Request) {
const body = await request.json().catch(() => null);
const parsed = NewCourse.safeParse(body);
if (!parsed.success) {
return Response.json({ error: "Invalid course", issues: z.flattenError(parsed.error).fieldErrors }, { status: 400 });
}
const slug = parsed.data.title.toLowerCase().replace(/[^a-z0-9]+/g, "-");
const course = { slug, ...parsed.data };
courses.push(course); // save it
return Response.json(course, { status: 201, headers: { Location: `/api/courses/${slug}` } });
}
GET /api/courses?level=beginner
→ 200 application/json
{"count":1,"courses":[{"slug":"react","title":"React.js","level":"beginner"}]}
POST /api/courses {"title":"Docker Basics","level":"beginner"}
→ 201 (Location: /api/courses/docker-basics) application/json
{"slug":"docker-basics","title":"Docker Basics","level":"beginner"}
POST /api/courses {"title":"X","level":"expert"}
→ 400 application/json
{"error":"Invalid course","issues":{"title":["Too small: expected string to have >=3 characters"],"level":["Invalid option: expected one of \"beginner\"|\"intermediate\""]}}
GET /api/courses
→ 200 application/json
{"count":3,"courses":[{"slug":"react","title":"React.js","level":"beginner"},{"slug":"nextjs","title":"Next.js","level":"intermediate"},{"slug":"docker-basics","title":"Docker Basics","level":"beginner"}]}Response.json(data, init)sends JSON with the right header;init.statussets the status code.NextRequestextends the standardRequestwith conveniences likerequest.nextUrl.searchParamsandrequest.cookies.- Validate request bodies exactly like form data – the zod schema from the previous lesson works here too.
Dynamic segments
// app/api/courses/[slug]/route.ts
import { courses } from "@/lib/courses";
export async function GET(_request: Request, ctx: RouteContext<"/api/courses/[slug]">) {
const { slug } = await ctx.params; // params is a Promise, like in pages
const course = courses.find((c) => c.slug === slug);
if (!course) return Response.json({ error: `No course "${slug}"` }, { status: 404 });
return Response.json(course);
}
export async function DELETE(request: Request, ctx: RouteContext<"/api/courses/[slug]">) {
if (request.headers.get("authorization") !== `Bearer ${process.env.ADMIN_TOKEN}`) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const { slug } = await ctx.params;
const index = courses.findIndex((c) => c.slug === slug);
if (index === -1) return Response.json({ error: `No course "${slug}"` }, { status: 404 });
courses.splice(index, 1);
return new Response(null, { status: 204 }); // deleted, no body
}
// lib/courses.ts
export const courses = [
{ slug: "react", title: "React.js", level: "beginner" },
{ slug: "nextjs", title: "Next.js", level: "intermediate" },
];
GET /api/courses/nextjs
→ 200 application/json
{"slug":"nextjs","title":"Next.js","level":"intermediate"}
GET /api/courses/vue
→ 404 application/json
{"error":"No course \"vue\""}
DELETE /api/courses/react
→ 401 application/json
{"error":"Unauthorized"}RouteContext<"/api/courses/[slug]"> is a generated type, like PageProps, so slug is typed for you.
Caching GET handlers
With Cache Components, a GET handler follows the same rules as a page: if it only uses static or cached data, its response is prerendered at build time. To cache data in a handler, put "use cache" in a helper function (not in the handler itself). Handlers that read the request – headers, cookies, the query string – run on every request.
Route Handlers vs Server Actions
| Use a Server Action for… | Use a Route Handler for… |
|---|---|
| forms and buttons in your own Next.js UI | public or third-party APIs (mobile apps, partners) |
| mutations followed by UI updates | webhooks (Stripe, Razorpay, GitHub, a CMS) |
| type-safe calls without writing fetch code | non-HTML responses: files, RSS feeds, images, streams |
| GET endpoints that other clients read, with HTTP caching |
Don't call your own API from Server Components
A Server Component that fetches /api/courses on the same server makes an unnecessary HTTP round trip – and during the build there's no server to answer. Call the data function (getCourses()) directly instead; keep Route Handlers for external clients.
Practice
Try it yourself
Create
GET /api/healththat returns{ "status": "ok", "node": … }with the Node.js major version, is never prerendered, and sends aCache-Control: no-storeheader.Show solution
// app/api/health/route.ts import { connection } from "next/server"; export async function GET() { await connection(); // never prerender a health check return Response.json( { status: "ok", node: process.version.split(".")[0] }, { headers: { "Cache-Control": "no-store" } } ); }GET /api/health → 200 application/json {"status":"ok","node":"v24"}
Quick check
What file defines a Route Handler?
route.ts, exporting functions named GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS.
Can route.ts and page.tsx live in the same folder?
No – a URL is either a page or an API endpoint.
Should a Server Component fetch your own /api route?
No – call the underlying data function directly.
Summary
- route.ts files export HTTP method functions that return Web Responses.
- Read query strings from nextUrl.searchParams and params from the awaited context; validate bodies and return proper status codes.
- Use Route Handlers for external clients and webhooks, Server Actions for your own UI.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.