Skip to main content

Web frameworks · Intermediate · 24 min

Build JSON endpoints with Next.js route handlers

By Padding · Updated 18 Nov 2026
Node.js 26 (node:26 image) · Next.js 16.4.6 · Zod 4.6.7 · TypeScript 5.9.3

You will build a small books API in Next.js 16.4 with GET, POST and DELETE route handlers, Zod validation, Problem Details errors, cache headers and CORS, and check every endpoint with a curl script.

On this page

A route handler is a route.ts file inside the app/ folder that answers HTTP requests with whatever you return: JSON, text, a file. Pages are for people with browsers. Route handlers are for programs: a mobile app, another website, a payment provider calling you back, a script on a schedule.

You will build a small books API from an empty folder. It lists books with search and a limit, returns one book by id, adds a book from a JSON body, and deletes one. Bad input gets a clear error in the Problem Details format (RFC 9457), reads carry cache headers, and a cross-origin client is allowed in by name. At the end you run a production build and check every endpoint with a curl script you write yourself.

The books live in memory so the tutorial stays about HTTP. Restarting the server resets them. Store library books in SQLite with Drizzle shows how to keep data in a database, and the handlers here would call it in the same places.

Step 1 · Create a minimal Next.js project

You do not need create-next-app for an API. A Next.js app needs next, react, react-dom, an app/ folder with a root layout, and TypeScript if you write .ts files. Pin the exact versions so the project behaves the same next month:

Bash
mkdir -p ~/shelf-api
cd ~/shelf-api
cat > package.json <<'JSON'
{
  "name": "shelf-api",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "next": "16.4.6",
    "react": "19.3.1",
    "react-dom": "19.3.1",
    "zod": "4.6.7"
  },
  "devDependencies": {
    "@types/node": "26.6.6",
    "@types/react": "19.3.0",
    "@types/react-dom": "19.3.0",
    "typescript": "5.9.3"
  }
}
JSON
npm install

TypeScript is pinned to 5.9, the major version that create-next-app 16 installs, rather than TypeScript 7. Next.js type-checks your code during next build, so keep to the version its starter uses.

Add a tsconfig.json with the @/ import alias, a root layout and a home page:

Bash
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["dom", "dom.iterable", "esnext"],
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "plugins": [{ "name": "next" }],
    "paths": { "@/*": ["./*"] }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
  "exclude": ["node_modules"]
}
JSON
mkdir -p app lib
cat > app/layout.tsx <<'TSX'
export const metadata = { title: "Shelf API" };

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}
TSX
cat > app/page.tsx <<'TSX'
export default function Home() {
  return (
    <main>
      <h1>Shelf API</h1>
      <p>The JSON API lives under /api/books.</p>
    </main>
  );
}
TSX

Now the data. lib/books.ts keeps the books in a Map on globalThis, so the dev server's hot reload and every route file share one copy. The search folds accents away, so ngugi finds Ngũgĩ wa Thiong'o. If your users type names from Yoruba, Igbo, Kikuyu or French on a phone keyboard without diacritics, this one line saves them a failed search:

Bash
cat > lib/books.ts <<'TS'
export type Book = { id: string; title: string; author: string; year?: number };

type Store = { books: Map<string, Book>; nextId: number };

const holder = globalThis as typeof globalThis & { shelfStore?: Store };

function store(): Store {
  holder.shelfStore ??= {
    books: new Map([
      ["1", { id: "1", title: "Things Fall Apart", author: "Chinua Achebe", year: 1958 }],
      ["2", { id: "2", title: "Half of a Yellow Sun", author: "Chimamanda Ngozi Adichie", year: 2006 }],
      ["3", { id: "3", title: "Purple Hibiscus", author: "Chimamanda Ngozi Adichie", year: 2003 }],
      ["4", { id: "4", title: "Weep Not, Child", author: "Ngũgĩ wa Thiong'o", year: 1964 }],
    ]),
    nextId: 5,
  };
  return holder.shelfStore;
}

