JSON response
- React course
- Advanced
- Lesson 11/56
- 4 min
Learn to return JSON with NextResponse.
JSON response
API routes most often return JSON. NextResponse.json() converts an object to JSON and adds the Content-Type: application/json header.
On the client, you call fetch('/api/items') and parse with await r.json(). Returning a proper status code on errors matters.
For example, on a validation error return NextResponse.json({ error: "..." }, { status: 400 }).
Error handling
Error handling in API routes uses try/catch. The try block does the work; if an error throws, catch catches it and returns a proper status code.
Expected errors (e.g. missing field) use 400, server errors 500. The client acts based on the code.
Error messages must be user-appropriate; sensitive info must not leak.
Practice Error-handling GET
Write a GET function: in a try block return NextResponse.json({ items: [1, 2, 3] }), in catch (e) return NextResponse.json({ error: "Server error" }, { status: 500 }). Include import { NextResponse } from "next/server" and export async function GET().
Starter code
// app/api/items/route.js
// import NextResponse ve GET fonksiyonunu (try/catch) yazSample solution
// app/api/items/route.js
import { NextResponse } from "next/server";
export async function GET() {
try {
return NextResponse.json({ items: [1, 2, 3] });
} catch (e) {
return NextResponse.json({ error: "Server error" }, { status: 500 });
}
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which status for a bad request?
- 400 Correct answer
- 200
- 100
- 500
Explanation: 400 (Bad Request).
2 try catch
try {
const data = await request.json();
return NextResponse.json({ ok: true });
} ____ (e) {
return NextResponse.json({ error: "Hata" }, { status: 500 });
}
try {
const data = await request.json();
return NextResponse.json({ ok: true });
} catch (e) {
return NextResponse.json({ error: "Hata" }, { status: 500 });
}
Explanation: The catch block catches errors.
3 JSON response: match the terms
| Term | Meaning |
|---|---|
200 |
OK |
201 |
Created |
400 |
Bad request |
500 |
Server error |