DEV Community

chandra penugonda
chandra penugonda

Posted on

Refresh token in SPA

Refresh tokens are the credentials that can be used to acquire new access tokens.

  • The lifetime of a refresh token is much longer compared to the lifetime of an access token.
  • Refresh tokens can also expire but are quiet long-lived.
  • When current access tokens expire or become invalid, the authorisation server provides refresh tokens to the client to obtain new access token.

Alt Text

JWT tokens are valid for a very specific amount of time. The time left for expiration is readily available as part of the access token. You can use a library such as jwt-decode to decode the access token and extract the expiration time. Once you have the expiration time,

Here are 3 options

  • Check token every time before making a request to know if it needs to be refreshed
  • Use setTimeout to refresh it periodically X seconds before it expires
  • Ask for a new access token if protected route returns 401

In this article , we will see 3rd approach

Pseudo code


try {

  // api call to protected route
  const response = await fetch();

  if (res.status === 200) {

    // update state management library with accessToken, refreshToken you have received from response
    // update cookies/LocalStorage with accessToken, refreshToken you have received from response

  } else {

    // perform necessary action

  }
} catch (error) {

  if (error.response.status === 401) {

    // get refreshToken from cookies or localstorage . in My case it's from cookies
    const refreshToken = cookies.readCookie("refreshToken");

    if (refreshToken) {

      // api call to GET new accessToken & refreshToken
      const response = await fetch();

      // update state management library with accessToken, refreshToken you have received from response
      // update cookies/LocalStorage with accessToken, refreshToken you have received from response

    } else {

      // redirect user to login

    }
  }
}

Enter fullscreen mode Exit fullscreen mode

In next article, we will see how to fetch failed api's and prevent user from requesting multiple tokens.

Top comments (1)

Collapse
 
andreich1980 profile image
AndrewP

Where do you get the credentials to request a new fresh token?
Do you redirect user to the login form again?