// "Ngũgĩ" -> "ngugi": split letters from their accents, drop the accents, lower-case.
const fold = (text: string) => text.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();

export function listBooks(query: string, limit: number): Book[] {
  const needle = fold(query);
  return [...store().books.values()]
    .filter((book) => fold(`${book.title} ${book.author}`).includes(needle))
    .slice(0, limit);
}

export function getBook(id: string): Book | undefined {
  return store().books.get(id);
}

export function addBook(input: Omit<Book, "id">): Book {
  const s = store();
  const book = { id: String(s.nextId++), ...input };
  s.books.set(book.id, book);
  return book;
}

export function deleteBook(id: string): boolean {
  return store().books.delete(id);
}
TS
npx next --version

Start the dev server in a second terminal, from ~/shelf-api. It stays in the foreground and recompiles when you save:

Bash
npm run dev
Bash
curl -s http://localhost:3000/ | grep -o '<h1>[^<]*</h1>'

Check it worked

npx next --version prints Next.js v16.4.6. The dev server prints Local: http://localhost:3000 and Ready, and the curl command prints <h1>Shelf API</h1>. The first start also writes a next-env.d.ts file and may add entries to tsconfig.json; leave both as Next.js wrote them.

Step 2 · List books with search parameters

Every response in this API goes through two small helpers. ok() sends a successful read. problem() sends an error as application/problem+json, with the fields RFC 9457 defines: type, title, status and detail. With type set to about:blank, the title is the plain HTTP status phrase, and detail says what went wrong this time. Errors are marked no-store so nobody caches them:

Bash
cat > lib/http.ts <<'TS'
import type { z } from "zod";

const titles: Record<number, string> = {
  400: "Bad Request",
  404: "Not Found",
  415: "Unsupported Media Type",
  422: "Unprocessable Content",
};

export function ok(body: unknown) {
  return Response.json(body);
}

export function problem(status: number, detail: string, extra: Record<string, unknown> = {}) {
  const body = { type: "about:blank", title: titles[status] ?? "Error", status, detail, ...extra };
  return new Response(JSON.stringify(body), {
    status,
    headers: { "Content-Type": "application/problem+json", "Cache-Control": "no-store" },
  });
}

export function fieldErrors(error: z.ZodError) {
  return error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
}
TS

The folder path is the URL. app/api/books/route.ts answers /api/books, and the exported function's name is the HTTP method it handles. Query strings arrive as text, so validate them like any other input. z.coerce.number() turns "2" into 2, and the max(50) stops a client asking for every row at once:

Bash
mkdir -p app/api/books
cat > app/api/books/route.ts <<'TS'
import type { NextRequest } from "next/server";
import { z } from "zod";
import { listBooks } from "@/lib/books";
import { fieldErrors, ok, problem } from "@/lib/http";

const ListQuery = z.object({
  q: z.string().trim().max(100).default(""),
  limit: z.coerce.number().int().min(1).max(50).default(20),
});

export async function GET(request: NextRequest) {
  const search = request.nextUrl.searchParams;
  const parsed = ListQuery.safeParse({
    q: search.get("q") ?? undefined,
    limit: search.get("limit") ?? undefined,
  });
  if (!parsed.success) {
    return problem(400, "The query string is not valid.", { errors: fieldErrors(parsed.error) });
  }
  const books = listBooks(parsed.data.q, parsed.data.limit);
  return ok({ books, count: books.length });
}
TS

Call it four ways. -G with --data-urlencode builds the query string and encodes it for you:

Bash
curl -s http://localhost:3000/api/books
echo
curl -s "http://localhost:3000/api/books?q=adichie&limit=1"
echo
curl -s -G http://localhost:3000/api/books --data-urlencode "q=ngugi"
echo
curl -s -i "http://localhost:3000/api/books?limit=500"

If the first request after you save answers with a 404 page, wait a few seconds and run it again. The dev server compiles a new route on its first request.

