GET and POST
- React course
- Advanced
- Lesson 10/56
- 4 min
Learn to answer GET and POST requests.
GET and POST
You can define both GET and POST in an API route. GET usually reads data, POST writes new data. The same file has two separate export async functions.
The POST function reads the body with await request.json(). GET reads parameters from request.url or searchParams.
Returning proper status codes is good practice: 200 ok, 201 created, 400 bad request.
Response types
Next.js App Router API routes can return Response, NextResponse.json() or NextResponse.redirect(). NextResponse.json automatically adds JSON headers.
Example: return NextResponse.json({ ok: true }). To add a status code, use a second argument: { status: 201 }.
For plain text, new Response("...") is enough.
Practice POST route
Write a POST function: take request, read the body with await request.json(), return NextResponse.json({ ok: true, received: data }, { status: 201 }). Include import { NextResponse } from "next/server". Make it export async.
Starter code
// app/api/items/route.js
// import NextResponse ve POST fonksiyonunu yazSample solution
// app/api/items/route.js
import { NextResponse } from "next/server";
export async function POST(request) {
const data = await request.json();
return NextResponse.json({ ok: true, received: data }, { status: 201 });
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How to read the POST body?
- fetch()
- request.body
- useState
- await request.json() Correct answer
Explanation: POST body = await request.json().
2 NextResponse json
import { NextResponse } from "next/server";
export async function POST(request) {
const data = await request.json();
return NextResponse.____({ ok: true, data });
}
import { NextResponse } from "next/server";
export async function POST(request) {
const data = await request.json();
return NextResponse.json({ ok: true, data });
}
Explanation: NextResponse.json returns a JSON response.
3 GET and POST: match the terms
| Term | Meaning |
|---|---|
Response |
Raw response |
NextResponse.json |
JSON response |
status 201 |
Created |
await request.json |
Body read |