Express.js: Scalable Backend Architecture
Express is unopinionated, which is both a blessing and a curse. In a professional environment, we use structured patterns like MVC or Clean Architecture.
Middleware: The Heart of Express
Middleware are functions that have access to the Request and Response objects. They can execute code, modify the request, or end the cycle.
javascript code// A custom logging middleware const logger = (req, res, next) => { console.log(`${req.method} ${req.url} - ${new Date()}`); next(); // Critical: pass control to the next middleware }; app.use(logger);
Advanced Routing Strategies
Don't dump 50 routes in app.js. Use express.Router to modularize your code.
javascript code// routes/userRoutes.js const router = express.Router(); router.get('/profile', authMiddleware, userController.getProfile); router.post('/register', validationMiddleware, userController.register); module.exports = router;
Error Handling Pattern
The correct way to handle errors in Express is through a centralized error handler.
javascript code// Generic Error Class class AppError extends Error { constructor(message, statusCode) { super(message); this.statusCode = statusCode; this.isOperational = true; } } // Global Error Handler (Last middleware in app.js) app.use((err, req, res, next) => { res.status(err.statusCode || 500).json({ status: 'error', message: err.message }); });
Async Error Handling
In Express 4, you must wrap async routes in a try/catch or a helper to catch rejected promises. Express 5 (currently in beta) handles this automatically.