How to setup Axios interceptors with React Context properly?

Common Approach (localStorage)

It is a common practice to store the JWT in the localStorage with

localStorage.setItem('token', 'your_jwt_eykdfjkdf...');

on login or page refresh, and make a module that exports an Axios instance with the token attached. We will get the token from localStorage

custom-axios.js

import axios from 'axios';

// axios instance for making requests 
const axiosInstance = axios.create();

// request interceptor for adding token
axiosInstance.interceptors.request.use((config) => {
  // add token to request headers
  config.headers['Authorization'] = localStorage.getItem('token');
  return config;
});

export default axiosInstance;

And then, just import the Axios instance we just created and make requests.

import axios from './custom-axios';

axios.get('/url');
axios.post('/url', { message: 'hello' });

Another approach (when you’ve token stored in the state)

If you have your JWT stored in the state or you can grab a fresh token from the state, make a module that exports a function that takes the token as an argument and returns an axios instance with the token attached like this:

custom-axios.js

import axios from 'axios';

const customAxios = (token) => {
  // axios instance for making requests
  const axiosInstance = axios.create();

  // request interceptor for adding token
  axiosInstance.interceptors.request.use((config) => {
    // add token to request headers
    config.headers['Authorization'] = token;
    return config;
  });

  return axiosInstance;
};

export default customAxios;

And then import the function we just created, grab the token from state, and make requests:

import axios from './custom-axios';

// logic to get token from state (it may vary from your approach but the idea is same)
const token = useSelector(token => token);

axios(token).get('/url');
axios(token).post('/url', { message: 'hello' });

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)