What HTTP methods are supported in API routes?

Route Handlers in the App Router support GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, each as a named export. Unsupported methods get 405 Method Not Allowed automatically. Pages Router API routes receive every method in one handler and you branch on req.method.

App Router (route.ts)

  • Export GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS as async functions.
  • If you do not export OPTIONS, Next.js implements it automatically and sets the Allow header from the methods you exported.
  • Only GET can be prerendered or cached. Other methods always run per request.

Method semantics to mention in interviews

  • GET: read, safe and idempotent; can be cached.
  • POST: create or trigger an action; not idempotent.
  • PUT: replace a resource; idempotent.
  • PATCH: partial update.
  • DELETE: remove; idempotent.
  • HEAD: like GET without a body (check existence or size).
  • OPTIONS: CORS preflight and capability discovery.

Pages Router (pages/api)

Any method reaches your default export. Use a switch (req.method) and return 405 with an Allow header for the rest.

Server Functions vs methods

Server Functions ("use server") are always invoked with POST, regardless of what they do. For a public REST API consumed by other clients, use Route Handlers.

Code example

tsx
1// app/api/posts/[id]/route.ts
2import { NextRequest } from "next/server";
3import { db } from "@/lib/db";
4
5export async function GET(_req: NextRequest, ctx: RouteContext<"/api/posts/[id]">) {
6 const { id } = await ctx.params;
7 const post = await db.post.findUnique({ where: { id } });
8 return post ? Response.json(post) : Response.json({ error: "Not found" }, { status: 404 });
9}
10
11export async function PATCH(req: NextRequest, ctx: RouteContext<"/api/posts/[id]">) {
12 const { id } = await ctx.params;
13 const data = await req.json();
14 const post = await db.post.update({ where: { id }, data: { title: data.title } });
15 return Response.json(post);
16}
17
18export async function DELETE(_req: NextRequest, ctx: RouteContext<"/api/posts/[id]">) {
19 const { id } = await ctx.params;
20 await db.post.delete({ where: { id } });
21 return new Response(null, { status: 204 });
22}
23// PUT/POST not exported -> 405 automatically; OPTIONS answered with Allow: GET, PATCH, DELETE

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.

Open in study app