node.jsexpressjwtaopaccess-token

Authenticating the request header with Express


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?


Solution

  • 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.