Hi I am new to the front end flow of JWT auth and was wondering how to resend a request when a new token is issued.
From my understanding Auth tokens should be short-lived, while Refresh tokens have a longer life span. This causes an issue where requests frequently fail due to expired auth token and a request has to be sent again with a new auth token.
What is the best practice in maintaining this pattern? As a POC I wrote quick snippet to showcase an idea I had, but feel there might be a better way.
const API_FETCH_ATTEMPTS = 2;
const refreshAPI = 'backend/refresh';
function customFetch(url, options, retryAttempts = API_FETCH_ATTEMPTS){
if (!retryAttempts){
return null
}
const authToken = localStorage.getItem('auth-token');
return fetch(url, {...options,'AuthToken': authToken})
.then()// successful call
.catch(err => {
if (err.status === '401'){
fetch(refreshAPI)
.then(newToken => {
localStorage.setItem('authToken', newToken)
customFetch(url, options, retryAttempts - 1);
});
}
});
}
Any ideas / assistance is much appreciated. Thanks!