Advanced patterns for developing custom Express middleware
Middleware functions are the backbone of Express applications. Understanding advanced middleware patterns allows you to write more maintainable, reusable, and powerful code.
Middleware functions have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle.
function middleware(req, res, next) { // Perform operations next(); // Pass control to the next middleware}
Chain multiple middleware functions to handle complex operations step by step.
1
Load Resource
First middleware loads the resource from the database
function loadUser(req, res, next) { var user = users[req.params.id]; if (user) { req.user = user; next(); } else { next(new Error('Failed to load user ' + req.params.id)); }}
2
Check Permissions
Second middleware validates permissions
function restrictToSelf(req, res, next) { if (req.authenticatedUser.id === req.user.id) { next(); } else { next(new Error('Unauthorized')); }}
Error-handling middleware must have four arguments: (err, req, res, next).
function errorHandler(err, req, res, next) { // Log the error console.error(err.stack); // Respond with error res.status(500); res.send('Internal Server Error');}// Must be placed after all routesapp.use(errorHandler);
Error-handling middleware must be defined after all other middleware and routes to catch errors properly.