Use specific middleware in Express for all paths except a specific one

I would add checkUser middleware to all my paths, except homepage.

app.get("https://stackoverflow.com/", routes.index);
app.get('/account', checkUser, routes.account);

or

app.all('*', checkUser);
    
function checkUser(req, res, next) {
  if ( req.path == "https://stackoverflow.com/") return next();

  //authenticate user
  next();
}

You could extend this to search for the req.path in an array of non-authenticated paths:

function checkUser(req, res, next) {
  const nonSecurePaths = ["https://stackoverflow.com/", '/about', '/contact'];
  if (nonSecurePaths.includes(req.path)) return next();

  //authenticate user
  next();
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)