Tips for refreshing the access token in Vue.js without the need for a complete page refresh by utilizing Axios interceptors

I'm currently working on updating the access token using a refresh token if the current token has expired in my application. Below is the code I have in place:

axios.interceptors.response.use(undefined, function(error) {
  if (error) {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      axios.post("auth/refresh", {
        refreshToken: store.state.refreshToken
      }).then(res => {
        store.dispatch('setToken', res.data.token)
        store.dispatch('setRefToken', res.data.refreshToken)
        error.config.headers[
          "Authorization"
        ] = `Bearer ${res.data.token}`;
      })
    } else {
      return Promise.reject(error);
    }
  }
})

The code successfully retrieves a new access token from the server, but there's an issue. Users need to manually refresh the page for the new Auth Headers to take effect, which is not user-friendly as it could lead to disruptions during ongoing actions.

How can I ensure a smooth transition of tokens without requiring users to manually refresh the page?

Answer №1

axios.interceptors.response.use(
  (res) => {
    return res;
  },
  async (err) => {
    const originalConfig = err.config;
    if (originalConfig.url !== "/login" && err.response) {
      if (err.response.status === 401 && !originalConfig._retry) {
        originalConfig._retry = true;
        try {
          const rs = await axios.post("auth/refresh", {
            refreshToken: store.state.refreshToken
          });
          const {
            token,
            refreshToken
          } = rs.data;
          store.dispatch('setToken', token)
          store.dispatch('setRefToken', refreshToken)
          err.config.headers[
            "Authorization"
          ] = `Bearer ${token}`;
          return new Promise((resolve, reject) => {
            axios.request(originalConfig).then(response => {
              resolve(response);
            }).catch((err) => {
              reject(err);
            })
          });
        } catch (_error) {
          return Promise.reject(_error);
        }
      }
    }
    return Promise.reject(err);
  }
);

I delved deep and researched extensively to identify the issues with my initial code and strategy. After thorough investigation, I found a solution that aligns perfectly with my requirements. It may seem complicated but it effectively resolves the problems.

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

Exploring ways to traverse a foreach loop based on a specific array size

Currently, I am utilizing two distinct for-each loops which are outlined below: <div id="filterarea" data-bind="foreach: { data: filters, as: 'filtercategory' } "> <ul data-bind="foreach: { data: Refiners, as: 'refiner' ...

Having issues with Npm installation not finishing up. Can anyone provide a solution to rectify this

I've been waiting for 30 minutes and my upload is still not completed. How can I resolve this issue? Click here to see the problem ...

What is the process for installing vue-cli?

I'm currently diving into the world of Node Package Manager and Vue, trying to wrap my head around the Vue CLI. On the vue.js website, they provide instructions for running the official Vue CLI: https://i.stack.imgur.com/0OCrc.png I have a few inqu ...

initiate a click event within another click event

This is an HTML Code snippet: <ul id="linkjess"> <li><a href="javascript:setfolder('medewerkers', '1000');">medewerkers 1000</a></li> <li><a href="javascript:setfolder('medewerkers', ...

Can a Vue.js project import the bootstrap.min.js file?

I have been working on a project in Vue.js where Bootstrap is already integrated. The project consists of HTML and CSS which I am converting into a Vue.js application while utilizing Bootstrap classes. However, I have encountered an issue with the dropdown ...

Optimal location for executing Js to render a partial within the Rails framework

I had a plan to update a partial using a click event where data was fetched via ajax. I navigated to my assets/javascripts directory and placed the code in the js file of the module I intended to call it on. I successfully fetched the data and performed so ...

Display error message for checkbox upon submission in AngularJS form validation

I'm having trouble displaying an error message for a checkbox in AngularJS. I want the error message to show up after clicking the submit button if the checkbox isn't checked. Here is what I have tried: <form action="/" method="post" name="m ...

The appearance of the React user interface in my app does not match what is displayed in the inspect element tool

Strange issue at hand. The progress bar in question appears like this: 1 export default function PercentageBar(props) { 2 return ( 3 <div className="w-full h-1 my-1 bg-stone-200"> 4 <div className={`h-1 bg-orange- ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

Components in Vue are not reflecting changes to reactive properties when using composition

I'm currently in the process of developing a notification system, and while it's partially functional, there are some issues. Here is the Composition function I am using: const data = reactive({ notifications: [] }); let notificationKey = 0; ...

"Transforming JSON-LD into a one-of-a-kind HTML template

Are there any template engines available that can convert a JSON-LD response to HTML using JavaScript in the browser or with Node.js? I have looked into SPARQL Web Pages and SPARQL Template Transformation Language, but they seem like large standards that ...

What is the best method for globally configuring the Angular moment timezone?

I integrated angular moment js into my angular application. I am looking to display the date and time based on the time zone of the user accessing the app. However, I am facing difficulty in applying the time zone globally throughout my application. https ...

Importing events from the calendar causes disarray in other data columns when sorted by date

I have a unique code that successfully imports my shared Google Calendar into a spreadsheet. In my medical office, I manage all appointments through a master Calendar. The calendar data includes start time, location, description, and title in columns B, ...

NodeJS API Language Configuration

I'm currently working on integrating the DuckDuckGo Instant Answer Api into my NodeJS application. To do so, I am making a data request from the API using Node Request. var request = require('request'); request('http://api.duckduckgo.c ...

Switching between components in Vue.js

I am a beginner with vue.js and I have encountered a challenge. On my page, I display a list of people with an 'Edit' button next to each person's details. My goal is to switch to another page when the Edit button is clicked, where I can edi ...

Top method for independently scrolling overlapping elements in both the x and y directions

Sorry if this is repeating information. I have a structure of nested divs like this: -container -row In order to enable scrolling without the default scrollbar appearing, each container and row has an additional container. My goal is to be able to scrol ...

changing the name of a key in an array of objects with javascript

I have an array of objects with keys and values as follows: let input = [ { "b1": [ 1, 0 ] }, { "b2": [ 1, 6 ] }, { "total": [ 0, 4 ] }, { "b3plus": [ 0, 2 ] } ] I want to rename the keys of this arr ...

What are the steps to handling an array using AngularJS?

My API is returning a simple JSON array like this: [ "efd98ad-first_key", "100eb0a-second_key" ] I am attempting to display this data in a table using Angular: <div name="listkeys" class="container"> <div class="starter-template"> ...

What is the method for obtaining a dynamic route path within the pages directory in Next.js?

In my code, I have a special Layout component that compares routing queries and displays the appropriate layout based on the query. I'm looking to extend this functionality to handle dynamic routing scenarios, such as invoices/invoice-1. Currently, ...