Episode 2 — React Frontend Architecture NextJS / 2.20 — Building APIs with NextJS
2.20 — Quick Revision: Next.js APIs
Cheat Sheet
| Topic | Remember |
|---|---|
| File | app/.../route.ts |
| Exports | GET, POST, PUT, PATCH, DELETE, … |
| Request | Web Request / NextRequest |
| Response | NextResponse.json(body, { status, headers }) |
| Query | request.nextUrl.searchParams |
| Dynamic | context.params — await in Next 15+ |
| JSON body | await request.json() in try/catch → 400 if invalid |
| Validation | Zod → 422 or 400 (pick one, document) |
| DB | Service layer + pooled / serverless-safe connection |
| Delete ok | 204 + empty body common pattern |
2.20.a — Route handlers & conventions
- Folder path under
app/defines URL segments;route.tscollocates HTTP with UI routes if you choose. - Prefer
route.tsover legacypages/apifor 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, safemessage, optionaldetailsfor 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
| # | Prompt | Answer you should produce |
|---|---|---|
| 1 | Where does GET /api/health live? | app/api/health/route.ts exporting GET. |
| 2 | Pages api vs route.ts? | Legacy default handler vs App Router per-verb Web APIs. |
| 3 | Malformed JSON status? | 400 after failed request.json() parse. |
| 4 | Duplicate unique constraint? | 409 with stable code like EMAIL_IN_USE. |
| 5 | Why service layer? | Testability, reuse from Server Actions, centralized transactions. |
| 6 | Edge DB caution? | Driver support + pooling model; default Node for classic SQL unless proven. |
| 7 | CORS with cookies? | Never careless *; explicit origin allowlist + correct preflight. |
| 8 | When Route Handler over Server Action? | Public HTTP consumers, webhooks, documented REST/OpenAPI needs. |