Dive into Express.js middleware—learn what it is, how it works, its types, and how to write your own for powerful web application development.
Table of content
Middleware in Express.js is a cornerstone concept for building robust web applications. Simply put, middleware are functions that have access to the request
, response
objects, and the next()
function in your Express app. They can execute code, modify the request and response, end the request-response cycle, or call the next middleware in the stack.
In every HTTP request, Express runs through a chain of middleware functions. The order in which you declare these functions is crucial, as each one either passes control to the next via next()
or ends the cycle by sending a response.
app.use((req, res, next) => {
console.log('Middleware executed!');
next();
});
app
instance, used across your entire application.express.Router()
to modularize and manage routes.express.json()
, express.static()
).morgan
(logger), body-parser
, or cors
, installed via npm.(err, req, res, next)
—for tracking and responding to application errors.app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
It’s easy to build powerful, custom middleware functions for tasks like authentication, logging, or data validation. Here’s a basic example for request time logging:
function requestTime(req, res, next) {
req.requestTime = Date.now();
next();
}
app.use(requestTime);
app.get('/', (req, res) => {
res.send(`Requested at: ${req.requestTime}`);
});
next()
to pass control except when sending a response.Understanding middleware is essential for developing scalable and maintainable applications in Express.js. By mastering middleware, you unlock the ability to customize your app’s request/response cycle, enforce security, and keep code organized. Dive deeper, experiment with custom middleware, and stay curious for the best results in your web development journey!