API Design in Next.js – Clean & Maintainable Route Handlers
— NextJS, API, Route-Handlers, Backend — 2 min read
API Design in Next.js – Clean & Maintainable Route Handlers
Hey everyone,
The more a project grows, the more important it becomes how we design its API. In the Next.js App Router, Route Handlers are the main place for backend logic. After several rounds of refactoring, here's the approach I use most often.
1. A Tidy Folder Structure
I like to separate by resource:
/app /api /users /route.ts /[id] /route.ts /invoices /route.tsOr if you go feature-based:
/features /users /api /route.ts2. Consistent Response Format
I always return a consistent format:
// Successreturn Response.json({ data: user }, { status: 200 });
// Errorreturn Response.json( { error: { message: "User not found", code: "USER_NOT_FOUND" } }, { status: 404 },);3. Validation with Zod
Every input must be validated:
import { z } from "zod";
const createUserSchema = z.object({ name: z.string().min(2), email: z.string().email(),});
export async function POST(request: Request) { const body = await request.json(); const parsed = createUserSchema.safeParse(body);
if (!parsed.success) { return Response.json( { error: { message: "Invalid input", details: parsed.error.flatten() } }, { status: 400 }, ); }
// continue processing...}4. Consistent Error Handling
I use a custom error class + a central handler so error responses are uniform across the entire API.
5. Things I Avoid
- Mixing too much business logic inside a Route Handler
- Returning raw data without structure
- Forgetting input validation
- Inconsistent status codes
Conclusion
A good API isn't just one that "works," but one that's easy to understand, easy to test, and easy to change.
If your Route Handlers are starting to feel messy, try starting with a consistent response format + Zod validation first. That's usually enough to make a big difference.
A question for you all: How do you structure your API in Next.js these days? Pure Route Handlers, or do you have a separate service layer?
Share your thoughts in the comments!
— Ady Rahmansyah
Software Engineer | Tech Blogger | Coffee Addict