nodejs Express framework this keyword

My app.js looks like this :

var expressJwt = require('express-jwt');
var session = require('redis-sessions');
app.use('/events', expressJwt({secret: secret}), session.verifyToken, events);

session.verifyToken is a custom modue for redis db to check to see if the token has expired.

All the test I wrote for my module work, so session.verifyToken works when I test it from mocha.

//verifyToke function        
RedisSessions.prototype.verifyToken = function(req, res, next){
    var token = this.extractToken( req.headers['authorization'] );
this.containsToken(token, function(err, contains){
    if(contains == 1){
        next();
    }else{
        res.send(401);
    }
});
}

and In the end I export my RedisSession module like this:

module.exports = new RedisSessions();

But, when the request is coming in through express I get a 500 internal error on this line.

var token = this.extractToken( req.headers['authorization'] );

The thing is, the scope of the this keyword is totally off, in the scope there should be only my RedisSessions object, but instead is the hole express framework.

Can anyone pls explain why is the this keyword off?

When you pass session.verifyToken to app.use() like that, you're passing the bare function. It does not have any context bound to it.

Here are two solutions to fix this:

function verifyToken(req, res, next) {
  session.verifyToken(req, res, next);
}
app.use('/events', expressJwt({secret: secret}), verifyToken, events);

or

app.use('/events', expressJwt({secret: secret}), session.verifyToken.bind(session), events);