Chaining Middleware
Middleware functions can be chained together using the next()
function to execute multiple middleware functions in a specific order. This allows for modularization and reusability of middleware logic across different routes and applications.
// Middleware for authentication
const authenticateMiddleware = (req, res, next) => {
if (req.headers.authorization === 'Bearer token') {
next(); // Proceed to the next middleware
} else {
res.status(401).send('Unauthorized');
}
};
// Middleware for logging
const loggerMiddleware = (req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Proceed to the next middleware
};
// Apply middleware to specific routes
app.get('/protected', authenticateMiddleware, loggerMiddleware, (req, res) => {
res.send('Protected Route');
});
Explain the concept of middleware in NodeJS
Middleware in NodeJS refers to a software design pattern where functions are invoked sequentially in a pipeline to handle requests and responses in web applications. It acts as an intermediary layer between the client and the server, allowing for modularization of request processing logic and enabling cross-cutting concerns such as authentication, logging, error handling, and data transformation. Let’s delve deeper into the concept of middleware in NodeJS.