Categories
JavaScript Answers

How to chain multiple pieces of middleware for specific route in Node.js Express?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *