Warning: Axios is sending duplicate CSRF-Tokens, resulting in a CSRF-Token mismatch

I am facing an issue with my Laravel/Vue with Sanctum setup. The problem is simple:

When I send a token request and log in the user, the server responds with a new token. However, Axios is adding this new token along with an additional token that is always the same and expired.

Here is the code snippet:

await APIClient.get("/sanctum/csrf-cookie")
return APIClient.post("/api/user/login", payload);

Upon inspecting DevTools/Network tab:

  • csrf-cookie request => response-headers contains the valid XSRF-TOKEN
  • login request => request-headers, SET-COOKIE property contains XSRF-TOKEN (old expired value) ; laravel_session ; XSRF-TOKEN (new valid value)

The issue lies with the presence of the old expired value. I have not included any code in my project that adds this token.

Below is my Axios client configuration:

const APIClient = axios.create({
    baseURL: constants.PATHS.url,
    withCredentials: true, // necessary for handling the CSRF token
});

Any assistance you can provide would be greatly appreciated.

Answer №1

I'm having trouble comprehending your query. Are you unsure about how to include either an (old expired value) or a (new valid value) in the header of axios? My suggestion would be to utilize axios as a property of the window object. This way, it's simpler to modify its attributes:

window.axios.defaults.headers.common['token'] = "aaa"; //insert a header

Answer №2

After extensive research, I have discovered a foolproof solution. By clearing the cookies of the document each time you logout, you ensure that the token will consistently be updated to a new value, thus preventing any duplication of the old token. This bug has been observed in certain scenarios, so it is imperative to take this precaution.

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

Angular select automatically saves the selected option when navigating between views

I would like the selected option in my dropdown menu to stay selected as I navigate through different views and then return back. Here is the view: <select ng-model="selectedSeason" class="form-control" ng-options="season as 'Season '+ seas ...

What causes a user to log out when the page is refreshed in a React/Redux application?

Each time the page is reloaded in my React/Redux application, the user gets logged out, even though I have stored the token in localStorage. There seems to be an error somewhere. The token should ideally be saved when the user logs in and not lost upon rel ...

Pre-rendering Vue.js for SEO with prerender-spa-plugin becomes unresponsive during the npm run build process

My current issue arises when attempting to execute the command npm run build while utilizing the pre-rendering plugin in my webpack configuration. I incorporated some advanced options in webpack such as: `captureAfterDocumentEvent: 'fetch-done' ...

problem with displaying sidebar in Ember template

Using Ember, I have a login page where I don't want to display the header or sidebar navigation for my site until the user is authenticated. Once they are logged in, I want the header and sidebar to be visible. Currently, I am achieving this by checki ...

The Checkbox generated by Javascript is failing to properly close the tag

When I generate a checkbox in this manner and insert it into my table's [TD] tag: let checkbox = document.createElement('input'); checkbox.type = 'checkbox'; td.appendChild(checkbox); It yields: <tr> <td> ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...

Combining objects using Vue.js and Axios

After fetching data from an axios request and a fetch call to an RSS feed, I have two objects with fields that serve the same purpose but have different names. See the example below: Two Object The objects currently look like this: Obj1 = {title: "Main te ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

Can saving data within a mongoose pre-save hook initiate a continuous loop?

Currently, I am developing an API for a forum system which includes functionalities for users, forums, and posts. In my MongoDB Database, there is a 'categories' collection where each category acts as a container for a group of forums. Each categ ...

Bizarre error when injecting Factory into Controller in AngularJS

After scouring through countless posts on various forums, I have yet to find a solution to my unique problem. I find myself in a peculiar situation where I am trying to inject a Factory into a Controller, and despite everything appearing to be in order, i ...

Attempting to develop a next.js web application using Vercel has hit a roadblock for me. Upon running the "vercel dev" command in the terminal, an error message is

vercel dev Vercel CLI 28.5.3 > Creating initial build node:events:491 throw er; // Unhandled 'error' event ^ Error: spawn cmd.exe ENOENT at ChildProcess._handle.onexit (node:internal/child_process:285:19) at onErrorNT (nod ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

Managing Image Quality with Unsplash API

How can we ensure high quality images are embedded on the web using Unsplash API or other methods? The image displayed in the example below appears blurry and unclear compared to the original image. Original Image link: Example of embedding the image abo ...

Storing property data outside of the render method in ReactJS is key for efficient

I have encountered an issue while attempting to map data outside of the render method in my function and return it within the render. The mapping error is causing confusion as I am uncertain about its underlying cause. Below is the function responsible fo ...

Creating a compact array from a larger array in JavaScript

I am currently using the jquery.bracket library and I am looking to split a large array into pairs like ["'Team 1', 'Team 2'"],["'Team 3', 'Team 4'"] from var all= ["'Team 1', 'Team 2'","'T ...

The findByIdAndUpdate() function lacks the ability to modify the collection

I'm encountering an issue when trying to update a product using mongodb and redux. It seems that the database is not reflecting the changes after I attempt to update the product. Can someone please assist me with this problem? Here is my product.js f ...

Developing a personalized language setting in Nuxt.js for internationalization

I'm facing an issue with my application where I am struggling to figure out how to create a custom locale. For example, I have routes like /hello and /ja/hello, where the first route is for the default English language and the second one is for Japane ...

The process of utilizing variables to form objects in ES6

My ES5 code contains a variable as shown below. var options = { clientId : clientId, keepAlive : keepAlive, clean : clean, reconnectPeriod : reconnectPeriod, will : lastWillMessage }; If I want to convert this to ES6, I can do so by writing ...

There are additional elements that can be toggled, but I prefer to only toggle the one that I have selected

Every time I click on a table a, intending to toggle the .info inside the same div, it also toggles the .info in other divs. Can someone provide assistance with this issue? function info() { $('.table a').click(function() { $('.info ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...