Building a Production-Ready REST API with Node.js and Express
A well-structured REST API is the backbone of modern web applications. This guide walks through building an Express API that is testable, secure, and ready for production traffic.
1. Project Structure
Organize your code by feature, not by type. Keep routes, controllers, and models for each resource in the same directory.
src/
routes/
users.ts
posts.ts
controllers/
users.ts
posts.ts
middleware/
auth.ts
errorHandler.ts
2. Middleware Chain
Express middleware runs in order. Place authentication, logging, and body parsing early in the chain so every route benefits automatically.
import express from 'express';
import { authMiddleware } from './middleware/auth';
import { errorHandler } from './middleware/errorHandler';
const app = express();
app.use(express.json());
app.use(authMiddleware);
app.use(errorHandler);
3. Error Handling
Create a centralized error handler middleware. Throw AppError instances with status codes in controllers, and let the handler format consistent JSON responses.
4. Rate Limiting
Protect your API from abuse with rate limiting. Use express-rate-limit to cap requests per IP address per time window.
5. Environment Configuration
Use dotenv for local development and inject environment variables in production. Never hardcode secrets or database URLs in your source code.