Attach Authorization header for all axios requests

I have a react/redux application that fetches a token from an api server. After the user authenticates I’d like to make all axios requests have that token as an Authorization header without having to manually attach it to every request in the action. I’m fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google.

Here is my redux setup:

// actions.js
import axios from 'axios';

export function loginUser(props) {
  const url = `https://api.mydomain.com/login/`;
  const { email, password } = props;
  const request = axios.post(url, { email, password });

  return {
    type: LOGIN_USER,
    payload: request
  };
}

export function fetchPages() {
  /* here is where I'd like the header to be attached automatically if the user
     has logged in */ 
  const request = axios.get(PAGES_URL);

  return {
    type: FETCH_PAGES,
    payload: request
  };
}

// reducers.js
const initialState = {
  isAuthenticated: false,
  token: null
};

export default (state = initialState, action) => {
  switch(action.type) {
    case LOGIN_USER:
      // here is where I believe I should be attaching the header to all axios requests.
      return {
        token: action.payload.data.key,
        isAuthenticated: true
      };
    case LOGOUT_USER:
      // i would remove the header from all axios requests here.
      return initialState;
    default:
      return state;
  }
}

My token is stored in redux store under state.session.token.

I’m a bit lost on how to proceed. I’ve tried making an axios instance in a file in my root directory and update/import that instead of from node_modules but it’s not attaching the header when the state changes. Any feedback/ideas are much appreciated, thanks.

9 Answers
9

Leave a Comment