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
You can write your own wrapper for the axios
and it should be something like this:
import axios from 'axios';
const request = axios.create({
baseURL: backUrl,
timeout: 5000,
});
export const get = url => {
const expiresIn = localStorage.getItem('expiresIn');
const accessToken = localStorage.getItem('accessToken');
if (expiresIn && Date.now() > expiresIn) {
const refreshToken = localStorage.getItem('refreshToken');
request
.post('/oauth/token', {
grant_type: 'refresh_token',
refresh_token: refreshToken,
})
.then(res => {
store.dispatch(
loginSubmitted(
res.data.access_token,
res.data.refresh_token,
res.data.expires_in,
),
);
localStorage.setItem('accessToken', res.data.access_token);
localStorage.setItem('refreshToken', res.data.refresh_token);
localStorage.setItem('expiresIn', res.data.expires_in);
return request.get(url, {
headers: { Authorization: `bearer ${res.data.access_token}` },
accessToken: res.data.access_token,
});
})
.catch(err => {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
localStorage.removeItem('expiresIn');
});
}
return request.get(url, {
headers: { Authorization: `bearer ${accessToken}` },
accessToken,
});
};
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