I'm working on a react application that consists of many API requests. The structure of the application is
When logging in, I'm receiving a token on response and I'm saving the token in my local storage to be used in other API requests.
This token is expired every 30 minutes and if I do an API request after 30 minutes, I'm receiving a status of 401 in my request. I'm using this 401 status to do my logging out and clearing token data in local storage.
Example request
export function stationDailyUsage(data) {
return dispatch => {
dispatch(dailyUsageLoading());
axios.get(`${API_URL}/Dashboard/DailyUsage?type=${data.type}&date=${data.date}`, {
headers: {
'Authorization': `Bearer ${token}`
},
})
.then(res => {
if (res.data.success === true) {
dispatch(dailyUsageSuccess(res.data));
} else {
console.log("error");
}
})
.catch(function (error) {
if(error.response.status === 401){
dispatch(logout());
}
});
}
}
So to logout this way I have to do this check for every API I use (Around 40 APIs ). Is this the best approach to follow or is there a better way to handle the logout. I've read about axios interceptors
but was not clear about how to implement it in my system. Any help is greatly appreciated.
Yes you're partially correct, in case you cannot use refresh tokens (which should be given to maintain the login state ideally).
Use axios interceptors to intercept the response before it becomes an error like 401 which needs to be handled.
Put this code in your project initialize or loading section, and run it once then every time you call
axios
this code will check errorsChange your variable here and use it
You can write your own wrapper for the
axios
and it should be something like this:so it will check the
exprire_date
before each request and send a new request for a new token so user won't log out