Search code examples
node.jsexpressmiddlewarenode.js-connect

How to use 'this' context in middleware


I wrote my own middleware as module for my purposes that looks like the following:

-- myMiddleware.js

module.exports = {
    fn1: function (req, res, next) {
       console.log('fn1');
       next();
    },

    fn2: function (req, res, next) {
        console.log('fn2');
        this.fn1(req, res, function () {
             next();
        });
    }
};

In my sserver.js I use this middleware as the following:

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));

app.use(require('./myMiddleware').fn2);

Unfortunately that does not work because this context in fn2 in not myMiddleware.js object. How can use proper this?


Solution

  • You can't, the 'this' property will always be the vanilla Server (http.Server) instance or compatible handler.

    You can do this:

    var middlewares = {};
    
    module.exports = middlewares;
    
    middlewares.fn1 = function(req, res, next){ ... };
    
    middlewares.fn2 = function(req, res, next){ 
        middlewares.fn1(req, res, next); 
    };