skip to Main Content

quick question on implementation of multiple axios instances.

I call my own API as needed inside my mobile app. Certain API endpoints are protected by checking that the token issued by Google Signin or Facebook Signin is authenticated and matches the expected user. Other endpoints do not require a token and actually require the frontend to not send a token at all to proceed down the proper logic path on the backend.

I set the global axios instance when I fetch the user token on frontend. I am hoping that all axios calls include the token by default. To achieve this, I set the default Authorization header as such:

import axios from 'axios'

...

axios.defaults.headers.common.Authorization = `Bearer ${fbUserInfo.accessToken}`

This code runs on the initial page of the app that is loaded, so everytime I use axios somewhere else in the app, the token is now included. It works as expected until I proceed to the following step.

In order to create some recurring API calls where a token should not be included, I create a “tokenless” instance inside one of my redux action creators.

const axiosTokenlessInstance = axios.create()
...
axiosTokenlessInstance.defaults.headers.common.Authorization = false

This does indeed override the default axios settings when I call it directly, however, I’ve realized that it also has overridden my default settings when I just call axios directly again.

I expected the behavior to be that I could still call axios.post or axios.get elsewhere and it would still include the token. Was I mistaken and do I have to create a “tokened” instance? I’d prefer not to do this as I’d have to go through and replaced tokened instance explicitly everywhere rather than just using axios default. Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    Specifying the blank header Authorization inside axios.create() fixes the issue and doesn't override the global axios headers.

    So this works as expected:

      const axiosTokenlessInstance = axios.create({
        baseURL: Config.API_HOST,
        headers: { Authorization: '' },
      })
    

    While this overrides global axios settings, not just affecting the specified instance:

      const axiosTokenlessInstance = axios.create()
      axiosTokenlessInstance.defaults.headers.common.Authorization = false
    

  2. Try creating a file called setAuthToken.js that handles the auth instance separately. This way any time you need to use the auth, you can just call this function ( I would even suggest limiting to calling this auth only once and having the token saved in the users localStorage):

    import axios from 'axios';
    
    const setAuthToken = token => {
    if(token){
        axios.defaults.headers.common['x-auth-token'] = token;
    }
    else{
      delete axios.defaults.headers.common['x-auth-token'];
    }
    
    }
    
    export default setAuthToken;
    

    Now let’s say you have a backend function call that needs auth verification, you can do it like so:

    import setAuthToken from "../utils/setAuthToken";
    export const loginUser = (token) => async (dispatch) => {
      if (localStorage.token) {
        setAuthToken(localStorage.token);
      }
      try {
        const res = await axios.get("/api/auth");
        dispatch({
          type: USER_LOGGED,
          payload: res.data,
        });
      } catch (err) {
        dispatch({
          type: AUTH_ERROR,
        });
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search