0

I have received access token and refresh token on login and saved it in local storage. I want to send refresh token for subsequent API request when Access token expires in react. I am getting 401 error 'jwt expired'


const accessToken = localStorage.getItem('accessToken')
const headerToken = {headers:{'authorization':`Bearer ${accessToken}`, 'Accept' : 'application/json',
'Content-Type': 'application/json'}}

const getAllProducts = async ()=>{
 
    const response = await axios.get(`${url}/ getProducts`,headerToken)
       
     }
ASIF KAIF
  • 317
  • 1
  • 4
  • 17
  • 2
    You can decode the token and check the expiry before sending the request. The following link would help with this. https://stackoverflow.com/a/65057994/4380459 – Bharat Vishe Sep 06 '21 at 05:46
  • 2
    Does this answer your question? [React - How to check if JWT is valid before sending a post request?](https://stackoverflow.com/questions/46418975/react-how-to-check-if-jwt-is-valid-before-sending-a-post-request) – Noam Yizraeli Sep 06 '21 at 05:57

1 Answers1

1

Install jwt-decode (npm install jwt-decode --save)

   let token = localStorage.getItem(TOKEN);
    let decodedToken = jwt_decode(token);
    console.log("Decoded Token", decodedToken);
    let currentDate = new Date();

    // JWT exp is in seconds
    if (decodedToken.exp * 1000 < currentDate.getTime()) {
      console.log("Token expired.");
    } else {
      console.log("Valid token");   
      result = true;
    }
jfk
  • 4,335
  • 34
  • 27