SoFunction
Updated on 2025-03-01

How to implement a front-end refresh token in js project

I encountered a problem a while ago. Sometimes when users are using the online platform, they suddenly ask the user to log in. This will cause a very bad user experience, but there was no good idea at that time, so it was put aside; through scattered time querying information and thinking, this problem was finally solved. Let me share it with you next!

environment

  • Axios V1.3.2 is used by the request.
  • The adoption of the platformJWT(JSON Web Tokens)Perform user login authentication.
    (Expand: JWT is an authentication mechanism that lets the background know that the request comes from the trusted client; in more detail, you can query the relevant information yourself)

Problem phenomenon

When online users use it, they occasionally jump to the login page and need to log in again.

reason

  • Suddenly jump to the login page, because the current token expires, the request failed;axiosResponse InterceptThe status code 401 returned by the failed processing request, and it is known at this timetokenIt is invalid, so it jumps to the login page and allows the user to log in again.
  • The current logic of the platform istokenIf the user logs into the platform, he can directly enter the homepage without logging in; therefore, this phenomenon exists: the user opens the platform, because at this timetokenBefore the expiration date, the user directly enters the homepage and performs other operations. However, during the user's operation,tokenIt suddenly fails, and a sudden jump to the login page will occur, seriously affecting the user's experience!
    Note: Currently, there is a large data screen in online projects, and some real-time data display; therefore, there is a situation where users stay on the large screen page for a long time without operating, and viewing real-time data.

Point of entry

  • How to update in a timely manner without the user's perceptiontoken
  • whentokenIn the event of failure, there may be more than one error request; when the failure oftokenAfter the update, how to resend multiple failed requests?

Operation process

alright! After some analysis, we found the problem and determined the entry point; then let's practice and solve the problem.

Before:

1. We only deal with it from the front-end perspective.
2. The backend provides two important parameters:accessToken(Used in the request header, authenticate, and has a valid period);refreshToken(Refresh token, used to update expired accessTokens, it has a longer validity period compared to accessTokens).

1. Handle axios response interception

Note: In my actual project,accessTokenThe expired backend returnsstatusCodeThe value is 401, and it needs to beoferrorLogical processing is performed in the callback.

// Response to intercept(
  (response) => {
    return response;
  },
  (error) => {
    let {
      data, config
    } = ;
    return new Promise((resolve, reject) => {
      /**
        * Determine that the current request has failed
        * Is it caused by toekn failure
        */
      if ( === 401) {
         /**
          * RefreshToken is the encapsulated operation related to updating tokens
          */
        refreshToken(() => {
          resolve(axiosInstance(config));
        });
      } else {
        reject();
      }
    })
  }
)
  • We judgedstatusCodeTo determine whether the current request failed istokendue to expiration;
  • Using Promise to handle requests that will fail, due totokenFailed requests caused by expiration are stored (the request callback function is stored, resolve status).Reason: We have updated latertokenAfter that, the stored failed request can be re-initiated to achieve the user's unsense experience.

2. Encapsulate refreshToken logic

Key points:

  • Storage due totokenFailed request due to expire.
  • Update local and headers in axiostoken
  • whenrefreshTokenAfter the refresh token is expired, let the user log in again.
// Store failed requests due to expired tokenlet expiredRequestArr: any[] = [];
/**
  * Store the request that failed to send due to token failure
  */
const saveErrorRequest = (expiredRequest: () => any) => {
  (expiredRequest);
}
// Avoid frequent update sendinglet firstRequre = true;
/**
  *Use refreshToken to update the currently used token
  */
const updateTokenByRefreshToken = () => {
  firstRequre = false;
  (
    'Request to update token',
  ).then(res => {
    let {
      refreshToken, accessToken
    } = ;
    // Update local tokens    ('accessToken', accessToken);
    // Update the token in the request header    setAxiosHeader(accessToken);
    ('refreshToken', refreshToken);
    /**
      * After obtaining the latest refreshToken, accessToken
      * Re-initiate a previously failed request
      */
    (request => {
      request();
    })
    expiredRequestArr = [];
  }).catch(err => {
    ('Fresh token failed err', err);
    /**
      * At this time, the refreshToken has also expired
      * Return to the login page and let the user login again
      */
     = `${HOME_PAGE}/login`;
  })
}
/**
  * Update the currently expired token
  * @param expiredRequest callback function, returns the request that failed due to the token expired
  */
export const refreshToken = (expiredRequest: () => any) => {
  saveErrorRequest(expiredRequest);
  if (firstRequre) {
    updateTokenByRefreshToken();
  }
}

Summarize

After a wave of analysis and operation, we finally achieved a senseless refresh in the actual project.tokenThe most important thing is to effectively avoid the phenomenon that users suddenly log out during platform operation (Especially when the user fills in the information and suddenly logs in again, all the information filled in before will be invalidated, which is easy to make people crazy.)。

This is the article about how to realize the invisible refresh token in the front-end in the js project. For more related js invisible refresh token content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!