NextResponse.json(): The Standard for API Responses in Next.js
NextResponse.json() is the standard way to send JSON from Next.js Route Handlers, like Express's res.json(). Use it in app/api routes to return data; it automatically sets the correct headers.
WHY IT EXISTS: In server-side code, you often need to send structured data back to a client. While the web platform provides a standard Response object, creating a correct JSON response requires manual stringification and setting headers. NextResponse.json() was created to abstract away this boilerplate for Next.js API endpoints, known as Route Handlers.
THE MENTAL MODEL: Think of NextResponse.json() as the purpose-built tool for sending JSON from your Next.js server. It's a specialized factory that takes a JavaScript object and returns a perfectly formed Response object with the right headers, ready to be sent over the network. It's the Next.js equivalent of res.json() in the Express framework.
HOW IT WORKS: NextResponse.json() is a static method. You pass it a JavaScript object or array. Internally, it calls JSON.stringify() on your data and creates a new Response object with the resulting string as the body. Crucially, it also sets the Content-Type header to application/json. You can also pass a second argument, an options object, to set other response properties like the HTTP status code, for example { status: 201 } for a successful creation.
WHEN TO USE IT: Always use NextResponse.json() when returning JSON data from a Route Handler (route.ts or route.js files) in the Next.js App Router. This is the standard, recommended practice for building APIs with Next.js, as it ensures correctness and improves code readability.
WHEN NOT TO USE IT: Do not use NextResponse.json() if you need to return something other than JSON, like HTML, a plain text string, or an image file. For those cases, you would use the base new Response() constructor with the appropriate content and Content-Type header. This function is for server-side code only and is not available in client components.
ONE CANONICAL EXAMPLE: In an API route file like app/api/users/route.ts, you can define a GET handler to return a list of users. First, import NextResponse from next/server. Then, inside an async function GET(), create your data and return it with NextResponse.json({ data }). For example: return NextResponse.json({ users: [{ id: 1, name: 'Alice' }] });. To send a custom status code, like a 400 Bad Request, pass an options object as the second argument: return NextResponse.json({ error: 'Missing name' }, { status: 400 });.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.