🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js Route Handlers

A Route Handler is a JSON endpoint inside the same project. It lives in a route.ts file.

The books endpoint

The GET handler reads the store and answers with the books. The POST handler is in the next lesson.

import { NextResponse } from "next/server";
import { readBooks } from "@/lib/books";

export async function GET() {
  const books = await readBooks();
  return NextResponse.json({ books });
}

The endpoint address

The file app/api/books/route.ts answers at /api/books. The folder path is the address.

ls app/api/books

Example

curl -s http://localhost:3112/api/books

Key points

  • Route Handler: a function that answers an HTTP request with a response
  • The file is route.ts, inside an api folder. The folder sets the address.
  • GET answers a read. It returns the books as JSON.
  • The handler runs on the server. The browser never sees its code.
  • The same project holds pages and endpoints. One server serves both.

In this example, the check asks the endpoint for the books. The answer is JSON with three books, each holding an author, an id, a read flag, and a title. Dune is marked read, and the other two are not. The endpoint read the same store the pages read. One project served the JSON, and no separate backend was needed.

Note

A page returns HTML, and a Route Handler returns JSON. The file name tells them apart.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

What does a Route Handler return?