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?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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?
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 });
}
// 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 });
}
page.tsx and route.ts in the same folder.export const dynamic = "force-static" to opt in.await req.formData(), raw text with req.text().Request/Response, there is no res.send.await req.text() and verify the signature on that string.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.