Authenticating the request header with Express

kambi picture kambi · Sep 7, 2017 · Viewed 40.3k times · Source

I want to verify that all our get requests have a specific token in their authentication header.

I can add this to our get endpoints:

app.get('/events/country', function(req, res) {
    if (!req.headers.authorization) {
    return res.json({ error: 'No credentials sent!' });
    }

Is there any better way to handle this in NodeJS/Express without changing every endpoint? something like a before-filter/AOP approach?

Answer

robertklep picture robertklep · Sep 7, 2017

That's what middleware is for:

app.use(function(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(403).json({ error: 'No credentials sent!' });
  }
  next();
});

...all your protected routes...

Make sure that the middleware is declared before the routes to which the middleware should apply.