Search code examples
node.jsexpressnode.js-connect

Using Connect\Express middleware within custom middleware


Is it viable to use popular Connect middleware within your custom middleware?

For example, I'm writing some authentication middleware, which obviously relies quite heavily on Connect's cookieParser() and session methods. These methods are middleware, so they require request, response and next parameters to be passed. The obvious option is to simply make sure I'm adding them to the middleware stack before I add my authentication middleware like so:

app.js:

app.use(express.cookieParser('secret'))
   .use(express.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }}))
   .use(my_auth_middleware())

But this seems a bit cumbersome as my middleware relies on the first two methods in order to do stuff with the req.session.

The other obvious way to do it would be to pass the app into my middleware, and then call the cookieParser() and session methods within, but because they are both middleware I would have to add them to the stack, which feels wrong:

my_auth_middleware.js:

module.exports = function(app){

    app.use(express.cookieParser('secret'));
    app.use(express.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }}));

    return function(req, res, next){

        // do stuff with req.session

        next();

    }
}

Can anyone confirm that this is a logical way to do things? Is there an argument for keeping the cookieParser() and session methods out of my middleware?

Obviously I'm using Express in these examples, but I'm aware these methods originate from Connect.


Solution

  • I don't think there's anything wrong with your first setup. It's rather explicit (you could perhaps add a comment stating that my_auth_middleware() relies on the other two), and therefore pretty obvious to anyone looking at your code.

    Your second example almost hides the fact that the other two middleware are being used. They also move some of your applications' configuration (secrets and cookie name) to a separate file, which might be confusing. And personally I don't like passing app around.

    FWIW, express.session also needs express.cookieParser to work, but it leaves it up to the programmer to load it.