I have created an axios instance:
const instance = axios.create({
baseURL: 'https://example.io/api/',
timeout: 1000
});
and would like to use it on different components. My webapp is secured with Keycloak and every request that goes to API, needs an authentication token. To get the token, I call the Keycloak method as follows:
kc
.init({onLoad: "login-required"})
.then(authenticated => {
if (kc.idToken === undefined) {
return Promise.reject("Can not be authenticated")
}
return authenticated && root !== null ? start({authToken: kc.idToken}, root) : Promise.reject("Can not be authenticated")
})
.catch(console.log)
When I do the request to the API server, I pass the token as Bearer token in the request header. To avoid passing the token on every request, can I use the intercepter right or what do I have to do?
One way to achieve this is as follows:
Create a file with the following code snippet and name this httpService.js (choose the name of your choice).
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(
function (config) {
// Do something before request is sent
config.headers.Authorization = `Bearer ${your_token}`;
// OR config.headers.common['Authorization'] = `Bearer ${your_token}`;
config.baseURL = 'https://example.io/api/';
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
export default {
get: axios.get,
post: axios.post,
put: axios.put,
delete: axios.delete,
patch: axios.patch
};
Now to use it in other parts of your application, add this import:
import http from './httpService';
Example usage:
static getClient = (clientId) => {
return http.get('/clients/' + clientId);
};
The baseUrl and Authorization header will be automatically configured with every request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With