spark
spark

Reputation: 1381

How to use dynamic auth-header in axios(vue.js)?

I am building an Vue.js app that relies heavily on api calls. I am using axios to make call. I am using a pattern similar this. Basically I have created a service that will be shared by all the components. Following is the service:

//api-client.js

import axios from 'axios'
import store from '../src/store'

let authKey = store.getters.getAuthKey
export default  axios.create({
  withCredentials: false, // This is the default
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    authorization: "Basic "+authKey
  }
})

Now notice I am using a getter to get auth token for the vuex store and seting it in the service.

I will use this service like:

//App.vue
<template>
    <div>
       <!-- some code -->
    </div>
</template>

<script>
import apiClient from "../api-client.js" 
    export default {
        mounted(){
         apiClient.get("#url").then(()={
            // Do Something

         })
      }
    }
</script>

<style lang="scss">

</style>

The situation is, auth key changes every now and then, so I have a setting that will update the auth key in the store. The setting updates the auth key in store successfully, but the key in api-client.js is not updated. It is loaded only once and the update in the store is not cascaded to this api-client.js.

Is there any pattern to solve this? Please suggest.

Upvotes: 6

Views: 4172

Answers (1)

zhuber
zhuber

Reputation: 5534

Since your token is dynamic, you can't define it in your axios instance factory headers setup. Best way to handle this globally is to use request interceptors

//api-client.js

import axios from 'axios'
import store from '../src/store'

const apiClient = axios.create({
    withCredentials: false, // This is the default
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
    }
});

apiClient.interceptors.request.use(function (config) {
    // Do something before request is sent
    let authKey = store.getters.getAuthKey
    config.headers["Authorization"] = "Basic " + authKey;
    return config;
});

export default apiClient;

This way interceptor function would occur on each request and would pickup latest version of your authKey;

Upvotes: 15

Related Questions