Check it worked

The first call returns all four books and "count":4. The second returns only Half of a Yellow Sun and "count":1. The third finds Weep Not, Child although you typed no accents. The last one shows HTTP/1.1 400 Bad Request, a content-type: application/problem+json header and a body like this, with Zod's own wording in message:

JSON
{"type":"about:blank","title":"Bad Request","status":400,"detail":"The query string is not valid.","errors":[{"field":"limit","message":"Too big: expected number to be <=50"}]}

Step 3 · Read one book from a dynamic segment

A folder named in square brackets is a dynamic segment. app/api/books/[id]/route.ts answers /api/books/1, /api/books/2 and so on. The second argument to a handler holds params, which is a Promise in Next.js 16, so await it. Quote the path in the shell, because [id] is a pattern to zsh and bash:

Bash
mkdir -p "app/api/books/[id]"
cat > "app/api/books/[id]/route.ts" <<'TS'
import { deleteBook, getBook } from "@/lib/books";
import { ok, problem } from "@/lib/http";

type Context = { params: Promise<{ id: string }> };

export async function GET(_request: Request, { params }: Context) {
  const { id } = await params;
  const book = getBook(id);
  if (!book) return problem(404, `There is no book with id ${id}.`);
  return ok(book);
}

export async function DELETE(_request: Request, { params }: Context) {
  const { id } = await params;
  if (!deleteBook(id)) return problem(404, `There is no book with id ${id}.`);
  return new Response(null, { status: 204 });
}
TS

Next.js also generates a global RouteContext<'/api/books/[id]'> type when the dev server or a build runs, which types params from the route itself. The hand-written Context type above works before any types have been generated.

Bash
curl -s http://localhost:3000/api/books/1
echo
curl -s http://localhost:3000/api/books/99
echo
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://localhost:3000/api/books/4
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://localhost:3000/api/books/4
curl -s -o /dev/null -w '%{http_code}\n' -X PUT http://localhost:3000/api/books/1

Check it worked

Book 1 comes back as one JSON object. Book 99 gets a Problem Details body with "status":404 and "detail":"There is no book with id 99.". The three status lines are 204 (deleted, nothing to send back), 404 (it is already gone) and 405. You never wrote a PUT handler, so Next.js answers 405 Method Not Allowed for you.

Step 4 · Accept new books with Zod validation

A POST body is untrusted. Check three things in order: the client said it is sending JSON (415 if not), the text parses (400 if not), and the fields make sense (422 if not). Replace app/api/books/route.ts with this version, which keeps GET and adds POST:

Bash
cat > app/api/books/route.ts <<'TS'
import type { NextRequest } from "next/server";
import { z } from "zod";
import { addBook, listBooks } from "@/lib/books";
import { fieldErrors, ok, problem } from "@/lib/http";

const ListQuery = z.object({
  q: z.string().trim().max(100).default(""),
  limit: z.coerce.number().int().min(1).max(50).default(20),
});

const NewBook = z.object({
  title: z.string().trim().min(1, "Give the book a title.").max(200),
  author: z.string().trim().min(1, "Name the author.").max(120),
  year: z.int().min(1000).max(new Date().getFullYear()).optional(),
});

export async function GET(request: NextRequest) {
  const search = request.nextUrl.searchParams;
  const parsed = ListQuery.safeParse({
    q: search.get("q") ?? undefined,
    limit: search.get("limit") ?? undefined,
  });
  if (!parsed.success) {
    return problem(400, "The query string is not valid.", { errors: fieldErrors(parsed.error) });
  }
  const books = listBooks(parsed.data.q, parsed.data.limit);
  return ok({ books, count: books.length });
}

