Challenge: Next.js API
- React course
- Advanced
- Lesson 53/56
- 6 min
Write an API route that returns products with GET and adds with POST.
Challenge: Next.js API
In this challenge you will write a Next.js App Router route handler. In app/api/items/route.js you define GET and POST functions.
GET returns a JSON array; POST reads the request body and responds with NextResponse.json at status 201. Remember to export.
Practice Write the API route handler
Write app/api/items/route.js. Import NextResponse. In export async function GET() return NextResponse.json([{ id: 1 }]). In export async function POST(request) read the body with request.json() and respond with NextResponse.json(body, { status: 201 }).
Starter code
// app/api/items/route.js
// Write the GET and POST functions hereSample solution
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json([{ id: 1 }]);
}
export async function POST(request) {
const body = await request.json();
return NextResponse.json(body, { status: 201 });
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where does an App Router route handler live?
- app/api/items/route.js Correct answer
- app/api/route.js
- pages/api/items.js
- server.js
Explanation: In App Router the route is defined in route.js.
2 Fill in the blank: respond with status 201
import { NextResponse } from 'next/server';
export async function POST(request) {
const body = await request.json();
return NextResponse.json(body, { status: ____ });
}
import { NextResponse } from 'next/server';
export async function POST(request) {
const body = await request.json();
return NextResponse.json(body, { status: 201 });
}
Explanation: POST returns 201 for successful creation.