Next.jsEasy
How do you handle different HTTP methods in a single API route?
In the App Router, export one function per method from the same route.ts file: export async function GET(), export async function POST(), and so on. In the Pages Router, write one default handler and branch on req.method.
App Router benefits
- Each method is a separate, typed function; there is no manual
switch. - Methods you do not export get an automatic 405.
OPTIONSis implemented for you unless you export your own.- You can share helpers (auth, validation) between methods in the same file.
Pages Router pattern
switch (req.method)with a case per method.default: set theAllowheader and return 405.- Keep each branch small by calling service functions.
Shared concerns
- Authentication: call a
requireUser()helper at the top of each method that needs it. - Validation: parse the body with Zod per method.
- Errors: wrap logic in
try/catchand return consistent JSON errors.
Tip
A REST resource often needs a collection route (/api/posts with GET and POST) and an item route (/api/posts/[id] with GET, PATCH and DELETE). Keep them as two files rather than parsing IDs from a single route.
Code example
tsx
1// app/api/posts/route.ts - collection: GET list, POST create2import { NextRequest } from "next/server";3import { z } from "zod";4import { requireUser } from "@/lib/auth";5import { db } from "@/lib/db";67const NewPost = z.object({ title: z.string().min(1), body: z.string() });89export async function GET(req: NextRequest) {10 const page = Number(req.nextUrl.searchParams.get("page") ?? 1);11 const posts = await db.post.findMany({ skip: (page - 1) * 20, take: 20 });12 return Response.json(posts);13}1415export async function POST(req: NextRequest) {16 const user = await requireUser(req);17 if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });1819 const parsed = NewPost.safeParse(await req.json());20 if (!parsed.success) return Response.json({ error: parsed.error.flatten() }, { status: 400 });2122 const post = await db.post.create({ data: { ...parsed.data, authorId: user.id } });23 return Response.json(post, { status: 201 });24}2526// Pages Router equivalent:27// switch (req.method) { case "GET": ...; case "POST": ...; default: res.setHeader("Allow", "GET, POST"); res.status(405).end(); }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.