Episode 2 — React Frontend Architecture NextJS / 2.20 — Building APIs with NextJS

2.20 — Quick Revision: Next.js APIs

<< 2.20 Overview


Cheat Sheet

TopicRemember
Fileapp/.../route.ts
ExportsGET, POST, PUT, PATCH, DELETE, …
RequestWeb Request / NextRequest
ResponseNextResponse.json(body, { status, headers })
Queryrequest.nextUrl.searchParams
Dynamiccontext.paramsawait in Next 15+
JSON bodyawait request.json() in try/catch → 400 if invalid
ValidationZod → 422 or 400 (pick one, document)
DBService layer + pooled / serverless-safe connection
Delete ok204 + empty body common pattern

2.20.a — Route handlers & conventions

  • Folder path under app/ defines URL segments; route.ts collocates HTTP with UI routes if you choose.
  • Prefer route.ts over legacy pages/api for new App Router projects.

2.20.b — HTTP methods

  • One export per verb; return precise status codes; document idempotency for PUT/DELETE.
  • Parse query params from NextRequest#nextUrl.

2.20.c — Databases

  • Handlers stay thin; services/transactions live in modules callable from actions too.
  • Watch serverless connection storms; use poolers/proxies recommended by your ORM.

2.20.d — Response shape & errors

  • Stable code, safe message, optional details for fields.
  • Log rich diagnostics server-side with request correlation ids.

Status Codes (Ultra Short)

200 OK          — read / update with body
201 Created     — POST create
204 No Content  — delete / update no body
400             — bad JSON / bad request
401 / 403       — authn / authz
404             — missing resource
409             — conflict
500             — unexpected (log inside)

One-Line Senior Phrase

route.ts is the HTTP adapter; services own business logic and transactions; errors map to stable codes and safe messages.”


Self-check: spoken answers

#PromptAnswer you should produce
1Where does GET /api/health live?app/api/health/route.ts exporting GET.
2Pages api vs route.ts?Legacy default handler vs App Router per-verb Web APIs.
3Malformed JSON status?400 after failed request.json() parse.
4Duplicate unique constraint?409 with stable code like EMAIL_IN_USE.
5Why service layer?Testability, reuse from Server Actions, centralized transactions.
6Edge DB caution?Driver support + pooling model; default Node for classic SQL unless proven.
7CORS with cookies?Never careless *; explicit origin allowlist + correct preflight.
8When Route Handler over Server Action?Public HTTP consumers, webhooks, documented REST/OpenAPI needs.

<< 2.20 Overview