DEV3 Technologies home

DEV3 Developer Forum

How do I write an API route handler in the Next.js App Router?

Next.js helpSolved0 views
dev3 ·

In the Pages Router I used pages/api/hello.ts with req and res. What is the App Router equivalent, how do I read JSON bodies and query params, and how do I return status codes?

#nextjs#route-handlers#api

0

1 reply

dev3 · Accepted answer

Create a route.ts file inside any folder under app/. Export a function named after the HTTP method.

// app/api/items/route.ts
import { NextRequest, NextResponse } from "next/server";

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

export async function POST(req: Request) {
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }
  // validate with zod, then save
  return NextResponse.json({ ok: true }, { status: 201 });
}

Dynamic segments

// app/api/items/[id]/route.ts
export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  return new Response(null, { status: 204 });
}

Things to know

  • Supported methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS.
  • You cannot have page.tsx and route.ts in the same folder.
  • From Next 15 GET handlers are not cached by default. Add export const dynamic = "force-static" to opt in.
  • Read form data with await req.formData(), raw text with req.text().
  • Use the standard Web Request/Response, there is no res.send.
  • Webhooks that need the raw body (Stripe) should call await req.text() and verify the signature on that string.
  • Use the Node runtime for database drivers (export const runtime = "nodejs").

Pitfall: do not export helper functions from route.ts files, only the HTTP methods and route config, otherwise the build fails. Put helpers in lib/.

If you need to test the endpoint quickly, the API request tester works from the browser.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.