Skip to content

How to check if a twilio token is expired

I have a nextjs project and I need to verify if a twilio token is expired or not.

I thought about using the library jwt-decode to decode the token and take the exp attribute from it, then compare it to the actual date. The problem is that the exp date seems to be broken because it is always in 1970.

For example I have just created this token:

{
  "jti": "SKbec4a565d0598f1e4130f65db51a8345-xxxxxxxxxx",
  "grants": {
    "identity": "618f7ef057c2923be10dfd1d",
    "chat": {
      "service_sid": "ISbffc1a6c2f8647ac8a6774xxxxxxxxxx"
    }
  },
  "iat": 1649879042,
  "exp": 1649882642,
  "iss": "SKbec4a565d0598f1e4130f6xxxxxxxxxx",
  "sub": "AC1d09a2edee3f481fbd1dafxxxxxxxxxx"
}

If I do new Date(1649882642) it comes out to be 1970-01-20T02:18:02.642Z. Always.

Maybe should I specify the token expiration when I create it? I created it following the official doc. So what should I do in order to determinate if a token is valid or not?

Answer

The iat and exp values in a Twilio JWT are the time in seconds since the epoch (1st January 1970).

However, Dates in JavaScript are measured in milliseconds since the the epoch.

So, to adjust the time in seconds to the date in JavaScript you should multiply by 1,000 first.

const exp = decodedToken.exp;
const expiryDate = new Date(exp * 1000);

In your example, that looks like:

const exp = 1649882642;
const expiryDate = new Date(exp * 1000);
expiryDate.toISOString();
// => 2022-04-13T20:44:02.000Z