export async function POST(request: NextRequest) {
  if (!request.headers.get("content-type")?.startsWith("application/json")) {
    return problem(415, "Send the book as JSON with Content-Type: application/json.");
  }
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return problem(400, "The request body is not valid JSON.");
  }
  const parsed = NewBook.safeParse(body);
  if (!parsed.success) {
    return problem(422, "The book has fields that are missing or invalid.", {
      errors: fieldErrors(parsed.error),
    });
  }
  const book = addBook(parsed.data);
  return Response.json(book, { status: 201, headers: { Location: `/api/books/${book.id}` } });
}
TS

z.object() drops keys it does not know. A client that sends "id": "1" cannot overwrite book 1, because id never reaches addBook. A successful create answers 201 Created with a Location header pointing at the new book, so a client does not have to guess the URL.

Bash
curl -s -i -X POST http://localhost:3000/api/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"Americanah","author":"Chimamanda Ngozi Adichie","year":2013,"id":"1"}'
echo
curl -s -X POST http://localhost:3000/api/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"  ","year":"2013"}'
echo
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:3000/api/books \
  -H 'Content-Type: application/json' -d '{"title":'
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:3000/api/books -d 'title=Americanah'

Check it worked

The first request prints HTTP/1.1 201 Created, a location: /api/books/5 header and the new book with "id":"5"; GET /api/books/1 still returns Things Fall Apart. The second prints a 422 problem with three entries in errors: title with your message Give the book a title. (the spaces were trimmed first), author because it is missing, and year because "2013" is a string, not a number. The last two lines print 400 for the broken JSON and 415 for the form-encoded body, which curl -d sends by default.

Step 5 · Set caching on GET responses

Route handlers are not cached by Next.js unless you opt in, so every request runs your code. That is right for this API, because the list depends on the query string. What you can still do is tell clients and shared caches how long a response stays fresh. On a slow connection or prepaid mobile data, a phone that reuses a 30-second-old list instead of fetching it again saves the user time and money.

Replace lib/http.ts. Only ok() changes:

Bash
cat > lib/http.ts <<'TS'
import type { z } from "zod";

const titles: Record<number, string> = {
  400: "Bad Request",
  404: "Not Found",
  415: "Unsupported Media Type",
  422: "Unprocessable Content",
};

// Successful reads: fresh for 30 s, then a cache may serve the old copy for
// up to 2 minutes more while it fetches a new one in the background.
export function ok(body: unknown) {
  return Response.json(body, {
    headers: { "Cache-Control": "public, max-age=30, stale-while-revalidate=120" },
  });
}

export function problem(status: number, detail: string, extra: Record<string, unknown> = {}) {
  const body = { type: "about:blank", title: titles[status] ?? "Error", status, detail, ...extra };
  return new Response(JSON.stringify(body), {
    status,
    headers: { "Content-Type": "application/problem+json", "Cache-Control": "no-store" },
  });
}

export function fieldErrors(error: z.ZodError) {
  return error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
}
TS

Two rules keep this safe. Use public only for data that is the same for everyone; a response that depends on who is signed in gets private or no-store. And accept that a cached list can be up to 30 seconds behind a POST or DELETE; if your clients cannot live with that, lower max-age.

If an endpoint reads nothing from the request, you can go further and have Next.js build its response once: add export const dynamic = "force-static" to that route.ts. With Cache Components switched on in next.config.ts, GET handlers follow the same prerendering rules as pages instead. This project has neither, so every call runs fresh and only the headers change.

Bash
curl -s -D - -o /dev/null http://localhost:3000/api/books/1 | grep -i '^cache-control'
curl -s -D - -o /dev/null http://localhost:3000/api/books/99 | grep -i '^cache-control'

Check it worked

The first line is cache-control: public, max-age=30, stale-while-revalidate=120. The second, for the missing book, is cache-control: no-store. A 201 from POST has no Cache-Control header at all, and nothing caches a POST response without one.

Step 6 · Allow named origins with CORS

CORS is a browser rule. A browser blocks JavaScript on https://app.example.com from reading your API's responses unless the API names that origin in Access-Control-Allow-Origin. For a POST with a JSON body, the browser first sends an OPTIONS preflight to ask permission.

