Attach Authorization header for all axios requests Attach Authorization header for all axios requests reactjs reactjs

Attach Authorization header for all axios requests


There are multiple ways to achieve this. Here, I have explained the two most common approaches.

1. You can use axios interceptors to intercept any requests and add authorization headers.

// Add a request interceptoraxios.interceptors.request.use(function (config) {    const token = store.getState().session.token;    config.headers.Authorization =  token;    return config;});

2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

So in your case:

axios.defaults.headers.common['Authorization'] = store.getState().session.token;

If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.

(function() {     String token = store.getState().session.token;     if (token) {         axios.defaults.headers.common['Authorization'] = token;     } else {         axios.defaults.headers.common['Authorization'] = null;         /*if setting null does not remove `Authorization` header then try                delete axios.defaults.headers.common['Authorization'];         */     }})();

Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).

Hope it helps :)


If you use "axios": "^0.17.1" version you can do like this:

Create instance of axios:

// Default config options  const defaultOptions = {    baseURL: <CHANGE-TO-URL>,    headers: {      'Content-Type': 'application/json',    },  };  // Create instance  let instance = axios.create(defaultOptions);  // Set the AUTH token for any request  instance.interceptors.request.use(function (config) {    const token = localStorage.getItem('token');    config.headers.Authorization =  token ? `Bearer ${token}` : '';    return config;  });

Then for any request the token will be select from localStorage and will be added to the request headers.

I'm using the same instance all over the app with this code:

import axios from 'axios';const fetchClient = () => {  const defaultOptions = {    baseURL: process.env.REACT_APP_API_PATH,    method: 'get',    headers: {      'Content-Type': 'application/json',    },  };  // Create instance  let instance = axios.create(defaultOptions);  // Set the AUTH token for any request  instance.interceptors.request.use(function (config) {    const token = localStorage.getItem('token');    config.headers.Authorization =  token ? `Bearer ${token}` : '';    return config;  });  return instance;};export default fetchClient();

Good luck.


The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios.

import axios from 'axios';const client = (token = null) => {    const defaultOptions = {        headers: {            Authorization: token ? `Token ${token}` : '',        },    };    return {        get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),        post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),        put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),        delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),    };};const request = client('MY SECRET TOKEN');request.get(PAGES_URL);

In this client, you can also retrieve the token from the localStorage / cookie, as you want.