Thomas Thomas - 1 year ago 76
Node.js Question

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

I am using the Express framework in node.js with some middleware functions:

var app = express.createServer(options);

I can use the
function with an additional parameter to use this middleware only on specific paths:

app.use('/userdata', User.checkUser);

Is it possible to use the path variable so that the middleware is used for all paths except a specific one, i.e. the root path?

I am thinking about something like this:

app.use('!/', User.checkUser);

is always called except for the root path.

Answer Source

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

app.get('/', routes.index);
app.get('/account', checkUser, routes.account);


app.all('*', checkUser);

function checkUser(req, res, next) {
  if ( req.path == '/') return next();

  //authenticate user

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

function checkUser(req, res, next) {
  var _ = require('underscore')
      , nonSecurePaths = ['/', '/about', '/contact'];

  if ( _.contains(nonSecurePaths, req.path) ) return next();

  //authenticate user
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download