axios interceptor - delay the request until the cookie API call is completed, and proceed only after that

Struggling to make axios wait for an additional call in the interceptor to finish. Using NuxtJS as a frontend SPA with Laravel 8 API.

After trying various approaches for about 4 days, none seem to be effective.

TARGET

Require axios REQUEST interceptor to verify cookie existence. If cookie is missing, initial API call should fetch the cookie before proceeding with other requests.

APPROACH

Implemented Axios interceptor for requests that triggers a call to the cookie endpoint if cookie is absent.

Also caching the cookie request promise for multiple calls when cookie is still not retrieved.

ISSUE

Expected behavior was to first call the cookie API and then all subsequent endpoints but experiencing two different outcomes with the code provided:

A) Triggering extra cookie call but not in the expected sequence, resulting in multiple hits on Laravel endpoint without cookies leading to excessive sessions.

B) No calls being made at all (as shown in the example).

Confused about where I might be going wrong. Any insights?

export default function ({$axios, redirect, $cookiz, store}) {
  $axios.onRequest(async request => {
    const xsrfCookie = $cookiz.get('XSRF-TOKEN')
    if (xsrfCookie === undefined || xsrfCookie === null || xsrfCookie === '') {
      await store.dispatch('login/getXsrfCookie')
      $axios.request(request)
    }
    $axios.request(request)
  })
}

  getXsrfCookie(context) {
    if (context.state.xsrfCookiePromise instanceof Promise) {
      return context.state.xsrfCookiePromise
    }
    const xsrfCookiePromise = this.$axios.get('/csrf-cookie').then(response => {
      context.commit('setXsrfCookiePromise', null)
      console.log('This is the cookie response', response)
    })
    context.commit('setXsrfCookiePromise', xsrfCookiePromise)

    return context.state.xsrfCookiePromise
  }

Answer №1

My knowledge of nuxt is limited, and I have a basic understanding of axios interceptors. However, upon reviewing the code...

  • It seems like the goal is to store a cookie, not just the promise for it.
  • The involvement of the store may not be necessary in this scenario.
  • You might be able to achieve this using your cookie plugin by utilizing the set method. Make sure to check the options parameter mentioned here.
async getXsrfCookie() {
  if (!$cookiz.get('XSRF-TOKEN')) {
    // It's important to verify which part of the response should be stored and whether stringification is needed.
    const response = await this.$axios.get('/csrf-cookie');
    $cookiz.set('XSRF-TOKEN', response.data);
  }
}
      
export default function ({$axios, redirect, $cookiz, store}) {
  $axios.onRequest(async request => {
    await getXsrfCookie();
    return $axios.request(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

How can I populate an array to use in a datatable when rendering?

How can I ensure that my datatable renders with the proper data on my webpage without needing to interact with the sort button? Where should I populate the array for use in a datatable so that it occurs before the rendering? export function MyComponent() ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

<dt> and <dd> have not been added after the previous element

I can't seem to figure out why the dt and dd elements are not being added to the dl I created. Here's my initial attempt: // Dictionary list var words = [ { term: "Procrastination", definition: "Pathological tendency to s ...

NodeJS and Express server is having trouble accessing the linked JavaScript file(s) from the HTML document

I'm facing a challenge with my web hosting server on AWS while using express.js. I have encountered the following error: root@ip(censored):/home/ubuntu/(censored)# /home/ubuntu/(censored)/routes/index.js:15 $(document).ready(function() { ^ Referen ...

Utilizing AJAX to submit a combination of text fields and files in an HTML form

Just starting out with AJAX and JQuery, I'm curious if it's possible to send data from an HTML form, including a text file and two separate text boxes, via an AJAX request. So far, I've managed to send the data from the text boxes but not th ...

With jQuery's .text() method, it is possible to modify the first span's Bootstrap class, but not the

As someone who is new to javascript, html, and jquery, I have been trying to change the text of 2 span elements in the same div using jquery's .text() command. Despite going through various solutions provided by different questions, none seem to work ...

Why does the ng-click function fail to execute when using the onclick attribute in AngularJS?

Whenever I try to invoke the ng-click function using onClick, I encounter an issue where the ng-click function is not being called. However, in my scenario, the model does open with the onClick function. //Function in Controller $scope.editProductDetail ...

The daily scripture quote from the ourmanna.com API may occasionally fail to appear

I've been trying to display the daily verse from ourmanna.com API using a combination of HTML and JS code, but I'm encountering an issue where the verse doesn't always show up. I'm not sure if this problem is on the side of their API or ...

Using absolute positioning on elements can result in the page zooming out

While this answer may seem obvious, I have been unable to find any similar solutions online. The problem lies with my responsive navbar, which functions perfectly on larger screens. However, on mobile devices, the entire website appears zoomed out like thi ...

The $scope.$watch function is not triggering events within a controller of a ui.bootstrap.modal

Currently, I am utilizing UI bootstrap for Angular and have successfully integrated the ui.bootstrap.modal component into my project. Everything seems to be working smoothly except for one issue I am encountering. Despite setting up a $scope.$watch to trac ...

Tampermonkey's .click() function appears to be malfunctioning

I am attempting to automate clicking a button in Tampermonkey, but for some reason the code is not working as expected. Interestingly, when I manually run the code in the console, it functions perfectly. Here is the snippet: $(document).ready(function() ...

"Implementing jQuery to dynamically set the href attribute for a link when

My website features a tabbed menu that displays content from various WordPress categories including Cars, Trucks, and Buses. The active tab is randomly selected each time the page is reloaded. However, there seems to be an issue with the "View More" button ...

Removing specific text from a textarea containing a vast quantity of information

I developed a simple XML formatter using HTML and Javascript. I am looking to incorporate a delete feature into it. Essentially, I want the ability to remove an entry without affecting any other data. <contact <!--Jane Smith--> first_name="Jane" ...

The useEffect alert is triggered before the component is re-rendered

Can someone help me understand why the HP in the code below is displayed as "1" when the alert is thrown, and only set to "0" after I confirm the alert? Shouldn't the component be rerendered before the alert is thrown so that it has already been displ ...

New functionality introduced in JavaScript ES6: Sets

I am currently using a Set data structure to store unique primitive values, but I am facing an issue when trying to add unique objects based on their property values. Below is an example of my code: "use strict" var set = new Set(); var student1 = { ...

Guide to assigning a value to a model in AngularJS by utilizing a select input with an array of objects

I'm new to AngularJS and I've encountered a challenge that requires an elegant solution. My application receives a list from the server, which is used as the data source for the select tag's options. Let's assume this list represents a ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

Error message: Unable to load image from local source in Vue application

I am currently working on creating a simple dice roll game in VueJs. However, I encountered an issue with using the dice images as it keeps giving me a 404 error. When I attempted to use require(), it stated that the function was not defined. After some t ...