express-jwt icon indicating copy to clipboard operation
express-jwt copied to clipboard

Headers Already sent

Open iamchathu opened this issue 7 years ago • 3 comments

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"

iamchathu avatar May 23 '17 08:05 iamchathu

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?

iamchathu avatar May 23 '17 08:05 iamchathu

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 :)
};

beaulac avatar Jun 24 '17 22:06 beaulac

Up

ShepelievD avatar May 18 '18 12:05 ShepelievD