Checking if the access token is valid or expired Basically, the server gives me a token object. I am planning to check the token on the client if it is expired/valid before making a request to the server.
The function below works as expected. I just want to know if my code catch-all edge cases? I don't want, even 1 second that will request will fail due to an expired access token.
I am using moment for comparing dates. I also converted the current date and expiry date to UTC so that I'm making sure that they are in the same timezone before comparing them.
const moment = require('moment');

/**
The token object passed in the function looks like this:
{
  access_token: '2hbssMdXDpwQX5WcnZ-iJlO754MLkEeDCmF-f1A-MaU',
  token_type: 'Bearer',
  expires_in: 604800,
  refresh_token: 'VxnN9uBVIcNMpuwRVpvXo2YxWuNFEayHqfnCM7aCTSI',
  scope: 'public',
  created_at: 1603604241
}
*/

export default function tokenValid(token = {}) {
  const currentDate = moment().utc();
  const expiryDate = moment.unix(token.created_at).add(token.expires_in, 'seconds').utc();

  return currentDate &lt; expiryDate;
}

EDIT (based on @hjpotter92's comment)
export default function tokenValid(token = {}) {
  const currentDate = moment().unix();
  const expiryDate = token.created_at + token.expires_in;

  return currentDate &lt; expiryDate;
}
You seem to ignore two facts.

The client clock can be out of sync with the server clock.

The transport of the request from client to server takes more then zero time.


Both these cases mean that no matter how hard you try on the client side, there is always a chance that the server will evaluate the token as expired during its processing.
What you should do is have the client take the same action when server refuses the token as you do when your client side validation fails.
In general, client side validation

is not necesary
is not reliable
reduces network traffic
increases user experience

Whereas backend side validation

is necesary
is the only source of truth

Clients should understand and handle possible server side validation errors prior to deploying their own validation logic.