Kevin Kevin - 1 year ago 116
Node.js Question

logs not being logged in nodejs with JWT

I'm following this tutorial to combine JWT authentication with Express routing and Sequelize db management. In the tutorial they use MongoDB while I use Sequelize, but the end-result should be the same.

const jwt = require('jsonwebtoken');
const apiRoutes = express.Router();'/authenticate', (req,res) => {
where: {username: req.body.username}
}).then(user => {
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.'});
if (user.password != req.body.password) {
res.json({ success: false, message: 'Authentication failed. Wrong password.' })

console.log('I am logged');

const token = jwt.sign(user, app.get('superSecret'), {
expiresIn: 60*60*24

console.log(`I'm not logged :(`, token);

succes: true,
message: 'Enjoy your token!',
}).catch(err => {

What's being logged is:

Magic happens at http://localhost:8080
Express server listening on port 8080
Executing (default): SELECT `id`, `username`, `password`, `admin`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`username` = 'Kevin frafster' LIMIT 1;
I am logged
POST /api/authenticate 200 22.819 ms - 2

So the logs after the token are not logged, I don't understand why. The check on username and password are working correctly and return the messages, however this POST returns:


in Postman... Any ideas?

Answer Source

jwt.sign() is throwing an error, which causes your catch to run.

  • In an error condition, you should be setting the status code to 500. res.status(500).json(...).
  • The properties of an Error are non-enumerable. This means that the JSON serializer doesn't see the properties like message, stack, etc. Since there are no enumerable properties available, an Error serializes to {}.

In your catch, add console.error(err.stack) to see why the sign operation fails. You could also provide a more useful error to the client.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download