How to Structure an Express API: Routes, Controllers, Services and Error Handling
By Muhammad Osama Khan, Software Engineer. APIs, Oct 20, 2026, 4 min read.
Keep routes thin, put business rules in services, validate input at the edge and handle every error in one place.
An Express app starts as one file and ends as a tangle of route handlers that parse input, run business rules, talk to the database and format errors all at once. A little structure early on keeps it testable and keeps changes local.
Folders and responsibilities
server/
src/
app.js create the Express app (no listen here, so tests can import it)
server.js connect to MongoDB, then app.listen
routes/ URL + method -> controller, plus validation middleware
controllers/ read the request, call a service, send the response
services/ business rules and database access
models/ Mongoose schemas
middleware/ auth, validate, error handler
utils/AppError.js an error that carries an HTTP status- Routes only wire things together. No logic.
- Controllers know about
reqandres, nothing else. - Services know nothing about HTTP. They take plain values and return plain values, which makes them easy to unit-test and to reuse from a script or a job.
An error type and one error handler
Throw an AppError anywhere, and let a single middleware turn it into a JSON response. Unknown errors become a generic 500, so stack traces and database messages never reach the client.
src/utils/AppError.js
export class AppError extends Error {
constructor(status, message, details) {
super(message);
this.status = status;
this.details = details;
}
}src/middleware/errorHandler.js
import { AppError } from '../utils/AppError.js';
export const notFound = (req, res) => {
res.status(404).json({ message: 'Route not found' });
};
// four arguments: this is how Express recognises an error handler
export const errorHandler = (err, req, res, next) => {
if (err instanceof AppError) {
return res.status(err.status).json({ message: err.message, details: err.details });
}
if (err.name === 'CastError') {
return res.status(400).json({ message: 'Invalid id' });
}
console.error(err);
res.status(500).json({ message: 'Something went wrong' });
};Validate input at the edge
Reject bad input before it reaches a service. A schema library such as zod keeps the rules in one place and gives you typed, trimmed data.
src/middleware/validate.js
import { AppError } from '../utils/AppError.js';
export const validate = (schema) => (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
throw new AppError(400, 'Validation failed', result.error.flatten().fieldErrors);
}
req.body = result.data; // the cleaned values
next();
};Putting one feature together
src/routes/tasks.js
import { Router } from 'express';
import { z } from 'zod';
import { requireAuth } from '../middleware/requireAuth.js';
import { validate } from '../middleware/validate.js';
import * as tasks from '../controllers/tasks.js';
const createTask = z.object({
title: z.string().trim().min(1).max(120),
dueDate: z.coerce.date().optional()
});
const router = Router();
router.use(requireAuth);
router.get('/', tasks.list);
router.post('/', validate(createTask), tasks.create);
export default router;src/controllers/tasks.js
import * as taskService from '../services/tasks.js';
export const list = async (req, res) => {
res.json(await taskService.listForUser(req.user.sub));
};
export const create = async (req, res) => {
const task = await taskService.create(req.user.sub, req.body);
res.status(201).json(task);
};src/services/tasks.js
import Task from '../models/Task.js';
import { AppError } from '../utils/AppError.js';
export const listForUser = (userId) => Task.find({ owner: userId }).sort({ createdAt: -1 }).lean();
export const create = async (userId, data) => {
const open = await Task.countDocuments({ owner: userId, done: false });
if (open >= 200) throw new AppError(409, 'Too many open tasks'); // a business rule lives here
return Task.create({ ...data, owner: userId });
};src/app.js
import express from 'express';
import taskRoutes from './routes/tasks.js';
import { notFound, errorHandler } from './middleware/errorHandler.js';
const app = express();
app.use(express.json({ limit: '100kb' }));
app.get('/api/health', (req, res) => res.json({ ok: true }));
app.use('/api/tasks', taskRoutes);
app.use(notFound); // after every route
app.use(errorHandler); // always last
export default app;Why this pays off
Because app.js does not call listen, a test can import the app and call it with a tool like Supertest. Because services are plain functions, the rules can be tested without HTTP. And because every error ends up in one place, the API always answers with the same JSON shape, which makes the React side simpler too.
Frequently asked questions
What is a good folder structure for an Express API?
Split by responsibility: routes map URLs to controllers, controllers handle req and res, services hold business rules and database access, plus models and middleware. Create the app in app.js and call listen in a separate server.js so tests can import the app.
How do I handle errors in Express?
Throw an error type that carries an HTTP status (for example AppError) and register one error-handling middleware, with four arguments, after all routes. Known errors return their status and message; anything unexpected returns a generic 500 without exposing internals.
Does Express catch errors in async route handlers?
Express 5 forwards a rejected promise from an async handler to the error handler automatically. On Express 4 you need a small wrapper or a package such as express-async-errors, otherwise the request can hang.
Where should request validation go in Express?
At the edge, in a middleware that runs before the controller. A schema library such as zod keeps the rules in one place, rejects bad input with a 400, and passes cleaned data to the rest of the code.