Which clients need it? A native Android or iOS app that calls the API from Kotlin, Swift or React Native's networking does not send preflights and ignores CORS. A web app on another domain does. So does a hybrid app built on a web view: Capacitor serves its pages from https://localhost on Android and capacitor://localhost on iOS by default, and those are the origins your API sees.

One proxy.ts file at the project root, next to app/, can handle every /api route at once. Keep the allowed origins in an environment variable so each deployment sets its own:

Bash
cat > .env.local <<'ENV'
# Replace app.example.com with the origin of your own web app.
ALLOWED_ORIGINS=https://app.example.com,https://localhost,capacitor://localhost
ENV
cat > proxy.ts <<'TS'
import { NextResponse, type NextRequest } from "next/server";

function allowedOrigin(request: NextRequest): string | null {
  const origin = request.headers.get("origin");
  const allowed = (process.env.ALLOWED_ORIGINS ?? "")
    .split(",")
    .map((value) => value.trim())
    .filter(Boolean);
  return origin && allowed.includes(origin) ? origin : null;
}

export function proxy(request: NextRequest) {
  const origin = allowedOrigin(request);

  if (request.method === "OPTIONS") {
    const preflight = new NextResponse(null, { status: 204 });
    preflight.headers.set("Vary", "Origin");
    if (origin) {
      preflight.headers.set("Access-Control-Allow-Origin", origin);
      preflight.headers.set("Access-Control-Allow-Methods", "GET, POST, DELETE");
      preflight.headers.set("Access-Control-Allow-Headers", "Content-Type");
      preflight.headers.set("Access-Control-Max-Age", "600");
    }
    return preflight;
  }

  const response = NextResponse.next();
  response.headers.set("Vary", "Origin");
  if (origin) {
    response.headers.set("Access-Control-Allow-Origin", origin);
    // Lets browser code read the Location header after a POST.
    response.headers.set("Access-Control-Expose-Headers", "Location");
  }
  return response;
}

export const config = { matcher: "/api/:path*" };
TS

An origin that is not on the list gets no Access-Control-Allow-Origin header, and the browser blocks the read. Vary: Origin tells caches that the answer depends on the Origin header, which matters now that reads are public. Never answer with * together with cookies or other credentials.

Stop the dev server with Ctrl+C and start it again, so it loads the new .env.local and proxy.ts:

Bash
npm run dev

Send a preflight from an allowed origin, then a plain read from one that is not allowed:

Bash
curl -s -i -X OPTIONS http://localhost:3000/api/books \
  -H 'Origin: https://app.example.com' \
  -H 'Access-Control-Request-Method: POST' \
  -H 'Access-Control-Request-Headers: content-type'
curl -s -D - -o /dev/null http://localhost:3000/api/books -H 'Origin: https://unknown.example' | grep -i '^access-control' || echo "no CORS headers"

Check it worked

The preflight prints HTTP/1.1 204 No Content with access-control-allow-origin: https://app.example.com, the three methods, content-type as an allowed header and a max age of 600. The request from https://unknown.example prints no CORS headers. The API still answered it: CORS does not protect data from curl or a server, it only tells browsers what pages may read. Authentication is a separate job.

Stop the dev server with Ctrl+C before you build.

Step 7 · Build for production and check every endpoint

Build the app. Next.js compiles every route, runs the TypeScript checker and prints a route table:

Bash
npm run build

The table lists /api/books and /api/books/[id] with ƒ, the symbol for routes that run on each request, and a line for the proxy. Start the production server on port 3100, in your second terminal:

Bash
npm run start -- -p 3100

Now write a script that calls each endpoint and compares the status code with the one you expect. It runs in its own shell, prints PASS or FAIL per line, and exits non-zero if anything failed, so you can run it in CI later. %header{location} needs curl 7.84 or newer:

