Endless loop issue encountered while attempting to refresh token with Axios interceptors

I have a Vue.js single-page application. My objective is to refresh the token automatically via axios interceptors if it has expired. Before sending a request to the API, I need to check the expiration time of the token. If it has expired, I should refresh it and then proceed with the user's request.

Here is the refresh function I am using:

const refreshToken = () => {
  return new Promise((resolve, reject) => {
    return axios.post('/api/auth/token/refresh/').then((response) => {
      resolve(response)
    }).catch((error) => {
      reject(error)
    })
  })
}

And this is the axios request interceptor setup:

axios.interceptors.request.use((config) => {
  let originalRequest = config
  if (jwt.isTokenExpired()) {
    return api.refreshToken()
      .then(res => {
        if (res.data.error == 'TOKEN_BLACKLISTED' && res.headers.authorization) {
          // Extract the token from headers, excluding the "Bearer " prefix 
          let token = res.headers.authorization.slice(7)
          // Save the token in localStorage
          jwt.setToken(`"${token}"`)
          // Update "Authorization" header with the new token
          api.setHeader()
          return Promise.resolve(originalRequest)
        } else {
          jwt.destroyToken()
          jwt.destroyExpiredTime()
          store.dispatch('auth/destroyToken')
          router.push({name: 'login'})
          return Promise.reject()
        }
      })
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

However, there seems to be an issue causing an infinite loop. How can I resolve this?

Answer №1

To effectively handle different endpoints, it is advisable to create two separate instances of axios:

  • Create the first instance for authorization-related endpoints that do not require an access token, naming it axiosAuth. For example, use
    axiosAuth.post('/api/auth/token/refresh/')
  • Establish a second instance for the authorized section of your project, naming it axiosApi. For example, utilize
    axiosApi.interceptors.request.use

Ensure you set up the interceptor for the second instance, so that calls to refresh_token will not trigger the wrong interceptor.

Answer №2

When the interceptor is triggered, it shows that a request is being made. This indicates that the token remains expired as the interceptor is activated during the request to refresh the URL. One solution could be to include a condition in your interceptor to verify if the URL matches your refresh token URL, and then proceed to resolve the initial request.

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

What is the best way to trigger the animation once more if the state remains unchanged?

I'm exploring how to re-animate the shake effect for an incorrect answer, or a flash animation for a correct answer. I've set up 2 Boolean states for the correct and incorrect answers. I know that if the same incorrect answer is entered again, t ...

"Efficiently rendering a variety of textures using a single draw

Hey there, I am interested in creating multiple cubes with unique textures for each cube. In order to optimize performance, I've combined the geometries into a single mesh. However, I've encountered an issue with textures as I currently require a ...

Adding data to MongoDB Using Node.js, mongojs, and express

Hey there, I'm having some difficulty inserting the JSON data I've created into MongoDB... var newjson = JSON.stringify(json); console.log(newjson); db.mongostuds.save(newjson, function(err, saved) { if( err || !saved ...

Create a dynamic AppBar Toolbar in React Admin that changes based on the current page

Recently delving into the world of React, I've been facing some challenges when it comes to loading IconButtons onto the toolBar of an AppBar (from Material UI). For instance, I'm looking to have two specific IconButtons displayed on pageA and d ...

My JavaScript functions are not compliant with the HTML5 required tag

I am currently developing input fields using javascript/jQuery, but I am facing an issue with the required attribute not functioning as expected. The form keeps submitting without displaying any message about the unfilled input field. I also use Bootstrap ...

Utilizing service-based global objects in Angular applications

Upon entry into my application, the GlobalApplicationController initializes several services that are utilized throughout the entire application, such as subscribing to sockets. It would be quite beneficial to have a CurrentUser object available - however, ...

I didn't see any activity in the network tab while I was browsing or refreshing web pages

While browsing or refreshing web pages, I noticed that there is nothing in the network tab. The filter icon appears red and doesn't seem to be functioning properly. The network panel is also empty, and Chrome inspector isn't showing any network r ...

Vue textarea not accepting null values

My current setup includes the following dependencies: - "vue": "3.2.26", - "vee-validate": "4.5.6", - "typescript": "4.5.4" While working on a textarea field in vue3, I encountered an issue Here's a snippet with vee-validate integration import { Fie ...

How does an iOS device typically manage the :hover pseudo-class?

My div is designed to expand when clicked using jQuery $('.mydiv').click, and collapse with a second click. In addition, the same div showcases more information on hover due to CSS rules utilizing :hover. This feature works perfectly on a comput ...

Extract particular XML element(s) and incorporate them into an HTML webpage

Just diving in for the first time. I hope you all can bear with me. This particular issue might have similarities with others, but from what I've gathered, this is a unique problem that I'm tackling. For your information, my expertise lies in de ...

Angular ngx-translate not displaying image

My Angular application is utilizing ngx-translate to support multiple languages. I am trying to dynamically change an image based on the language selected by the user. However, I am facing difficulty in updating the image when a language is clicked. The ap ...

Is it possible to load conditionally if the browser is switched to Developer Mode?

Currently, I am in the process of debugging my code using Chrome Dev Tools. I have been contemplating whether it is possible to load JavaScript only when DevTools are active in Chrome and ignore it otherwise. This way, I can include debugging logic in my ...

Warning: Angular.js encountered a max of 10 $digest() iterations while iterating through array slices. Operation aborted

JSbin: http://jsbin.com/oxugef/1/edit I am attempting to slice an array into smaller subarrays and iterate through them in order to create a table of divs that are evenly divided. Unfortunately, there seems to be an issue where I am unknowingly overwritin ...

Create a function that binds a select dropdown to each table column header using JavaScript Object Notation (JSON), and then populate an HTML table with the

I have a dynamic table populated with JSON data, and I would like to add a select dropdown for each column. The challenge is that the number of columns is not fixed and they are also populated by JSON. Therefore, I want the select dropdown at the top of ea ...

React checkbox remains checked even after uncheckingIs this revised version

I am currently working on a React application where I display an array of matches as a list of rows. Each row contains two athletes, and users can use checkboxes to predict the winner for each match. Only one athlete per row can be checked. To keep track o ...

Extract the String data from a JSON file

valeurs_d = ""; for (var i = 0; i < keys.length -1 ; i++) valeurs_d += + event[keys[i]] + ", "; var str5 = ","; var str6 = str5.concat(valeurs_d); var valeurs = str6.sub ...

I am currently facing an issue with my Next JS app where the search results page is not showing up when a user enters a query

I am currently working on a search application using Next.js. Within my app directory, I have 3 main files - layout.js, page.js, and searchResults.js Here is the code in layout.js: export const metadata = { title: 'xyz Search', description: ...

The specific error "Argument is not a function, got undefined" in the $broadcast function is exclusive to Angular on Firefox

An Angular error is popping up in Firefox but not in Chrome or IE. The specific error message is: Error: Argument 'myControllerName' is not a function, got undefined. When tracing the stack, it seems to be originating from the $broadcast function ...

An error occurs with Three JS when trying to access a S3 Bucket used as a CDN due to Cross Origin

function displayItem() { startScene(); THREE.ImageUtils.crossOrigin = "anonymous"; var mtlLoader = new THREE.MTLLoader(); mtlLoader.setTexturePath('https://cdn.rubyrealms.com/textures/'); mtlLoader.setPath('https://cdn.ru ...

A guide on testing Vue 2 CSS class styles with vitest and Vue test utils

In the process of developing a component library that utilizes SCSS modules (<component>.module.scss) for styling, I am looking to incorporate tests that verify the correct application of styles. Currently, my tests only check if classes are correctl ...