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

95,408

Solution 1

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

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

or

app.all('*', checkUser);
    
function checkUser(req, res, next) {
  if ( req.path == '/') 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 = ['/', '/about', '/contact'];
  if (nonSecurePaths.includes(req.path)) return next();

  //authenticate user
  next();
}

Solution 2

You can set the middleware on each route also.

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  res.send('welcome, ' + req.body.username)
})

Solution 3

Instead of directly registering User.checkUser as middleware, register a new helper function, say checkUserFilter, that gets called on every URL, but passed execution to userFiled` only on given URLs. Example:

var checkUserFilter = function(req, res, next) {
    if(req._parsedUrl.pathname === '/') {
        next();
    } else {
        User.checkUser(req, res, next);
    }
}

app.use(checkUserFilter);

In theory, you could provide regexp paths to app.use. For instance something like:

app.use(/^\/.+$/, checkUser);

Tried it on express 3.0.0rc5, but it doesn't work.

Maybe we could open a new ticket and suggest this as a feature?

Solution 4

Use

app.use(/^(\/.+|(?!\/).*)$/, function(req, resp, next){...

This pass any url apart from /. Unless, it works for me.

In general

/^(\/path.+|(?!\/path).*)$/

(see How to negate specific word in regex?)

Hope this helps

Solution 5

The solution is to use order of setting api and middleware. In your case it must be something like this.

 var app = express.createServer(options);
    
    // put every api that you want to not use checkUser here and before setting User.checkUser
    app.use("/", (req, res) => res.send("checkUser middleware is not called"));
    
    
    app.use(User.checkUser);
    
    // put every api that you want use checkUser
    app.use("/userdata", User.checkUser, (req, res) =>
      res.send("checkUser called!")
    );

This is a full example.

const express = require("express");
const app = express();
const port = 3002;

app.get("/", (req, res) => res.send("hi"));

app.use((req, res, next) => {
  console.log("check user");
  next();
});

app.get("/checkedAPI", (req, res) => res.send("checkUser called"));

app.listen(port, () => {
  console.log(`Server started at port ${port}`);
});
Share:
95,408
Thomas
Author by

Thomas

I am an Informatics scientist interested in machine learning and NLP technology.

Updated on June 11, 2021

Comments

  • Thomas
    Thomas almost 3 years

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

    var app = express.createServer(options);
    app.use(User.checkUser);
    

    I can use the .use 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);
    

    So User.checkUser is always called except for the root path.

  • Thomas
    Thomas over 11 years
    Is it possible to allow all request to a specific path, but not the sub-paths? (i.e. '/', '/style.css', '/background.jpg', but not '/lists/' or '/titles')
  • chovy
    chovy over 11 years
    your static assets should be served out of a static directory.
  • Riz-waan
    Riz-waan over 3 years
    I think this is only supported from v4.
  • Ladu anand
    Ladu anand about 2 years
    @chovy How do I specify regex paths in nonSecurePaths and it works
  • chovy
    chovy about 2 years
    I'm not sure what you're asking @la