[Fixed] jwt check if token expired

Issue

I’ve configured the token like this:

jwt.sign(
  {
    user: pick(user, ['_id', 'username'])
  },
  secret,
  {
    expiresIn: '2m'
  }
);

But when I want to check if the token was expired, this code doesn’t work

function isAuthenticated() {
  const token = localStorage.getItem('token');
  const refreshToken = localStorage.getItem('refreshToken');
  try {
    decode(token);
    const { exp } = decode(refreshToken);
    if (exp < (new Date().getTime() + 1) / 1000) {
      return false;
    }
  } catch (err) {
    return false;
  }
  return true;
}

The problem is this part:

if (exp < (new Date().getTime() + 1) / 1000) {
  return false;
}

new Date().getTime() + 1) / 1000 = 1531335468.113

exp = 1531334595

Because I don’t know what format of time uses JWT…

How can I resolve this?

Thank you!

Solution

This is the answer if someone want to know

if (Date.now() >= exp * 1000) {
  return false;
}

Leave a Reply

(*) Required, Your email will not be published