Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use axios instance in different components in react?

Tags:

reactjs

axios

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?

like image 444
softshipper Avatar asked May 19 '26 11:05

softshipper


1 Answers

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.

like image 183
Arfizur Rahman Avatar answered May 21 '26 00:05

Arfizur Rahman