Search code examples
javascriptvue.jsaxiosjwtvuex

How to configure Authorization bearer token in axios?


Hi I created a login action (using Vuex) which saves a users jwt token to local storage. Inside this login action I call another action to fetch some posts which this user created. It works completely fine when I pass the token in the header of the get request in the fetchPosts action.

async login(context, user){
    try {
       const res = await api.post('/users/login', user)
       localStorage.setItem('jwt', res.data.token)
       context.commit('SET_USER', res.data.user)
       context.dispatch('fetchPosts')
    }catch(err){
       console.log(err.response.data)
    }
}

async fetchPosts(context){
    try {
        const res = await api.get('/posts', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('jwt')}`
          }
        })
        context.commit('SET_POSTS', res.data)
     }catch(err){
        console.log(err.response.data)
     }
}

The above codes works perfectly fine, but the problem is I have several auth routes and I don't want to pass

headers: { Authorization: `Bearer ${localStorage.getItem('jwt')}`}

for all api requests.

I want to configure in 1 file, which I tried but when I login I get unauthenticated message and when I check in the networks tab I see Bearer null passed into authorization. See below my attempt to configure.

import axios from 'axios'
export default axios.create({
  baseURL: 'http://localhost:3000',
  headers: {
    Authorization: `Bearer ${localStorage.getItem('jwt')}`
  }
})

Anyone know where I went wrong or what I can do to resolve this issue.


Solution

  • Here is a simple example of how to do it.

        axios.interceptors.request.use(
            (config) => {
                const token = localStorage.getItem('authtoken');
        
                if (token) {
                    config.headers['Authorization'] = `Bearer ${token}`;
                }
        
                return config;
            },
        
            (error) => {
                return Promise.reject(error);
            }
        );
    
    

    Find more information here