Dynamic product page
- React course
- Advanced
- Lesson 15/56
- 5 min
Write a page that shows product detail from a URL parameter.
Cart API
In this lesson we write app/api/cart/route.js. A POST request takes a product id and adds it to the cart; GET returns the cart.
For simplicity we keep the cart as a module-level array. In production you would use a database or Redis instead.
API routes run on the server; no JavaScript ships to the client. This keeps credentials safe.
Adding with POST
The client calls fetch('/api/cart', { method: 'POST', body: JSON.stringify({ id: 1 }) }). The server reads the body with await request.json() and pushes the id to the cart.
The response is NextResponse.json({ ok: true, cart }); the client sees the updated cart.
This pattern is the foundation of REST APIs. GET reads, POST writes, PUT updates, DELETE removes.
Practice Write cart API
Define an empty array named cart. Write a GET function: return NextResponse.json({ cart }). Write a POST function: read body with await request.json(), push with cart.push(data.id), return NextResponse.json({ ok: true, cart }, { status: 201 }). Include import { NextResponse } from "next/server". Both functions must be export async.
Starter code
// app/api/cart/route.js
// import NextResponse, cart dizisi, GET ve POST fonksiyonlarını yazSample solution
// app/api/cart/route.js
import { NextResponse } from "next/server";
const cart = [];
export async function GET() {
return NextResponse.json({ cart });
}
export async function POST(request) {
const data = await request.json();
cart.push(data.id);
return NextResponse.json({ ok: true, cart }, { status: 201 });
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which file holds the cart API?
- app/api/cart/route.js Correct answer
- app/cart/page.js
- app/api/cart.js
- cart/api.js
Explanation: Cart API = app/api/cart/route.js.
2 POST fetch
fetch("/api/cart", {
method: "____",
body: JSON.stringify({ id: 1 })
});
fetch("/api/cart", {
method: "POST",
body: JSON.stringify({ id: 1 })
});
Explanation: POST is used to add new data.
3 Dynamic product page: match the terms
| Term | Meaning |
|---|---|
POST |
Add |
GET |
Read |
JSON.stringify |
Prepare body |
await request.json |
Read body |