Search code examples
node.jsexpressmiddleware

How to dynamically decide if a request should go thru a middleware in Express


All:

I am pretty new to Epxress, I build a middleware to check user credential, and I specify it like:

var check = function(req, res, next){/* checking user cred*/}

And I use it like:

app.use(check);

OR like:

app.get("some url", check, function(req, res, next){})

But there is only one thing confuses me, sometimes, I need to skip the check in same handler depends on req.query, I wonder if there is a way(or design pattern) to do this without specify this condition checking inside check middleware( I just want to make check modulized and focus on its biz logic)?

Thanks


Solution

  • For authentication, a typical pattern would be to have a collection of routes that allow anonymous access, and a section that requires authentication, thus calls your middleware.

    Additionally, look into the Passport library for your authentication concerns, it integrates really well into express.