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

Pull information from database based on selection made in combo box

I am attempting to populate a text box with values from a database based on the selection in a combo box. I have written the code below but it doesn't seem to be working correctly. The issue is that the value selected in the combo box is not being pas ...

Set my click event handler back to its default setting

I'm struggling with resetting a click function after it completes. How can I make sure it's ready to run again? $('body').on('click', '#ConfirmBet', function () { function randomImg() { var imgs = $(&apo ...

What's the best way to adjust the width of the <Input> component in Reactstrap?

How can I adjust the width of an input element in Reactstrap to be smaller? I've attempted to set the bsSize to small without success <InputGroup> <Input type="text" name="searchTxt" value={props.searchText ...

It seems that the `to` required prop was missing in the `Link` component of React-Router

Currently, I am facing an issue while trying to integrate react-router. The error message I'm encountering is: Failed propType: Required prop to was not specified in Link. Check the render method of app. Unfortunately, I am unable to pinpoint ex ...

Is there a way to streamline and optimize this React/Material UI code for faster performance?

There seems to be a lot of repetition in the code that needs to be cleaned up. I'm wondering if the switch statement is necessary. It looks like it requires the muiTheme palette to be passed this way. Also, can these theme constants be placed in a sep ...

The behavior of Elementor lightbox buttons upon being clicked

When using Android, I've noticed that the lightbox briefly displays a semitransparent cyan bar on the left and right buttons when they are pressed. Is there a way to control or prevent this behavior? Any suggestions would be appreciated! Thanks in adv ...

Stopping an endless loop in JavaScript by pressing a key on the keyboard can be a useful

I've been working on creating a JavaScript game and am currently tackling the challenge of implementing gravity. One crucial aspect I need to address is creating an infinite loop without causing the browser to crash. Is there a way for me to include a ...

React: The peculiar contradiction of useEffect with eventHandler props

Having trouble with this specific example. The issue arises with an Input component that includes an onChange prop to manage internal data changes. Under normal circumstances, if the value is updated externally, the onChange prop does not trigger since t ...

Add to an array the recently created span element which was inputted through text in AngularJS

Having some difficulty controlling an array object with a list of span values using a watcher in Angularjs. The current setup works partially - when I input span elements, an array is automatically created for each span. When I remove a span element, the ...

Using JLinq for Date-Based Filtering of JSON Data

I have been trying to use JLinq for filtering JSON data, but I am facing an issue with filtering by date. Despite attempting different methods, the problem persists. Below is a snippet of my code: //This works jlinq.from(myData) .select(function ...

Is it possible to enable tab navigation for a button located within a div when the div is in focus?

I have a component set up like this: (Check out the Code Sandbox example here: https://codesandbox.io/s/boring-platform-1ry6b2?file=/src/App.js) The section highlighted in green is a div. Here is the code snippet: import { useState } from "react" ...

Whenever I adjust the layout of the navigation bar, the edges end up getting clipped

I'm having trouble with the border shape of my navbar. When I try to make it a rounded pill shape, the edges get cut off instead of being properly displayed. https://i.stack.imgur.com/sUN2Y.png Below is the HTML template: <template> <div cl ...

Create a fresh field for the form and store the data in the database

Issue Number One: I am looking to dynamically add a new field along with a button click event that will generate the new field. I attempted to use Jquery for this purpose, but as a newbie in this type of programming language, I am struggling. Can anyone o ...

Dilemma: Navigating the Conflict Between Context API and Next.js Routing in React

Recently, I was following a Material UI tutorial on Udemy and decided to set up a Context API in Create React App without passing down props as shown in the tutorial. Later on, when I tried migrating to Next JS with the same Context API, I started encounte ...

Step-by-step guide on redirecting to a different page following a successful POST API call using Jquery

I have the code below in my JavaScript file. $scope.addLookupAction = function () { $("#importForm").attr("action", 'xyz.com'); success:function(response) { $log.info("Redirecting to lookup home page"); ...

What is the process for setting a cookie in Next.js from a different backend server?

I have encountered an issue with my Node.js API built using Express.js. The cookie I set works perfectly fine on Postman, but for some reason, it is not functioning properly in Next.js. I set the cookie when a user logs in, but it is not appearing in the b ...

Simple method for implementing a fade effect on a React component with raw JavaScript techniques?

I am seeking a way to have my React component smoothly fade in upon being mounted. The component's outermost DIV starts with inline style display:none. Within the componentDidMount() method, I've written the following code: let el = document.que ...

When attempting to render a React child, it is important to note that objects are not valid (found: [object Promise]). If your intention was to display a collection of children, it is advised

Instructions in "/pages/blog/index.js" : import BlogComponents from "../../components/Blog/blogComponents"; import { listBlogs } from "../../server/mongodb"; const index = async (props) => { console.log(props) return ( ...

Warning: The React Router v6's Route component is unable to find the origin of the key props

I recently came across an error in my console and I'm unsure which list is causing it. Is there a way for me to trace back the origin of this error so I can pinpoint where to fix it? The error seems to be related to the React Router component, which ...

Leverage Node.js modules to reassign variable values

My simplified JavaScript module simulates an eye pose. var pose = {}; var eye = {}; var left = {}; left.pitchPos = 37; left.yawPos = 47; exports.init = function () { eye.left = left; pose.eye = eye; return this; }; exports.eye = function (e ...