Next.jsEasy
How do you return JSON from a Route Handler?
Return Response.json(data, init) (standard Web API) or NextResponse.json(data, init). Both serialize the value, set Content-Type: application/json, and accept a status and headers in the second argument.
Examples of init options
{ status: 201 }for created resources.{ status: 404 }with an error body.{ headers: { "Cache-Control": "public, s-maxage=60" } }to let a CDN cache it.
Response.json vs NextResponse.json
They produce the same JSON response. NextResponse adds convenience APIs such as response.cookies.set(), and helpers like NextResponse.redirect() and NextResponse.rewrite() (the latter mainly in Proxy). Use Response.json when you need nothing extra; it keeps handlers portable.
Good practices
- Use a consistent error shape, for example
{ error: { code, message } }. - Return proper status codes: 200, 201, 204 (no body), 400, 401, 403, 404, 409, 422, 429, 500.
- Do not leak stack traces or database errors in responses; log them on the server.
- Values like
BigIntandMapare not JSON-serializable. Convert them first, orJSON.stringifythrows. - For
204 No Contentusenew Response(null, { status: 204 }), since a JSON body is not allowed.
Code example
tsx
1// app/api/products/[id]/route.ts2import { NextResponse } from "next/server";3import { db } from "@/lib/db";45export async function GET(_req: Request, ctx: RouteContext<"/api/products/[id]">) {6 const { id } = await ctx.params;7 const product = await db.product.findUnique({ where: { id } });89 if (!product) {10 return Response.json(11 { error: { code: "NOT_FOUND", message: `Product ${id} not found` } },12 { status: 404 }13 );14 }1516 const res = NextResponse.json(17 { id: product.id, name: product.name, price: Number(product.price) },18 { status: 200, headers: { "Cache-Control": "public, s-maxage=60, stale-while-revalidate=600" } }19 );20 res.cookies.set("last_viewed", id, { path: "/", maxAge: 3600 });21 return res;22}
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.