React Global Instance of Axios with API Keys & Tokens

Photo by Jean van der Meulen from Pexels

Overview

This is a quick how-to for creating a single file to handle the API calls using Axios. The advantage of handling the API keys and tokens in one file, is code reusability and fewer points of failure. Maybe create a connection file for each API you work. In this example a file labeled axiosConn.js is created and used for API calls. Also show how to set up Interceptors for incoming and outgoing requests.

File axiosConn.js located at the root or under a folder for global classes or components. Base Example from axios-http.com

import axios from 'axios';

const axiosConn = axios.create({
  baseURL: `https://localhost:43242`
});

export default axiosConn;

// Request interceptor (Outgoing)
axiosConn.interceptors.request.use(function (config) {
    // Do something before request is sent   
    console.log('Interceptor Request (Outgoing) ', config);
   
    config.headers.API_KEY = 'YOUR_API_KEY';

    if(sessionStorage.getItem('jwt_token')) {
      config.headers.Authorization = `Bearer ${sessionStorage.getItem('jwt_token')}`;
    }
    return config;
  }, function (error) {
    // Request error
    return Promise.reject(error);
});
  
// Response interceptor (Incoming) - Optional
axiosConn.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger

    // Response data
    console.log('Interceptor Response (Incoming) ', response);

    return response;
  }, function (error) {

    // Any status codes that falls outside the range of 2xx cause this function to trigger

    // Do something with response error
    return Promise.reject(error);
});  

You should see the incoming and outgoing traffic from the Console tab from your browser.

Optional: For HTTP Only Cookies there is an option for with credentials.

import axios from 'axios';

const axiosConn = axios.create({
  baseURL: `https://localhost:43242`
});

export default axiosConn;

          
axios.defaults.withCredentials = true;

Examples of a Get and a Post.

Import the source file axiosConn.js in the components instead of importing axios.

Get

const url = '/api/product/getall'
axiosConn.get(url)
.then(function (innerResponse) {
    console.log(innerResponse);            
}).catch(function (innerResponse) {
    console.log(innerResponse);
})

Post

const url = '/api/product/addproduct'
axiosConn.post(url, {        
    Title: title,  
    Description: description
})      
.then(function (response) {
  console.log(response);            
}).catch(function (response) {
  console.log(response);
});