intermediate

Route handlers

Implement HTTP handlers with request parsing, validation, response shapes, caching, and runtime constraints.

Route handlers are HTTP endpoints in `app/**/route.ts` exporting functions named after methods (`GET`, `POST`, etc.). They parse requests, enforce auth, call services, and return `Response` objects with explicit status and cache headers.

					// app/api/posts/route.ts
export async function POST(request: Request) {
  const body = await request.json();
  const post = await createPost(body);
  return Response.json(post, { status: 201 });
}
				

Choose Node or Edge runtime per handler based on APIs needed. Webhooks and file uploads often require Node.

On interviews: compare handlers to Server Actions for mutations and to external microservices for ownership.

Common pitfalls: missing method guards, unvalidated JSON bodies, and caching `POST` responses accidentally.

The trade-off is colocated endpoints versus spreading HTTP across separate services.

Checklist:

  • Export only supported HTTP methods.
  • Validate input and auth first.
  • Set cache headers explicitly.
  • Pick runtime for required APIs.