Next.js · module 6 of 16

Route Handlers

// app/api/users/route.js

Course map

What this module covers

4 steps · Next.js

  1. Step 1. API Routes (Route Handlers)

    // app/api/users/route.js import { NextResponse } from 'next/server'; export async function GET() { return NextResponse.json([{ id: 1, name: 'Alice' }]); } export async function POST(req) { const body = await req.json(); return NextResponse.json(body, { status: 201 }); } // app/api/users/[id]/route.js — dynamic route handler export async function DELETE(req, { params }) { await db.users.delete(params.id); return new Response(null, { status: 204 }); } // GET /api/search?q=react — query params export async function GET(req) { const { searchParams } = new URL(req.url); const q = searchParams.get('q'); return NextResponse.json({ q }); }

    The exported function name IS the HTTP method it handles — GET, POST, DELETE, etc. — Next.js routes the request to the matching export automatically, no manual method-checking required. In Next.js, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [Next.js] Does GET return a JSON response via NextResponse.json?

  2. Step 2. Quiz: API Routes (Route Handlers)

    Answer these questions about Route Handlers.

    route.js is the special filename; NextResponse.json() builds a JSON response; query params are parsed from the raw request URL. In Next.js, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [Next.js] Answer the quiz below.

  3. Step 3. Todos REST API

    Build a /api/todos REST API with GET (list all) and POST (create). Store data in a module-level in-memory array.

    A module-level array persists across requests within the same server instance — enough to demo full CRUD semantics without wiring up a real database yet. In Next.js, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [Next.js] Does GET list all todos and POST add a new one with a 201 status?

  4. Step 4. Mini project: Route Handlers

    Build a /api/todos REST API with GET (list all) and POST (create). Store data in a module-level in-memory array. Turn the completed challenge into a small standalone project. Add realistic content, clear naming, one edge case or error state, and a short README-style explanation of how the main idea works.

    A module-level array persists across requests within the same server instance — enough to demo full CRUD semantics without wiring up a real database yet. This project stage asks you to apply the same idea without step-by-step scaffolding. In Next.js, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [Next.js] Does GET list all todos and POST add a new one with a 201 status?

Loading code lab...