Home > Software design >  Logout user on expired JWT token
Logout user on expired JWT token

Time:05-18

I am trying to log out a user when the jwt token expires. I am trying to do it with axios interceptors, with the following code, but I get an infinite loop since it's asynchronous. Would anyone be able to tell how to go about it or if there is a better way? Thank you

 axios.interceptors.request.use(async (req) => {
    if (token) {
      const userToken = jwt_decoder(token);
      const isExpired = userToken.exp * 1000 < Date.now();
      if (!isExpired) return req;

      axios
        .delete("users/sign_out")
        .then((resp) => {
          clearLocalStorage();
        })

        .catch((err) => {
          clearLocalStorage();
        });
    }
    return req;
  });

CodePudding user response:

axios.interceptors.request.use(async (req) => {
    if (token) {
      const userToken = jwt_decoder(token);
      const isExpired = userToken.exp * 1000 < Date.now();
      if (!isExpired) return req;
      try {
       const resp = await axios.delete("users/sign_out");
        clearLocalStorage();
      } catch(e) {
       clearLocalStorage();
      }
    }
    return req;
  });

CodePudding user response:

Clearing the local storage before making the delete API call should stop the infinite loop. As it won't enter the if condition during the delete API call. Try this.

axios.interceptors.request.use(async (req) => {
    if (token) {
      const userToken = jwt_decoder(token);
      const isExpired = userToken.exp * 1000 < Date.now();
      if (!isExpired) return req
      
      clearLocalStorage();
      axios
        .delete("users/sign_out")
        .then((resp) => {
          clearLocalStorage();
        })

        .catch((err) => {
          clearLocalStorage();
        });
       return req;
     }
    return req;
  });

But as the comment on your question it is not advisable to carry out this check on the client. rather use the status code 401 (unauthorised)

  • Related