Search code examples
laravelvue.jsaxios

The first API call after login is unauthorized until page reload (Laravel Sanctum & VueJS)


I am trying to resolve this 401 issue for some time. After logging in and obtaining the token I am setting it as a header, but keep getting 401 exception on first load of the page. The error goes away after refresh. It seems that the token is not written to store or localStorage the first time around. Here's my code for login (I set the token to state.token in the mutation):

retrieveToken(context, credentials) {
    return new Promise((resolve, reject) => {
      axios.post('api/login', {
        email: credentials.email,
        password: credentials.password,

      })
        .then(response => {
          const token = response.data.access_token
          localStorage.setItem('access_token', token)
          context.commit('RETRIEVE_TOKEN', token)
          resolve(response)
          console.log(response.data)
        })
        .catch(error => {
          console.log(error)
          reject(error)
        })
    })
  },

And that's how I set it to header (setting it from localStorage doesn't solve the issue):

const authorizedApiClient = axios.create({
  baseURL: process.env.VUE_APP_PRODUCTION_URL,
  
  headers: {
    Accept: 'application/json',
    'Authorization': `Bearer ${store.getters.token}`
  }   
})

This behavior baffles me. Is there any theory or suggestions on how to debug?


Solution

  • I guess when the axios client is created the token is not yet retrieved from api. Try setting the header before each request using an interceptor:

    const authorizedApiClient = axios.create({
      baseURL: process.env.VUE_APP_PRODUCTION_URL,
      
      headers: {
        Accept: 'application/json'
      }   
    })
    
    authorizedApiClient.interceptors.request.use((config) => {
      if (store.getters.token){ // or get it from localStorage
        config.headers["Authorization"] = "Bearer " + store.getters.token
      }
      return config
    })