Categories
JavaScript Answers

How to use specific middleware in Express for all paths except a specific one with Node.js?

Spread the love

To use specific middleware in Express for all paths except a specific one with Node.js, we can check the path of the request in the middleware function.

For instance, we write

const checkUser = (req, res, next) => {
  if (req.path == "/") {
    return next();
  }
  next();
};

app.all("*", checkUser);

to call app.all to add the checkUser middleware for all routes.

In checkUser, we check the path of the request with req.path.

If it’s '/', we call the next middleware with next and return to end the execution of checkUser.

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 *