jwt check if token expired

Andrés Montoya picture Andrés Montoya · Jul 11, 2018 · Viewed 91.2k times · Source

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!

Answer

Andr&#233;s Montoya picture Andrés Montoya · Jul 11, 2018

This is the answer if someone want to know

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