Building Maintainable Express.js APIs: Architecture, Validation, Error Handling, and Best Practices
Express.js is one of the most popular frameworks for building backend applications with Node.js.
Its minimal design makes it easy to create REST APIs, connect databases, implement authentication, and integrate third-party services.
However, as an application grows, a simple Express project can quickly become difficult to maintain.
You might start with a few routes and controllers. A few months later, those files may contain database queries, authentication logic, validation rules, business rules, and error handling all mixed together.
This creates several problems:
- Difficult-to-maintain code.
- Duplicated business logic.
- Inconsistent API responses.
- Complicated testing.
- Poor error handling.
- Security vulnerabilities.
- Difficult collaboration between developers.
Building a production-ready API isn't just about making endpoints work. It's about organizing the application so that it remains understandable, testable, secure, and scalable as requirements change.
In this guide, we'll explore a practical architecture for Express.js applications and implement the important components using Node.js, Express, MongoDB, Mongoose, and Zod.
1. Understanding Express.js API Architecture
Express.js provides routing and middleware functionality, but it doesn't enforce a particular application architecture.
You can organize your application in many different ways.
For a small project, keeping everything in a few files might be sufficient. However, for applications with multiple features and business rules, separating responsibilities becomes important.
Consider an API endpoint that creates a new job listing.
A poorly structured controller might look like this:
router.post("/jobs", async (req, res) => {
const { title, description, salary } = req.body;
if (!title || !description) {
return res.status(400).json({
message: "Missing required fields"
});
}
const company = await Company.findById(req.user.companyId);
if (!company) {
return res.status(404).json({
message: "Company not found"
});
}
const job = await Job.create({
title,
description,
salary,
company: company._id
});
res.status(201).json(job);
});
This works for a simple example, but the controller is responsible for several different things:
- Reading request data.
- Validating input.
- Checking business requirements.
- Retrieving database records.
- Creating database records.
- Sending the HTTP response.
As the application grows, this approach becomes difficult to maintain.
A better approach is to separate these responsibilities.
Recommended architecture
A practical Express application can use the following layers:
| Layer | Responsibility |
|---|---|
| Routes | Define API endpoints and middleware |
| Controllers | Handle HTTP requests and responses |
| Services | Implement application business logic |
| Repositories | Encapsulate database operations |
| Models | Define database schemas |
| Validators | Validate incoming data |
| Middleware | Handle authentication, authorization, and request processing |
| Utilities | Provide reusable helper functions |
| Config | Manage application configuration |
The request flow looks like this:
Client Request
|
v
Express App
|
v
Middleware
|
v
Routes
|
v
Validation
|
v
Controller
|
v
Service
|
v
Repository
|
v
Database
|
v
Service Result
|
v
Controller
|
v
JSON Response
Not every project needs a separate repository layer. For smaller applications, services can interact directly with Mongoose models.
The goal isn't to create as many folders as possible. It's to establish clear responsibilities and avoid mixing unrelated concerns.
2. Organizing a Production-Oriented Express Project
Let's create a practical folder structure for an Express application.
src/
├── config/
│ ├── database.js
│ ├── environment.js
│ └── logger.js
│
├── middleware/
│ ├── authenticate.js
│ ├── authorize.js
│ ├── validate.js
│ ├── notFound.js
│ └── errorHandler.js
│
├── modules/
│ └── jobs/
│ ├── job.model.js
│ ├── job.routes.js
│ ├── job.controller.js
│ ├── job.service.js
│ ├── job.repository.js
│ └── job.validation.js
│
├── utils/
│ ├── ApiError.js
│ ├── asyncHandler.js
│ └── response.js
│
├── app.js
└── server.js
tests/
├── integration/
└── unit/
.env
.gitignore
package.json
This example uses a feature-based structure.
Instead of placing every controller in one global directory, related files are grouped inside their respective modules.
For example, everything related to job listings lives inside modules/jobs/.
This provides several advantages:
- Related code is easier to locate.
- Features can be developed independently.
- Large projects become easier to navigate.
- Testing individual modules becomes simpler.
- New developers can understand the application structure more quickly.
Feature-based vs layer-based organization
A traditional layer-based structure might look like:
controllers/
services/
models/
routes/
validators/
This works well for smaller projects.
However, when an application contains many features, individual modules become scattered across multiple directories.
A feature-based structure keeps related files together:
modules/
├── users/
├── jobs/
├── companies/
├── applications/
└── notifications/
For medium and large applications, feature-based organization is often easier to maintain.
3. Separating Routes, Controllers, and Services
Let's implement a job management module to understand how these layers work together.
Step 1: Create the Mongoose model
Create modules/jobs/job.model.js:
import mongoose from "mongoose";
const jobSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true
},
description: {
type: String,
required: true
},
salary: {
type: Number,
min: 0
},
status: {
type: String,
enum: ["draft", "published", "closed"],
default: "draft"
},
company: {
type: mongoose.Schema.Types.ObjectId,
ref: "Company",
required: true,
index: true
}
},
{
timestamps: true
}
);
export default mongoose.model("Job", jobSchema);
The model defines the structure of job documents and their database-level validation rules.
Step 2: Create a repository
Create modules/jobs/job.repository.js:
import Job from "./job.model.js";
export const jobRepository = {
create(data) {
return Job.create(data);
},
findById(id) {
return Job.findById(id);
},
findByCompany(companyId) {
return Job.find({
company: companyId
}).sort({ createdAt: -1 });
},
updateById(id, data) {
return Job.findByIdAndUpdate(
id,
data,
{
new: true,
runValidators: true
}
);
},
deleteById(id) {
return Job.findByIdAndDelete(id);
}
};
The repository encapsulates database operations.
Instead of writing Mongoose queries inside every controller, you can reuse these methods.
This layer becomes particularly useful when database access is complex or when multiple services share the same data-access logic.
Step 3: Create a service
Create modules/jobs/job.service.js:
import { jobRepository } from "./job.repository.js";
import ApiError from "../../utils/ApiError.js";
export const jobService = {
async createJob(data, companyId) {
const job = await jobRepository.create({
...data,
company: companyId
});
return job;
},
async getJobById(id) {
const job = await jobRepository.findById(id);
if (!job) {
throw new ApiError(404, "Job not found");
}
return job;
},
async getCompanyJobs(companyId) {
return jobRepository.findByCompany(companyId);
},
async updateJob(id, companyId, data) {
const existingJob = await jobRepository.findById(id);
if (!existingJob) {
throw new ApiError(404, "Job not found");
}
if (existingJob.company.toString() !== companyId.toString()) {
throw new ApiError(403, "You cannot modify this job");
}
return jobRepository.updateById(id, data);
}
};
The service contains application business logic.
For example, checking whether a company owns a job is a business rule, not an HTTP routing responsibility.
The service can be reused by different controllers, background workers, or other application components.
Step 4: Create a controller
Create modules/jobs/job.controller.js:
import { jobService } from "./job.service.js";
export const jobController = {
async createJob(req, res) {
const job = await jobService.createJob(
req.validated.body,
req.user.companyId
);
res.status(201).json({
success: true,
data: job
});
},
async getJob(req, res) {
const job = await jobService.getJobById(
req.validated.params.id
);
res.status(200).json({
success: true,
data: job
});
},
async getCompanyJobs(req, res) {
const jobs = await jobService.getCompanyJobs(
req.user.companyId
);
res.status(200).json({
success: true,
data: jobs
});
}
};
The controller now focuses on HTTP-related responsibilities:
- Reading validated request data.
- Calling the service.
- Returning the response.
It doesn't need to know how the database query is implemented.
Step 5: Define routes
Create modules/jobs/job.routes.js:
import { Router } from "express";
import { jobController } from "./job.controller.js";
import { authenticate } from "../../middleware/authenticate.js";
import { validate } from "../../middleware/validate.js";
import {
createJobSchema,
getJobSchema
} from "./job.validation.js";
const router = Router();
router.post(
"/",
authenticate,
validate(createJobSchema),
jobController.createJob
);
router.get(
"/:id",
validate(getJobSchema),
jobController.getJob
);
router.get(
"/company",
authenticate,
jobController.getCompanyJobs
);
export default router;
Finally, mount the module inside the main application.
import jobRoutes from "./modules/jobs/job.routes.js";
app.use("/api/v1/jobs", jobRoutes);
The API structure is now separated into manageable components.
4. Request Validation with Zod
One of the most important responsibilities of a backend API is validating incoming data.
Never assume that data received from the frontend is valid.
Even if your React application validates every form field, users can bypass frontend validation by sending requests directly through tools such as Postman, curl, or browser developer tools.
Consider this request:
{
"title": "",
"salary": -50000,
"status": "super-admin"
}
Without proper validation, unexpected values can reach your application logic.
This can lead to incorrect database records and security problems.
Why use a validation library?
You could manually validate every field:
if (!req.body.title) {
return res.status(400).json({
message: "Title is required"
});
}
But manually validating complex objects becomes repetitive.
Libraries such as Zod, Joi, and express-validator provide structured validation.
In this guide, we'll use Zod.
Install it:
npm install zod
Create a validation schema
Create modules/jobs/job.validation.js:
import { z } from "zod";
export const createJobSchema = z.object({
body: z.object({
title: z.string()
.trim()
.min(3, "Title must contain at least 3 characters")
.max(100),
description: z.string()
.trim()
.min(20, "Description must contain at least 20 characters"),
salary: z.number()
.nonnegative()
.optional(),
status: z.enum([
"draft",
"published",
"closed"
]).optional()
}).strict()
});
export const getJobSchema = z.object({
params: z.object({
id: z.string()
.regex(/^[a-f\d]{24}$/i, "Invalid job ID")
})
});
Here, .strict() rejects unexpected object properties instead of silently accepting them.
This is useful when you don't want clients to submit fields such as company, owner, or internal administrative properties.
Create reusable validation middleware
Create middleware/validate.js:
import ApiError from "../utils/ApiError.js";
export function validate(schema) {
return (req, res, next) => {
const result = schema.safeParse({
body: req.body,
params: req.params,
query: req.query
});
if (!result.success) {
const errors = result.error.issues.map((issue) => ({
field: issue.path.join("."),
message: issue.message
}));
return next(
new ApiError(
400,
"Request validation failed",
errors
)
);
}
req.validated = result.data;
next();
};
}
The middleware validates the request before it reaches the controller.
Why use safeParse()?
Zod provides two common parsing methods:
parse():
const data = schema.parse(req.body);
Throws a validation error when the input is invalid.
safeParse():
const result = schema.safeParse(req.body);
Returns a result object indicating whether validation succeeded.
For reusable Express validation middleware, safeParse() is convenient because it allows you to convert validation failures into your application's standard error format.
Important: Validate query parameters too
Query parameters usually arrive as strings.
For example:
GET /api/v1/jobs?page=2&limit=20
You can use Zod coercion:
import { z } from "zod";
export const paginationSchema = z.object({
query: z.object({
page: z.coerce.number()
.int()
.min(1)
.default(1),
limit: z.coerce.number()
.int()
.min(1)
.max(100)
.default(20)
})
});
This ensures that pagination values are converted and validated before reaching the database layer.
5. Centralized Error Handling
Error handling is another major part of maintainable Express applications.
Without a centralized approach, every controller may return errors differently.
For example:
res.status(404).json({
message: "User not found"
});
Another controller might return:
res.status(400).json({
error: "Invalid request"
});
And another might accidentally expose internal error details.
A centralized error-handling system provides consistent responses and makes debugging easier.
Step 1: Create a custom API error class
Create utils/ApiError.js:
export default class ApiError extends Error {
constructor(statusCode, message, details = null) {
super(message);
this.statusCode = statusCode;
this.details = details;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
Now you can create application errors:
throw new ApiError(404, "Job not found");
Or validation errors:
throw new ApiError(
400,
"Validation failed",
[
{
field: "title",
message: "Title is required"
}
]
);
Step 2: Create an asynchronous handler utility
Express 5 automatically forwards rejected promises from async route handlers and middleware to error-handling middleware.
If you're using Express 4, an async wrapper can simplify error propagation.
Create utils/asyncHandler.js:
const asyncHandler = (handler) => {
return (req, res, next) => {
Promise.resolve(handler(req, res, next))
.catch(next);
};
};
export default asyncHandler;
For Express 4, use it around asynchronous handlers:
router.get(
"/:id",
asyncHandler(jobController.getJob)
);
For Express 5, this wrapper is generally unnecessary for standard promise-returning handlers.
Step 3: Create centralized error middleware
Create middleware/errorHandler.js:
import ApiError from "../utils/ApiError.js";
export function notFound(req, res, next) {
next(
new ApiError(
404,
`Route not found: ${req.method} ${req.originalUrl}`
)
);
}
export function errorHandler(err, req, res, next) {
if (res.headersSent) {
return next(err);
}
let statusCode = err.statusCode || err.status || 500;
let message = err.message || "Internal server error";
let details = err.details || null;
if (err.name === "ValidationError") {
statusCode = 400;
message = "Database validation failed";
details = Object.values(err.errors).map((error) => ({
field: error.path,
message: error.message
}));
}
if (err.name === "CastError") {
statusCode = 400;
message = "Invalid resource identifier";
}
if (err.code === 11000) {
statusCode = 409;
message = "A record with this value already exists";
}
if (!Number.isInteger(statusCode) || statusCode < 400 || statusCode > 599) {
statusCode = 500;
}
const isProduction = process.env.NODE_ENV === "production";
if (statusCode >= 500) {
console.error(err);
}
res.status(statusCode).json({
success: false,
message: statusCode >= 500 && isProduction
? "Internal server error"
: message,
...(details && { errors: details }),
...(!isProduction && {
stack: err.stack
})
});
}
This example maps common Mongoose errors to appropriate HTTP responses.
In production, you should use structured logging instead of relying on console.error(), and avoid returning stack traces or internal database details to clients.
Step 4: Register middleware in the correct order
The error handler must be registered after routes and other middleware.
Inside app.js:
import express from "express";
import jobRoutes from "./modules/jobs/job.routes.js";
import {
notFound,
errorHandler
} from "./middleware/errorHandler.js";
const app = express();
app.use(express.json());
app.use("/api/v1/jobs", jobRoutes);
app.use(notFound);
app.use(errorHandler);
export default app;
The order matters because Express processes middleware in registration order.
The notFound middleware handles requests that don't match an existing route. The error handler handles errors passed through the middleware chain.
6. Understanding HTTP Status Codes
A well-designed REST API should use appropriate HTTP status codes.
Returning 200 OK for every response makes client-side error handling unnecessarily difficult.
Here are commonly used status codes:
| Status | Meaning | Example |
|---|---|---|
| 200 | OK | Successful GET or update |
| 201 | Created | Resource created |
| 202 | Accepted | Background operation accepted |
| 204 | No Content | Successful deletion without response body |
| 400 | Bad Request | Invalid request data |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Duplicate or conflicting resource |
| 413 | Content Too Large | Request body exceeds limit |
| 415 | Unsupported Media Type | Unsupported request content type |
| 422 | Unprocessable Content | Semantically invalid request |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server failure |
| 503 | Service Unavailable | Temporary service unavailability |
The exact status code should reflect the API contract and the reason the request failed.
For example, a malformed JSON request can produce 400, while a valid JSON document that violates a semantic business rule might produce 422.
Consistency across endpoints is more important than choosing between equivalent conventions without a documented reason.
7. Authentication and Authorization Middleware
Authentication and authorization should be implemented separately from business logic.
Authentication determines who is making the request.
Authorization determines whether that user can perform the requested action.
For example:
Client Request
|
v
Authentication
|
v
Authorization
|
v
Request Validation
|
v
Controller
Authentication middleware
A simplified JWT authentication middleware might look like this:
import jwt from "jsonwebtoken";
import ApiError from "../utils/ApiError.js";
export function authenticate(req, res, next) {
const authorization = req.headers.authorization;
if (!authorization?.startsWith("Bearer ")) {
return next(
new ApiError(401, "Authentication required")
);
}
try {
const token = authorization.slice(7);
const payload = jwt.verify(
token,
process.env.JWT_ACCESS_SECRET,
{
algorithms: ["HS256"],
issuer: "https://api.example.com",
audience: "https://example.com"
}
);
req.user = {
id: payload.sub,
role: payload.role
};
next();
} catch {
next(
new ApiError(401, "Invalid or expired access token")
);
}
}
This example assumes that the application issues JWTs with the specified algorithm, issuer, and audience.
Authorization middleware
import ApiError from "../utils/ApiError.js";
export function authorize(...roles) {
return (req, res, next) => {
if (!req.user) {
return next(
new ApiError(401, "Authentication required")
);
}
if (!roles.includes(req.user.role)) {
return next(
new ApiError(403, "Insufficient permissions")
);
}
next();
};
}
Protect an administrator route:
router.delete(
"/:id",
authenticate,
authorize("admin"),
deleteJob
);
Don't forget resource ownership
Role checks alone aren't sufficient.
For example, two recruiters may have the same role, but one recruiter shouldn't automatically be allowed to modify another recruiter's job listing.
Check resource ownership in the service layer:
if (job.company.toString() !== user.companyId.toString()) {
throw new ApiError(403, "Access denied");
}
For more details about JWT token management, read JWT Authentication in Production: Security Best Practices for Node.js Applications.
8. Secure Express.js APIs
A production API needs security controls at multiple levels.
Express provides middleware support that makes it possible to add security features without mixing them into every route.
Use Helmet
Helmet helps configure HTTP response headers that improve application security.
Install it:
npm install helmet
Configure it:
import helmet from "helmet";
app.use(helmet());
Helmet sets several security-related headers.
However, it isn't a replacement for authentication, authorization, input validation, or secure application logic.
Configure CORS correctly
Install the CORS middleware:
npm install cors
Configure allowed origins:
import cors from "cors";
app.use(cors({
origin: [
"https://example.com",
"https://www.example.com"
],
methods: [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE"
],
credentials: true
}));
For cookie-based authentication, configure credential handling carefully.
Don't use wildcard origins with credentialed requests.
CORS controls which browser origins can read cross-origin responses. It isn't an authentication or authorization mechanism.
Apply rate limiting
Authentication endpoints and expensive operations should be protected against excessive requests.
Install:
npm install express-rate-limit
Example:
import rateLimit from "express-rate-limit";
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10,
standardHeaders: "draft-8",
legacyHeaders: false,
message: {
success: false,
message: "Too many login attempts. Try again later."
}
});
app.use("/api/v1/auth/login", loginLimiter);
This example limits repeated login requests.
For a distributed deployment with multiple application instances, use an appropriate shared rate-limit store rather than relying on independent in-memory counters.
Limit request body size
Accepting unnecessarily large request bodies can consume server resources.
Configure reasonable limits:
app.use(express.json({
limit: "1mb"
}));
app.use(express.urlencoded({
extended: true,
limit: "1mb"
}));
Choose limits based on the actual requirements of your API.
Large file uploads should generally use a dedicated upload strategy rather than increasing the JSON body limit.
Avoid unsafe database queries
Never pass arbitrary client-controlled query objects directly into MongoDB.
Avoid:
const users = await User.find(req.query);
A client could submit unexpected query structures or operators.
Prefer an explicit allowlist:
const users = await User.find({
role: req.query.role,
isActive: true
});
Validate and normalize every query parameter before using it.
9. Logging and Monitoring
Logging is essential for understanding what happens inside a production API.
Without meaningful logs, diagnosing failed requests, database problems, and authentication issues becomes difficult.
However, logging every object or request indiscriminately can introduce security and performance problems.
Use structured logging
Instead of writing arbitrary console messages:
console.log("User logged in");
Use a structured logging library such as Pino.
Install:
npm install pino pino-http
Create config/logger.js:
import pino from "pino";
const logger = pino({
level: process.env.LOG_LEVEL || "info",
redact: {
paths: [
"req.headers.authorization",
"req.headers.cookie",
"res.headers.set-cookie",
"*.password",
"*.refreshToken",
"*.accessToken"
],
censor: "[REDACTED]"
}
});
export default logger;
Add HTTP logging:
import pinoHttp from "pino-http";
import logger from "./config/logger.js";
app.use(pinoHttp({
logger,
autoLogging: true
}));
Structured logs make it easier to search and analyze application events.
What should you log?
Useful events include:
- Incoming request method and path.
- Response status and duration.
- Authentication failures.
- Authorization failures.
- Validation failures.
- Database errors.
- Unexpected application errors.
- Important administrative actions.
Avoid logging:
- Passwords.
- Access tokens.
- Refresh tokens.
- Session secrets.
- Sensitive personal information.
- Full payment credentials.
Also consider request IDs or correlation IDs so that logs from related operations can be connected.
Monitoring
For production systems, combine application logs with metrics and error monitoring.
Useful metrics include:
- Request count.
- Error rate.
- Response latency.
- Database query duration.
- Memory usage.
- CPU usage.
- Active connections.
- Rate-limit rejections.
Tools such as OpenTelemetry can help instrument distributed applications and trace requests across multiple services.
10. API Versioning and Consistent Responses
As applications grow, API contracts change.
You may eventually need to introduce new fields, modify response structures, or change endpoint behavior.
API versioning helps manage these changes.
A common approach is URL-based versioning:
/api/v1/users
/api/v1/jobs
/api/v2/jobs
Example:
app.use("/api/v1/jobs", jobRoutesV1);
app.use("/api/v2/jobs", jobRoutesV2);
Not every internal change requires a new API version.
Version when you introduce changes that break existing client expectations.
Maintain a consistent response format
For example, a successful response:
{
"success": true,
"message": "Job created successfully",
"data": {
"id": "65f123456789abcdef123456",
"title": "Node.js Developer"
}
}
An error response:
{
"success": false,
"message": "Request validation failed",
"errors": [
{
"field": "title",
"message": "Title is required"
}
]
}
A consistent structure makes frontend integration easier.
However, don't create unnecessary abstractions just to wrap every response in multiple layers of objects.
Keep the API contract simple and document it clearly.
Use appropriate pagination
Avoid returning thousands of records in a single request.
For smaller datasets, offset-based pagination is straightforward:
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(
100,
Math.max(1, Number(req.query.limit) || 20)
);
const skip = (page - 1) * limit;
const [jobs, total] = await Promise.all([
Job.find({ status: "published" })
.sort({ createdAt: -1, _id: -1 })
.skip(skip)
.limit(limit),
Job.countDocuments({
status: "published"
})
]);
For large datasets or rapidly changing feeds, cursor-based pagination is often more efficient and predictable.
For example:
const jobs = await Job.find({
status: "published",
...(cursor && {
_id: { $lt: cursor }
})
})
.sort({ _id: -1 })
.limit(limit + 1);
A production cursor should be validated and tied to a deterministic sort order. For more complex sorting, encode all required sort values in the cursor.
11. Testing Express APIs
An API that works manually isn't necessarily reliable.
Automated testing helps detect regressions when business logic or database behavior changes.
Common testing levels include:
| Test type | Purpose |
|---|---|
| Unit tests | Test individual functions and services |
| Integration tests | Test components working together |
| API tests | Test HTTP endpoints |
| End-to-end tests | Test complete application workflows |
Install testing dependencies
npm install --save-dev vitest supertest
Vitest provides a testing framework, while Supertest allows you to make HTTP requests against an Express application.
Example API test
Assume your Express application exports app without starting a network listener.
Create tests/integration/jobs.test.js:
import { describe, it, expect } from "vitest";
import request from "supertest";
import app from "../../src/app.js";
describe("Jobs API", () => {
it("should return 404 for a non-existing job", async () => {
const response = await request(app)
.get("/api/v1/jobs/65f123456789abcdef123456");
expect(response.status).toBe(404);
expect(response.body.success).toBe(false);
expect(response.body.message).toBe("Job not found");
});
});
This test assumes the database test environment contains no matching job and that the route is configured to return a 404 response.
What should you test?
At minimum, test:
- Successful requests.
- Invalid request bodies.
- Missing authentication.
- Insufficient permissions.
- Non-existent resources.
- Duplicate records.
- Database failures.
- Pagination behavior.
- Resource ownership.
- Unexpected errors.
Use an isolated test database and clean up test data between tests.
Don't run destructive tests against production databases.
12. Database and Performance Best Practices
A well-organized API can still perform poorly if its database operations are inefficient.
Here are some important practices.
Use appropriate indexes
Indexes help MongoDB locate documents efficiently.
For example, if your API frequently retrieves published jobs by company:
jobSchema.index({
company: 1,
status: 1,
createdAt: -1
});
Index design should reflect actual query patterns.
Too many indexes can also increase storage usage and write overhead.
Select only required fields
Avoid retrieving unnecessary information.
const jobs = await Job.find({
status: "published"
})
.select("title salary company createdAt")
.lean();
Using .lean() returns plain JavaScript objects rather than full Mongoose documents, which can reduce overhead for read-only operations.
Avoid N+1 queries
An N+1 problem occurs when an application executes one query to retrieve a list and then additional queries for each record.
For example, retrieving 100 jobs and separately querying the company for each job can create unnecessary database traffic.
Depending on the use case, consider:
- Mongoose
populate(). - MongoDB aggregation with
$lookup. - Embedding small, frequently accessed data.
- Batching database operations.
Avoid unnecessary synchronous work
Node.js uses an event-driven execution model.
Long-running synchronous operations can block the event loop and delay unrelated requests.
Prefer asynchronous APIs for I/O operations and move CPU-intensive work to worker threads or separate services when appropriate.
13. Graceful Shutdown and Process Reliability
A production API should shut down cleanly when the process receives a termination signal.
This is particularly important when deploying with Docker, Kubernetes, PM2, or cloud infrastructure.
A graceful shutdown should:
- Stop accepting new HTTP connections.
- Allow active requests to finish within a reasonable deadline.
- Close database connections.
- Release other resources.
- Exit the process.
Example server.js:
import app from "./app.js";
import mongoose from "mongoose";
import logger from "./config/logger.js";
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => {
logger.info(`Server running on port ${PORT}`);
});
let shuttingDown = false;
async function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
logger.info({ signal }, "Starting graceful shutdown");
const forceExit = setTimeout(() => {
logger.error("Graceful shutdown timed out");
process.exit(1);
}, 10000);
forceExit.unref();
server.close(async (error) => {
try {
if (error) {
throw error;
}
await mongoose.disconnect();
clearTimeout(forceExit);
logger.info("Shutdown completed");
process.exit(0);
} catch (error) {
logger.error(error, "Shutdown failed");
process.exit(1);
}
});
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));
This is a simplified example. Production systems may also need to close Redis connections, message consumers, background workers, and other resources.
The important point is to avoid abruptly terminating a process while it is handling active work.
14. Common Express.js Architecture Mistakes
Even well-intentioned developers can introduce unnecessary complexity into their APIs.
Here are some mistakes worth avoiding.
1. Putting all business logic inside controllers
Controllers should handle HTTP concerns rather than becoming the home for every business rule.
Better approach: Move reusable business logic into services.
2. Creating too many abstraction layers
A repository, service, factory, adapter, and manager for every simple operation can make a small application unnecessarily complicated.
Better approach: Introduce abstractions when they solve a real maintenance or testing problem.
3. Trusting frontend validation
Frontend validation improves user experience but doesn't secure your API.
Better approach: Validate every incoming request on the backend.
4. Repeating error handling in every controller
This produces inconsistent responses and duplicated code.
Better approach: Use centralized error-handling middleware.
5. Returning database documents without considering the API contract
Database documents may contain internal fields that shouldn't be exposed.
Better approach: Return explicit response objects or DTOs containing only the fields the client needs.
6. Ignoring resource ownership
Checking whether a user has a valid role doesn't prove they own a particular resource.
Better approach: Enforce ownership checks in the service or authorization layer.
7. Using unlimited database queries
Returning every matching record can cause performance and memory problems.
Better approach: Use pagination, field selection, and query limits.
8. Logging sensitive information
Detailed logs can accidentally expose passwords, cookies, or access tokens.
Better approach: Use structured logging with explicit redaction rules.
9. Treating every error as an internal server error
Returning HTTP 500 for every failure makes it difficult for clients to handle expected conditions.
Better approach: Map known validation, authentication, authorization, and resource errors to appropriate status codes.
10. Ignoring API documentation
An API that works but has no clear documentation becomes difficult for frontend developers and external consumers to integrate.
Better approach: Maintain an OpenAPI specification and keep it synchronized with actual endpoint behavior.
15. Production Checklist
Before deploying an Express.js API, review the following checklist.
Architecture
- Routes, controllers, and services have clear responsibilities.
- Related functionality is organized into feature modules.
- Business rules aren't unnecessarily duplicated.
- Database access is organized consistently.
- Sensitive response fields are excluded.
Validation and errors
- Request bodies are validated.
- Route parameters are validated.
- Query parameters are validated.
- Unexpected properties are rejected where appropriate.
- Error responses follow a consistent format.
- Internal stack traces aren't exposed in production.
- Unknown routes return appropriate 404 responses.
Security
- Authentication is implemented on protected endpoints.
- Authorization checks are performed on the backend.
- Resource ownership is validated.
- Helmet is configured.
- CORS uses explicit trusted origins.
- Rate limiting protects sensitive endpoints.
- Request body sizes are limited.
- Database queries use validated and allowlisted inputs.
- Secrets are stored outside source control.
- HTTPS is enabled in production.
Performance and reliability
- Appropriate database indexes exist.
- Large responses are paginated.
- Database queries retrieve only necessary fields.
- Slow operations are monitored.
- Logs are structured and sensitive fields are redacted.
- Graceful shutdown is implemented.
- Automated tests cover important API behavior.
- API documentation is maintained.
Conclusion
Building maintainable Express.js APIs requires more than creating routes and connecting MongoDB.
A well-structured backend separates HTTP handling from business logic, validates every request, centralizes error handling, enforces authorization, and provides consistent API responses.
Feature-based organization, reusable middleware, structured logging, database optimization, and automated testing help applications remain manageable as their requirements grow.
However, good architecture doesn't mean introducing unnecessary abstractions.
Start with a clear structure, separate responsibilities where they genuinely belong, and add complexity only when your application needs it.
Remember: A production-ready API isn't simply an API that works today. It's an API that developers can understand, test, debug, secure, and extend tomorrow.



