Updating the id token in VueJs using Axios interceptor when it expires

I need to implement an axios interceptor that will add the idToken as an authorization header to every axios call, and also refresh the idToken if it has expired before making any call.

My current code for this task is as follows:

axios.interceptors.request.use(function(config) {
  var idToken = getIdToken()
  var refreshToken = {
    "refreshToken" : getRefreshToken()
  }

   if(isTokenExpired(idToken)){
     console.log("==============Reloading")
     refresh(refreshToken).then(response=>{
       setIdToken(response.idToken)
       setAccessToken(response.accessToken)
     })
     idToken = getIdToken()
     config.headers.Authorization = `${idToken}`;
   }
   else{
    config.headers.Authorization = `${idToken}`;
   }
 return config;
 }, function(err) {
  return Promise.reject(err);
});

This implementation works well when the idToken is valid. However, when the idToken expires, it causes an infinite loop leading to page hang. The refresh() function, used to call the API for refreshing looks like this:

function refresh(refreshToken) {
  const url = `${BASE_URL}/user/refresh`;
  return axios.post(url,JSON.stringify(refreshToken))
  .then(response =>response.data.data)
  .catch(e => {
      console.log(e);
  });
}

Answer №1

I encountered a similar issue, and I was able to resolve it by creating a new axios instance specifically for performing the refresh token API call. It's important to note that defining axios.interceptors.request.use did not solve the problem for me (the code snippet below serves as a basic example).

Don't forget to store the original request and process it after refreshing the token:

For example, you can define http-common.js like this:

import axios from 'axios'
const AXIOS = axios.create()
export default AXIOS

...

In App.vue:

axios.interceptors.request.use((config) => {
  let originalRequest = config
  if (helper.isTokenExpired(this.$store.getters.tokenInfo)) {
    return this.refreshToken(this.$store.getters.jwt).then((response) => {
      localStorage.setItem('token', response.data.token)
      originalRequest.headers.Authorization = response.data.token
      return Promise.resolve(originalRequest)
    })
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

And here is the method for refreshing the token:

    refreshToken (token) {
      const payload = {
        token: token
      }
      const headers = {
        'Content-Type': 'application/json'
      }
      return new Promise((resolve, reject) => {
        return AXIOS.post('/api/auth/token/refresh/', payload, { headers: headers }).then((response) => {
          resolve(response)
        }).catch((error) => {
          reject(error)
        })
      })
    }

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

How to display an HTML element conditionally with v-if based on a variable's value

Looking for a way to display a <div> element, including nested <div>s, based on the value of a variable. I'm currently using v-if, but open to better suggestions. I attempted wrapping the entire <div> in a <template v-if> as s ...

Is it better to use Asynchronous or Synchronous request with XMLHttpRequest in the Firefox Extension for handling multiple requests

As a newcomer to developing Firefox Add-Ons, my initial project involves calling an external API in two steps: Step 1) Retrieve data from the API. Step 2) Use the data retrieved in Step 1 to make another call to the same API for additional information. ...

Issue with Angular's ngOnChanges Lifecycle Hook Preventing Function ExecutionWhen attempting to run a function within Angular's ngOn

In the midst of my evaluation process to ensure that specific values are properly transmitted from one component to another using Angular's custom Output() and EventEmitter(), I am encountering some issues. These values are being sent from the view of ...

Using Array.map and filter together can result in multiple fetch requests being made

Currently, I am in the process of developing an application using Next.js 13 in conjunction with App Routes. However, I have encountered a minor obstacle and could use some assistance. In one of the pages, I have arranged a grid to display information, al ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Dealing with AngularJS ng-model problems when duplicating a form

Currently, I am facing an issue with sending parameters to control and require some guidance. I have multiple types of questions within the ng-repeat loop named 'question' that I am iterating through. The problem arises when there are two questi ...

Display all pages in the DataTables plugin while utilizing responsive tables and additional features

I am struggling to combine the responsive and fixed header attributes of my current function with the "Show All" list feature, similar to what is demonstrated in this example: https://datatables.net/examples/advanced_init/length_menu.html I need assistanc ...

Exploring the combination of vuedraggable with transition groups and header slots

I successfully implemented code with a transition group to create a flip animation <draggable v-model="items" group="backlog-posts" animation="200" handle=".post-content" draggable=".drag-item" @start="drag = true" @end="dra ...

How can I go about refreshing my mapbox gl source data?

Hey there, I'm encountering an issue when attempting to update my mapbox source on click. I currently have two sources (cells, heatmap), and I am trying to add a new source using this code snippet: this.map.addSource("points", { type: "geojson", ...

Invoking a React function repeatedly (every second)

Currently, I am working with React and utilizing Material UI to create a modal. The modal is rendered as part of the body of the code, placed at the bottom of the page. Its visibility is controlled by the state; if it's open or closed. However, I&apos ...

Question: How can I use the jQuery datepicker to ensure that the selected date remains in the

I recently created a webpage using a combination of HTML, PHP, and jQuery. The PHP script is designed to load all data where the date matches the one selected in the text input field generated by the jQuery datepicker. However, I encountered a problem whe ...

Adding semi-colon in JavaScript with special comments by YUI Compressor

Our team recently implemented YUI Compressor (2.4.8) on our project and it's been performing well. However, we encountered an unexpected issue while minifying JavaScript files that contain special comments. It appears that YUI Compressor is automatic ...

Upon the initial hover, the data added to the title tag following an Ajax call is not appearing

I am currently working on an ajax request that retrieves information such as username, email, and user_id. Once the ajax call is successful, I use jQuery to append this data to the title tag. The main issue I am facing is that the data is only displayed af ...

What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript? I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable? T ...

Editing the content of a div in real-time by dynamically updating the innerHTML

Looking for a way to dynamically change the innerHTML of a contentEditable div using pure JavaScript, without relying on the Rangy library. I want the change to occur on keyup without losing cursor position or focus. Here is an example setup: <div id=" ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

Discover the steps to linking a dropdown menu to a text input using HTML and JavaScript

I'm currently using Sublime and trying to link a dropdown menu with an input text using html, css, and javascript. When the user selects an option from the dropdown menu, I want the corresponding value to appear in the text input field. For example, i ...

Keep your data safe and protected within a Node CLI application

Currently developing a NodeJS command-line application that interacts with an API to provide data to users. To access the public API, users need an API token. The CLI will be globally installed on users' machines using npm i -g super-cool-api-cli. Up ...

Having trouble with flash messages in Node.js?

Could anyone shed some light on why the flash messages are not displaying properly in my situation? Here is how I'm attempting to utilize them: This snippet is from my app.js file: var express = require('express'); var app = express ...

What steps can be taken to remove the search parameter responsible for the error?

Imagine having a webpage that displays search results based on the parameters in the URL, like this: https://www.someurl.com/categories/somecategory?brands=brand1,brand2,brand3 This URL will show listings for only brand1, brand2, and brand3. Additionally ...