Sikau

Next.js · Day 13 · about 30 min

Route handlers (APIs)

route.js answers HTTP requests.

Your own API, in the same project

Mobile apps, webhooks and other sites need JSON, not pages. A route handler — a route.js file — answers HTTP requests at its URL. app/api/dishes/route.js handles /api/dishes.

Export a function per HTTP method

import { getDishes } from "@/lib/data";

export async function GET(request) {
  const veg = request.nextUrl.searchParams.get("veg");
  const dishes = await getDishes();
  const list = veg === "true" ? dishes.filter((d) => d.veg) : dishes;
  return Response.json(list.map((d) => ({ slug: d.slug, name: d.name, price: d.price })));
}

export async function POST(request) {
  const body = await request.json();
  if (!body.name) {
    return Response.json({ error: "name is required" }, { status: 400 });
  }
  return Response.json({ ok: true, name: body.name }, { status: 201 });
}
  • Dynamic segments work here too: app/api/dishes/[slug]/route.js receives { params } as the second argument.
  • A folder can have page.jsx or route.js, not both.
  • Your own pages usually don't need an API: Server Components can read data directly. Route handlers are for *other* clients.

The rest of this lesson

  • Requests and responsesexplain
  • When you need oneexplain
  • Which status?predict
  • Status for the situationmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 19 lessons of Next.js