express-jwt
express-jwt copied to clipboard
Headers Already sent
I have sent express jwt as
app.use(jwt({secret: config.sessionSecret}).unless({path: ['/auth']}));
app.use(auth.jwtErrorHandler);
And jwtErrorHandler impleted as
// lib/auth.js
'use strict';
module.exports.jwtErrorHandler = (err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(err.status).json({message: err.inner.name});
}
next();
};
I get response from server when token expired as
{
"message": "TokenExpiredError"
}
But below waring is appears in console.
(node:98721) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
This error not there when I commented out jwtErrorHandler part
I'm using
Nodejs : v6.10.3 NPM : 3.10.10 "express-jwt": "^5.3.0", "jsonwebtoken": "^7.4.1"
I got this fixed after changing jwtErrorHandler to below version
'use strict';
module.exports.jwtErrorHandler = (err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
return res.status(err.status).json({message: err.inner.name});
}
return next();
};
Can anyone please explain this?
Without the return
you added in the if
block, it falls through and next()
is called.
That next middleware (most likely the default error handler, but it depends on your routing setup) attempts to set response headers.
Since the response was already sent when .json(...)
was called, an unhandled promise rejection occurs. You could have alternatively used an else
to avoid this fall-through.
BTW: in an error handler, if you don't handle certain types of error, then pass those along in next()
call, otherwise they are lost 😨
module.exports.jwtErrorHandler = (err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
return res.status(err.status).json({message: err.inner.name});
}
// return next(); // Next error handling middleware does not know the error :(
return next(err); // Unless you pass it through :)
};
Up