I'm trying to use Axios interceptors to request the CSRF then Bearer Token if it's not already stored in local-storage.
It mostly works, however the requests don't seem to wait for authToken = await fetchAuthToken();
to resolve before continuing, and I can't seem to figure out why.
What I'm expecting is the console.log("this")
will run first, then console.log("then this")
;
Everything is defined, I've omitted parts for brevity.
function fetchAuthToken() {
authToken = checkLocalStorage("token", false);
if (isFetchingToken) return false;
if (authToken) return authToken;
return apiClient
.get("/csrf-cookie")
.then(() => {
apiClient.get("/token").then((res) => {
authToken = res.data.bearer_token;
localStorage.setItem("token", JSON.stringify(res.data.bearer_token));
console.log('this')
});
})
.catch((err) => {});
}
// Request interceptor for API calls
apiClient.interceptors.request.use(
async (config) => {
if (config.url.includes("/csrf-cookie") || config.url.includes("/token")) {
isFetchingToken = true;
return config;
}
if (!authToken) {
authToken = await fetchAuthToken();
console.log('then this')
}
config.headers = {
Authorization: `Bearer ${authToken}`,
};
return config;
},
(error) => {
Promise.reject(error);
}
);