API Routes with Next.js Route Handlers
Keep frontend and backend in one Next.js project by writing HTTP endpoints as route handlers, and know when a separate server is better.
Intermediate · about 6 hours · difficulty 3/5
Learn first: Node.js Runtime Essentials, REST API Design, Server Actions and Mutations
Route handlers (route.ts files inside app) let a Next.js app expose real HTTP endpoints. For many student projects and early startups, one Next.js codebase deployed to Vercel is the simplest full-stack setup.
Basics
- app/api/companies/route.ts exporting GET and POST functions handles /api/companies.
- Handlers use the standard Web Request and Response objects; NextResponse.json is a convenient helper.
- Dynamic segments work like pages: app/api/companies/[id]/route.ts.
Good uses
- Webhooks from Razorpay, GitHub or email providers.
- Endpoints for a mobile app or a third-party integration.
- Public read APIs with caching headers.
For mutations from your own UI, server actions are often simpler.
Structure
Keep handlers thin: validate input, check auth, call a shared service module that holds business logic and database access. The same services can then be used by server components and server actions.
Limits to know
Serverless functions have execution time limits and cold starts, and do not suit long-lived connections like WebSockets. If you need those, long background work or a separate team owning the API, a standalone Express or Fastify server is a better fit.
Pitfalls
- Duplicating logic between route handlers and server actions.
- Forgetting that a handler is public and skipping auth.
- Opening a new database connection per request in serverless without pooling.
You are ready to move on when your Next.js project exposes a validated, authenticated REST endpoint and a webhook handler, both calling shared service functions.
Key concepts
- route.ts and HTTP method exports
- Request and Response objects
- Dynamic route segments
- Webhook handlers
- Shared service layer
- Serverless limits and cold starts
- Middleware for auth redirects
Other options for this step
- Building APIs with Express: Build a typed REST API with Express: routing, middleware, a layered structure and centralised error handling.
- Building APIs with Fastify: Build fast, schema-driven Node.js APIs with Fastify's plugin system, built-in validation and structured logging.
Mini project
Add /api/openings (GET with filters, POST for admins) and /api/webhooks/test (verifies a shared-secret signature) to your Next.js portal, both using one shared openings service.
Check yourself
When would you move from Next.js route handlers to a separate Express or Fastify server? Name two concrete reasons.
Free resources
- route.js file convention (Next.js)
- Response (Web API) (MDN)