Bash
cat > check-api.sh <<'SH'
#!/usr/bin/env bash
# Usage: bash check-api.sh http://localhost:3100
set -u
base="${1:-http://localhost:3000}"
failures=0

expect() {
  if [ "$3" = "$2" ]; then
    echo "PASS $1"
  else
    echo "FAIL $1: expected $2, got $3"
    failures=$((failures + 1))
  fi
}

status() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
json='Content-Type: application/json'

expect "list books" 200 "$(status "$base/api/books")"
expect "reject limit=0" 400 "$(status "$base/api/books?limit=0")"
expect "read one book" 200 "$(status "$base/api/books/1")"
expect "missing book" 404 "$(status "$base/api/books/999")"
expect "problem content type" application/problem+json \
  "$(curl -s -o /dev/null -w '%{content_type}' "$base/api/books/999")"
expect "unsupported method" 405 "$(status -X PUT "$base/api/books/1")"
expect "form body" 415 "$(status -X POST -d 'title=x' "$base/api/books")"
expect "broken JSON" 400 "$(status -X POST -H "$json" -d '{' "$base/api/books")"
expect "invalid book" 422 "$(status -X POST -H "$json" -d '{"title":""}' "$base/api/books")"

location=$(curl -s -o /dev/null -w '%header{location}' -X POST -H "$json" \
  -d '{"title":"Nervous Conditions","author":"Tsitsi Dangarembga","year":1988}' "$base/api/books")
expect "create sets Location" yes "$([ -n "$location" ] && echo yes || echo no)"
expect "new book is readable" 200 "$(status "$base$location")"
expect "delete new book" 204 "$(status -X DELETE "$base$location")"
expect "deleted book is gone" 404 "$(status "$base$location")"

expect "preflight allows app origin" https://app.example.com \
  "$(curl -s -o /dev/null -w '%header{access-control-allow-origin}' -X OPTIONS \
    -H 'Origin: https://app.example.com' -H 'Access-Control-Request-Method: POST' "$base/api/books")"
expect "reads are cacheable" "public, max-age=30, stale-while-revalidate=120" \
  "$(curl -s -o /dev/null -w '%header{cache-control}' "$base/api/books/1")"

echo "$failures failed"
[ "$failures" -eq 0 ]
SH
bash check-api.sh http://localhost:3100

Check it worked

npm run build ends with the route table and no type errors. The script prints 15 PASS lines and 0 failed. If a line says FAIL, it names the endpoint and the status code that came back, which points you at the handler to read again.

Leave the production server running for the next step, or stop it with Ctrl+C.

Step 8 · Choose route handlers or server actions

The library app in this series changes books with server actions, and this tutorial did the same work with route handlers. Both run on your server. The question is who calls them.

Use a server action when the caller is your own Next.js UI: a form or button that changes data and then refreshes the page. Next.js wires up the request for you, and a server action is posted to the page that uses it, not to a URL you design and document. Server actions run one at a time, so do not use them to fetch data.

Use a route handler when the caller is anything else:

  • A mobile app, a desktop app or another website that needs a stable URL and a documented JSON contract.
  • A webhook: a payment provider such as Paystack or M-Pesa calling you when a payment completes. Read the body with await request.text() so you can check the provider's signature against the exact bytes before you parse it.
  • A GET endpoint that other clients should cache, or that you want to share as a link.
  • A scheduled job, a health check or a script.

Do not call your own route handlers from a Server Component. It adds an HTTP round trip inside your own server, and fails during a build when nothing is listening. Call the function the handler uses, such as listBooks(), directly.

When you have finished, stop the server with Ctrl+C and remove the project:

Bash
cd ~
rm -rf ~/shelf-api

Check it worked

List the endpoints you plan to build next. For each one, write down who calls it. If the answer is "a form on my own pages", it is a server action. If it is a phone, another site, a provider or a script, it is a route handler, and you can now write one with validation, Problem Details errors, cache headers and CORS. ls ~/shelf-api now reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.