To chain multiple pieces of middleware for specific route in Node.js Express, we put the middlewares in an array.
For instance, we write
const middleware = {
requireAuthentication: (req, res, next) => {
console.log("private route list!");
next();
},
logger: (req, res, next) => {
console.log("Original request hit : " + req.originalUrl);
next();
},
};
app.get(
"/",
[middleware.requireAuthentication, middleware.logger],
(req, res) => {
res.send("Hello!");
}
);
to add the middlewares into the middleware
object.
Then we call app.get
with an array with the middlewares as the 2nd argument to call them in the same order they’re listed before calling the route handler.