Implementing dynamic authorization headers in axios with vue.js

I am currently working on a Vue.js application that heavily relies on API calls, utilizing axios to make these requests. I have implemented a similar pattern found at this link. Essentially, I have created a service that will be shared across all components. Here is the structure of 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
  }
})

One important detail to note is that I retrieve the authentication token using a getter from Vuex store and incorporate it into the service.

This service is then utilized as follows:

//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 issue arises when the authentication key changes periodically, which triggers an update in the store. However, despite successful updating of the key in the store, the key in api-client.js remains static. It seems that the service loads only once and doesn't reflect subsequent updates made to the key in the store.

Does anyone know of a pattern or technique to address this problem? Any suggestions would be greatly appreciated.

Answer №1

If your token is constantly changing, it's not feasible to define it in the headers setup of your axios instance factory. The best approach to handle this globally is by utilizing request interceptors

//api-client.js

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

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

apiClient.interceptors.request.use(function (config) {
    // Perform actions before sending the request
    let authKey = store.getters.getAuthKey
    config.headers["Authorization"] = "Basic " + authKey;
    return config;
});

export default apiClient;

By implementing this interceptor function, it will run on every request and fetch the most up-to-date version of your authKey.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to match a string against a numeric value

I have a span id with textContent which have their own time(hour/minutes) <div class="here"> <span class="time" >8 min</span> </div> <div class="here"> <span class="time" >22 min&l ...

Power up your web development with the dynamic combination of .NET Core, Vue

I'm currently attempting to utilize the following package: https://github.com/IntelliTect/Coalesce.Vue.Template Within the section titled Creating a new Coalesce project using the template, it instructs: Run dotnet coalesce to trigger Coalesce&apos ...

The functionality of the mapGetters function varies from that of store.getters

Looking below, you'll notice I have a getter that returns a new method which requires a parameter. Based on the documentation, I should be able to invoke this method without the need for two separate method calls. When directly using store.getters, ev ...

What is the best way to display a single instance of a React component that is declared in multiple locations within the app?

Imagine I have 2 main components, A and B. Now, component C needs to be created inside both A and B. How can I guarantee that the same exact instance of C is generated in both places? Essentially, I want them to stay synchronized - any changes made to one ...

Is it possible to transmit parameters when calling an ajax function on an HTML page?

I am trying to implement multiple buttons that trigger the same ajax function. Each button should be able to pass its own unique ID so that the ajax function can apply its action on a specific element related to that button. Is it possible to include a p ...

Ways to execute a function upon form submission

On my HTML page, I have a section dedicated to receiving a threshold value and calling a function with that value. <form id="distance_input" onSubmit="return false;" > <p>Enter a threshold</p> <div class="col-md-8" style=" ...

While Postman (Thunder Client) is able to send requests successfully, Axios lacks the capability to do

When attempting to make HTTP requests using axios to my Node.js backend, I am encountering a persistent 500 (Internal Server Error) despite Thunder Client (similar to Postman) successfully sending the request and receiving the expected response. In my ser ...

What is the method for obtaining the entire object as a response following a click?

I am working on a basic JavaScript snippet: var image = [{name: "Breakfast", age: 100, author: "Alice"},{name: "Dinner", age: 10, author: "Teddy"}]; function gallery(name, content) { this.name = name; this.c ...

Clicking on Vue.js links does not result in any action, and the Home component fails to load automatically

Greetings! I am brand new to exploring the world of vue.js. I recently integrated a TypeScript vue.js project into an existing Visual Studio 2017 solution and it worked seamlessly right out of the gate. Now, my next step is a seemingly simple task - creat ...

The focal point of a Three JS rotation

My goal is to rotate the geometry around a pivot point and set that as the new definition of the geometry. I want the current rotationZ to become the new rotationZ 0 without having to keep editing the rotationZ. This way, when I create a new rotation task ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

How can I automatically center a Vimeo iframe vertically without having to manually adjust the position?

I'm trying to adjust a popular fluid jQuery script so that it can automatically center a vimeo video vertically, without any black bars. A little horizontal cropping is acceptable. Here is my current code: HTML <div class="container"> < ...

bespoke HTML elements and properties

I'm currently facing some difficulties and I am unsure of how challenging it can be. I have tried following various tutorials, including those on SO and YouTube, but they all provide different approaches leaving me stuck. My goal is to create a custo ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

Tips for splitting the json_encode output in Javascript

Looking for help with extracting specific values from JSON data retrieved via PHP and AJAX. I only want to display the agent name in my ID, not the entire object that includes "name" : "Testing". Here is the console output: [{"agent_module_id":"1","agen ...

What is the best method for designing a custom mask for the jQuery Masked Input Plugin that accommodates alphanumeric characters, spaces, and accented

Looking for a way to make a custom mask in jQuery Masked Input Plugin that allows alphanumeric characters, spaces, and accented characters? This is what I currently have: $.mask.definitions["A"] = "[a-zA-Z0-9 ]"; $("#input").mask("A?AAAAAAA"); However, ...

JavaScript functions properly on the home page, yet encounters issues on all other pages

I've been struggling for hours to make this work, but I can't seem to find a solution. I'm working with Ruby, Haml, Sinatra, and Highcharts. I've created a Ruby HighCharts object that includes a Haml partial with the :javascript filter ...

Preventing access to drives and desktop until the mandatory HTML form is completed

Looking to develop a webpage in JSP that will automatically open whenever my system is started. Users will be required to fill out a form on this page before proceeding further. If they attempt to bypass filling out the form, they should not have access ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...