express-jwt
express-jwt copied to clipboard
Catch expired token throwing error
Running into the issue where expired token (using credentialsRequired false) is throwing error, and I want to redirect instead. What is the current correct way to handle this?
Same here.
To catch errors in a specific middleware like express-jwt
you can wrap it in your own middleware like this, and catch it's errors (in my example I clear the cookie I retrieve the token from):
app.use((req, res, next) => {
const handleErrorNext = err => {
if (err) {
if (
err.name === 'UnauthorizedError' &&
err.inner.name === 'TokenExpiredError'
) {
res.clearCookie('auth0idToken');
return next();
}
}
next(err);
};
const middleware = jwt({
// ...jwt-express options
});
middleware(req, res, handleErrorNext);
});
@hobofan this may be a dumb question, but how do you error out from there? Basically I was to say if unauthorized return a 403. If I'm not in the callback I can just throw an HttpException but as soon as I'm in my secondary middleware it doesn't work - it throws for the application but is not handled and the request is simply canceled.
Edit: scratch that! It was as simple as res.status(401).json({});