The second argument to Response.json sets the status. Without it, the status
is 200.
POST with a JSON body
JavaScript
export async function POST(request) { const body = await request.json(); …}
request.json() reads the JSON the caller sent. The console's POST button
sends one with fetch, a method and a body. As with server actions, check
everything that arrives. Valid JSON can still be null, a number or an array;
malformed JSON makes request.json() throw. Both should get a helpful 400,
not an accidental server error. The handler does that in two steps:
The try/catch handles text that isn't JSON at all. The long if then asks
five questions, in order, and stops at the first that fails:
Check
Fails for
body === null
null, valid JSON with nothing in it
typeof body !== "object"
5, "hi", true
Array.isArray(body)
[], which is an object too
typeof body.title !== "string"
{} or { "title": 5 }
body.title.trim() === ""
{ "title": " " }
The order matters. With null first, body.title is never read on null,
which would throw Cannot read properties of null and send a 500. And
trim() is only called once the title is known to be a string.
Trace { "title": 5 }: request.json() succeeds, so no catch. It isn't
null, it is an object, it isn't an array, but typeof 5 is "number", so
the fourth check fails: 400 {"error":"title is required"}.
Predict
In ApiConsole.jsx, the add function sends JSON.stringify({ title }).
Replace that with "null" and press POST /api/topics. Then try "[1]",
then "hello". Which step stops each one, and what does the console show?
Check your prediction
"null" is valid JSON, so it passes the catch, then fails the first check:
400 {"error":"title is required"}.
"[1]" is valid JSON too, and an object, but an array: the same 400.
"hello" isn't JSON, so request.json() throws and the catch answers
400 {"error":"Send valid JSON"}.
Put JSON.stringify({ title }) back.
A dynamic route handler
app/api/topics/[slug]/route.js handles /api/topics/routing. Route handlers
get params too, as the second argument's params property:
For forms on your own site, use server actions: less code, and the page
refreshes for you. Use route handlers when something other than your pages
needs your data, or when you need full control of the request and response.
Exercise
Delete
Add DELETE /api/topics/[slug], which removes a topic and answers
{ "deleted": "routing" }, or a 404 if there's no such topic. Add a DELETE
/api/topics/routing button to the console to try it twice.
Your working spaceNext.js · 7 filesimport "./globals.css";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>Study Hub</header>
{children}
</body>
</html>
);
}
import ApiConsole from "./ApiConsole.jsx";
export default function HomePage() {
return (
<main>
<h1>Try the API</h1>
<ApiConsole />
</main>
);
}
"use client";
import { useState } from "react";
// A tiny API client: each button sends one request and shows the answer.
export default function ApiConsole() {
const [title, setTitle] = useState("");
const [answer, setAnswer] = useState("");
async function send(url, options) {
const response = await fetch(url, options);
const body = await response.json();
setAnswer(`${response.status} ${JSON.stringify(body)}`);
}
function add() {
send("/api/topics", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
}
return (
<>
<p>
<button onClick={() => send("/api/topics")}>GET /api/topics</button>{" "}
<button onClick={() => send("/api/topics/routing")}>GET /api/topics/routing</button>{" "}
<button onClick={() => send("/api/topics/nope")}>GET /api/topics/nope</button>
</p>
<p>
<label>
Title <input value={title} onChange={(e) => setTitle(e.target.value)} />
</label>{" "}
<button onClick={add}>POST /api/topics</button>
</p>
<pre aria-label="Answer" className="card">{answer}</pre>
</>
);
}
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
color: #1c2430;
}
header,
main,
footer {
max-width: 36rem;
margin: 0 auto;
padding: 0.75rem 1rem;
}
header {
border-bottom: 1px solid #d6dde6;
}
nav {
display: flex;
gap: 1rem;
}
a {
color: #06617f;
}
h1 {
margin: 0.5rem 0;
}
.muted {
color: #5b6876;
}
.card {
border: 1px solid #d6dde6;
border-radius: 8px;
padding: 0.75rem 1rem;
margin-bottom: 0.75rem;
}
import { addTopic, getTopic, getTopics } from "@/lib/topics.js";
export async function GET() {
return Response.json(getTopics());
}
// POST /api/topics with a JSON body adds a topic.
export async function POST(request) {
let body;
try {
body = await request.json();
} catch {
return Response.json({ error: "Send valid JSON" }, { status: 400 });
}
if (body === null || typeof body !== "object" || Array.isArray(body) ||
typeof body.title !== "string" || body.title.trim() === "") {
return Response.json({ error: "title is required" }, { status: 400 });
}
const slug = body.title.trim().toLowerCase().replaceAll(" ", "-");
if (getTopic(slug)) {
return Response.json({ error: `${slug} already exists` }, { status: 409 });
}
const topic = { slug, title: body.title.trim(), day: Number(body.day) || 1 };
addTopic(topic);
return Response.json(topic, { status: 201 });
}
import { getTopic } from "@/lib/topics.js";
// GET /api/topics/routing: one topic, or a 404 with an error.
export async function GET(request, { params }) {
const { slug } = await params;
const topic = getTopic(slug);
if (!topic) {
return Response.json({ error: `No topic called ${slug}` }, { status: 404 });
}
return Response.json(topic);
}
// A pretend database of topics, in the server's memory.
const topics = [
{ slug: "routing", title: "Routing", day: 1 },
{ slug: "server-components", title: "Server components", day: 2 },
{ slug: "dynamic-routes", title: "Dynamic routes", day: 3 },
];
export function getTopics() {
return topics;
}
export function getTopic(slug) {
return topics.find((topic) => topic.slug === slug) ?? null;
}
export function addTopic(topic) {
topics.push(topic);
}
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
Deleting one topic looks like reading one: the slug comes from params, and
no such topic is a 404. The change to the data belongs in lib/topics.js,
next to addTopic, so the handler only translates its result into HTTP.
Hint 2: a first step
Write removeTopic(slug) in lib/topics.js so that it tells you whether it
found anything: true or false. Then export a DELETE function from the
[slug] route, shaped like its GET. The console's send takes the same
options as fetch, including method.
Show one solution
In lib/topics.js:
JavaScript
export function removeTopic(slug) { const index = topics.findIndex((topic) => topic.slug === slug); if (index === -1) return false; topics.splice(index, 1); return true;}
In app/api/topics/[slug]/route.js, also import removeTopic:
removeTopic returns a boolean instead of answering HTTP itself, so the
handler alone decides between 200 and 404. The second press gets a
404 because the first really removed the topic. Answering 200 both
times would hide that from the caller.
Completion is saved in this browser only. It does not measure mastery.