Introduction
Next.js has evolved far beyond a React framework. With the App Router and Route Handlers, you can build an entire backend API without leaving the project. In this guide, we'll build a fully featured blog API using Next.js 16, TypeScript, and MongoDB.
Project Architecture
We follow a layered architecture that keeps route handlers thin:
- /lib — shared utilities and database connection
- /models — Mongoose schemas
- /validators — Zod input validation
- /services — business logic
- /middlewares — JWT auth, rate limiting
MongoDB Connection
Using a global singleton prevents Mongoose from creating multiple connections in development due to hot reload. The key is caching the promise on the global object.
const cached = global.__mongoose ?? { conn: null, promise: null }
Authentication with JWT
We implement a Higher-Order Function that wraps route handlers, verifies the bearer token, and injects the decoded payload. This keeps auth logic DRY without Next.js Edge Middleware (which can't use Mongoose).
Conclusion
With this setup, you get a production-grade API without reaching for Express or a separate backend service. Next.js handles everything.