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:
- Your
if(!req.headers.auth)
block will never be executed, you're already in side anif(req.headers.auth)
block. - In all failure cases here (
req.headers.auth
is missing, orpayload.sub
is missing) you should return a401 Unauthorized
. 301 and 404 would both be incorrect.