I am trying to update access token using refresh tokens. I am using axios interceptors to call the /refreshendpoint which returns a new access token. I am setting the token and refresh token in local storage. however, when the token is expired, the getAll method is called before the response interceptor. the token does get updated in the local storage after I call the /refresh endpoint in the response interceptor, but in the getAll method, the token that's set in the header is still the previous expired token. When I refresh the page though, the new token is set in the header and it works as expected. when I see the server console, it shows the /patients endpoint is called before the /refresh endpoint. I am calling the getAll method when the component mounts.
axios interceptor code:
import { getFromLS } from "./localStorage";
const baseURL = "http://localhost:4200/api"
const instance = axios.create({
baseURL,
});
instance.interceptors.request.use((request: AxiosRequestConfig) => {
axios.defaults.headers.common["Authorization"] = "";
delete axios.defaults.headers.common["Authorization"];
if (getFromLS("token")) {
if(request.headers) {
request.headers.Authorization = getFromLS("token");
}
}
return request;
});
instance.interceptors.response.use(
(response) => response,
(error) => {
const originalRequest = error.config;
if (
error.response.status === 401 &&
originalRequest.url === `${baseURL}/refresh`
) {
return Promise.reject(error);
}
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
instance
.post("/refresh", {
body: {
id: Number(getFromLS("user")),
refreshToken: getFromLS("refreshToken"),
},
})
.then((response) => {
const newToken = response.data.data.newAccessToken;
localStorage.setItem("token", newToken);
instance.defaults.headers.common[
"Authorization"
] = `Bearer ${newToken}`;
return instance(originalRequest);
})
}
return Promise.reject(error);
}
);
export default instance;
the getAll method which uses the above axios instance:
get: (url: string) => instance.get<IPatientResponse>(url).then(responseBody)
getAll: (): Promise<IPatientResponse[]> => get("/patients"),