Search code examples
node.jsmongodbexpressjwtexpress-jwt

Need of JWT expiresIn field to display on console


how to get expiry time in JWT? I want to notice every user the expiration time of login token, right now i could display their userId, email id but unable to display expiresIn timings. Please point out where should i edit my code to display expiresIn field.

 router.post("/login", (req, res, next) => {
  User.find({ username: req.body.username })
    .exec()
    .then(user => {
      if (user.length < 1) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        if (result) {
          const token = jwt.sign(
            {
              username: user[0].username,
              email: user[0].email,
              userId: user[0]._id,
            },
            process.env.JWT_KEY,
            {
              expiresIn: "10h"
            }
          );
          return res.status(200).json({
            message: "Auth successful",
            token: token,
            userId: user[0]._id,
            expiresIn: user[0].exp,
          });
        }
        res.status(401).json({
          message: "Auth failed"
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

This is the output i m getting as of now.

{ "message": "Auth successful", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRhcnNoYW4iLCJlbWFpbCI6ImRhcnNoYW5hbi4yNEBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU3MTcxNmRjODlhYzZiNGUyY2E0MTciLCJpYXQiOjE1Mzg5ODEyOTYsImV4cCI6MTUzONn0.k0PVole653f_pB3CrQLtdUmv7-c00x1irbQph2i2XaE", "userId": "5b571716dc89ac6b4e2ca417" , "email": "darsh4@gmail.com"}


Solution

  • Look like you have not sent the proper expiration response.

     let expiration = '10h'
     const token = jwt.sign(
                {
                  username: user[0].username,
                  email: user[0].email,
                  userId: user[0]._id,
                },
                process.env.JWT_KEY,
                {
                  expiresIn: expiration
                }
              );
              return res.status(200).json({
                message: "Auth successful",
                token: token,
                userId: user[0]._id,
                expiresIn: expiration, //set expiration time
              });
    

    Reference link that helps you : here