javascriptreactjsauthenticationtokenrefresh-token

I want to make refresh token API call every 60 minutes


I currently have a refresh token API call every 60 minutes,

Here is my condition:

 **const expires_in = 3600 //This is 3600s comes from auth api 
if (refreshToken && expires_in * 1000 > Date.now() + 3600000) {
// RefreshToken Function
else {
        console.log("accessToken not expired yet");
    }**

This condition is not working properly. This condition calls RefreshToken Function on every reload but I want to call this after every 60 minutes.

Accurate my condition which is to call after every 60 minutes.


Solution

  • First store this date whenever you got the new access token.

    // This snippet adds 3600 seconds to the current date
    const accessTokenTime = new Date();
    accessTokenTime.setSeconds(accessTokenTime.getSeconds() + expires_in);
    

    After that you can compare the two dates, If the accessTokenTime less than the current time, means the 60 minutes is completed for the acccessToken.

    if (refreshToken && (accessTokenTime < Date.now()) {
        // RefreshToken Function
    } else {
       console.log("accessToken not expired yet");
    }