Building APIs with Next.js — App Router & Route Handlers
Key Points
- App Router uses web-standard Request/Response APIs
- Export HTTP methods (GET/POST/etc.) in app/.../route.ts
- Static SPA export disables dynamic server endpoints
Summary
This guide explains how to build HTTP APIs using Next.js App Router and Route Handlers. It covers project setup, placing route.ts files in app/, exporting method handlers (GET, POST, etc.), using the Web Request/Response APIs (NextRequest/NextResponse), handling query params, headers and cookies, dynamic route segments, reusable middleware wrappers, proxying/backends (BFF), and deployment trade-offs including static SPA export limits and Vercel deployment features.
Key Points
- Initialize projects quickly:
npx create-next-app@latest --apiadds an exampleapp/api/.../route.ts. - App Router (app/) uses Web standard Request/Response; prefer
route.tsover pages/api/* for new apps. - Export per-method handlers in a single file (export async function GET/POST/PUT/DELETE) to handle multiple HTTP verbs.
- Access request data via
Request/NextRequestand return aResponse/NextResponse; userequest.nextUrl.searchParamsfor query params. - Read cookies and headers with
next/headershelpers or viarequest.headers; NextRequest/NextResponse extend web APIs. - Create dynamic API routes with folder segments like
app/api/users/[id]/route.tsand readparams.idin handlers. - Build reusable middleware wrappers (e.g.,
withAuth) to centralize auth, logging, or validation across handlers. - Use Route Handlers as a proxy/BFF to call upstream services, forward auth, and transform responses.
- Deployment: standard Node.js/
next startsupports full server features; SPA/output: 'export'static mode cannot run server endpoints (GET can be static only if not dynamic). - On Vercel you can deploy Route Handlers with platform features (firewall, cron jobs); consider a separate API service if you need full control or heavy compute.
- Skip creating public API endpoints when server components can fetch private data directly for your Next.js app.
Actionable checklist for engineers
- Add
app/api/<route>/route.tsand export HTTP method functions. - Use
NextRequestandcookies()/headers()for shared server logic. - Use dynamic segments for id-based routes and return proper status codes (200, 201, 204, 401).
- Wrap common logic into small libs (e.g.,
lib/with-auth.ts) and reuse across handlers. - Evaluate deployment target: if you need server-side runtime features, avoid SPA/static-only export or host API separately.