Explain the concept of middleware execution order in a request processing chain.
sobes.tech AI
Answer from AI
In Node.js (for example, in Express), middleware are functions that process requests sequentially in a chain. The order of their execution is determined by how they are registered in the application: the first middleware is called first, then the next, and so on.
Each middleware receives request (req), response (res), and next function objects. To pass control to the next middleware, you need to call next(). If next() is not called, the chain is interrupted, and subsequent middleware are not executed.
Thus, the order of middleware registration is critical, as it determines the sequence of request processing. For example, logging middleware is usually placed at the beginning, and route handlers at the end.
Example:
app.use((req, res, next) => {
console.log('Logging request');
next();
});
app.use((req, res, next) => {
if (!req.user) {
return res.status(401).send('Unauthorized');
}
next();
});
app.get('/profile', (req, res) => {
res.send('User profile');
});
Here, logging occurs first, then authorization check, and only then the route handler.