I have an accessToken in my redux store. I am creating a axios client like this:
import axios from 'axios';
import store from '../redux/store';
const apiClient = axios.create({
baseURL: 'http://localhost:5002/api/',
headers: {
Authorization:`Bearer ${store.getState().auth.accessToken}` // ???
}
});
apiClient.defaults.headers.common['Authorization'] = `Bearer ${store.getState().auth.accessToken}`; // ???
export default apiClient;
I want every request that is sent by the apiClient to contain the current value of the accessToken from the redux store (at the time the request is sent). And with the lines that are marked with ???, I'm not sure whether the Authorization header is only set once when the apiClient is created, or whether the value of the header also changes when the accessToken in the store has been updated. Later I want to make a request like this:
apiClient.get<User[]>('Users/Friends');
And I want the request to include the accessToken that is in the store at the time the request is sent not at the time the client is created. Is there a way to achieve this while the creation of the client or do I always have to put the Authorization header config with the current accessToken in every request?
Now I added this code:
const apiClient = axios.create({
baseURL: 'http://192.168.178.188:5002/api/'
});
apiClient.interceptors.request.use(config => {
config.headers['Authorization'] = `Bearer ${store.getState().auth.accessToken}`
return config;
});
Is this the most elegant solution?