Is it possible to use validation with express static routes? Is it possible to use validation with express static routes? express express

Is it possible to use validation with express static routes?


Yes, you can attach an extra middleware to execute for your express static resources like this:

var staticMiddleware = function(req, res, next) {    console.log('Hello from staticMiddleware!');    next();};app.use(staticMiddleware, express.static(__dirname + '/public'));

Note that if you do add this JWT token checking middleware you should only be returning a response in this code (eg res.send()) if authentication fails. If the JWT is valid, to allow the code to proceed to the static route, call next().

I would have two additional notes regarding your code:

  1. Your if(!req.headers.auth) block will never be executed, you're already in side an if(req.headers.auth) block.
  2. In all failure cases here (req.headers.auth is missing, or payload.sub is missing) you should return a 401 Unauthorized. 301 and 404 would both be incorrect.