Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in the screenshots below:

Screenshot taken during navigation in Chrome browser: https://i.stack.imgur.com/VPk9D.png

Screenshot taken during Cypress test run: https://i.stack.imgur.com/HT27A.png

To verify this issue, I tried replaying the request using curl and including the X-CSRFToken, which resolved the problem. How can I address this issue when running tests with Cypress?

NOTE: This problem arises specifically when performing drag and drop events using the trigger() function.

Answer №1

Recently encountered a problem and managed to find a solution:

To maintain session data (Cookies) while running tests, utilize the cy.session() command. Refer to cypress documentation for more details.

Here's an example solution implemented in my application:

Cypress.Commands.add(
  'login',
  (username, password) => {
    
    cy.session('user', () => { // <-- implementing command here
    // Initial login request to DJANGO which sets
    // Cookies (XSRF-TOKEN, session_id)
    cy.request({
        method: 'POST',
        url: apiUrl,
        headers: {
          Accept: 'application/json, text/plain, */*',
        },
        body: {
          password: pw,
          username: user,
        },
      }).then((response) => {
        const user = response.body.user
        user.token = response.body.access_token

        window.localStorage.setItem('auth.currentUser', JSON.stringify(user))
      })
    })
  })

With this setup, cookies are already configured in my test:


 it('Signs in as Premium User, creates a team, and deletes it', () => {
    cy.login('user', 'password')

    // execute test requests that rely on XSRF-TOKEN being set at this point
  })

Considering the relatively new nature of the cy.session() feature, you may need to enable a flag in your cypress.config.ts:

import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    experimentalSessionAndOrigin: true,
    // ....
  }

Hopefully, this information proves useful to someone :)

Answer №2

When using Cypress, cookies are automatically cleared between each test. This means that even if you set your cookies correctly during the login process, they will be discarded once the test block (it, specify, describe, or context) finishes executing. Consequently, subsequent network requests will start with a clean slate.

To overcome this behavior, you can utilize Cypress.Cookies.preserveOnce: https://docs.cypress.io/api/cypress-api/cookies.html#Preserve-Once

Here's an example of how I tackled a similar issue:

    beforeEach(() => {
        Cypress.Cookies.preserveOnce('XSRF-TOKEN', 'session_id')
    })

If you want to maintain this cookie state across all your test suites (including separate spec.js files), you can include the following in your cypress/support/index.js file:

Cypress.Cookies.defaults({
    preserve: ['XSRF-TOKEN', 'session_id']
})

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

The issue of React Js's inline style malfunctioning when using a loop condition

Having some trouble with setting different backgrounds for items in a loop in React JS. I attempted to use inline styles to make it dynamic, but no luck so far. Any tips or solutions? { main.map((item, index) => ( <a key={index} href=&apo ...

Every time I try to retrieve my JavaScript code, I am bombarded with endless prompts that prevent me

Desperate for assistance! I have been using a website called "codepen" for my javascript coding, but I mistakenly triggered infinite prompts every time I open the project. Now, I am unable to access the code and despite my efforts in searching for a solu ...

Python on the server side generating a downloadable zip file

After passing a parameter from my client to a python script on the server through a GET request, the script initiates a process that results in the creation of a zip file. However, upon making an AJAX call in my client-side JavaScript, I am only able to co ...

Utilizing Angular: Importing Scripts in index.html and Implementing Them in Components

Currently, I am attempting to integrate the Spotify SDK into an Angular application. While I have successfully imported the script from the CDN in index.html, I am encountering difficulties in utilizing it at the component level. It seems like there may be ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...

When using my webrtc technology, I configure my sdp to establish a recvonly direction

While attempting to make a video call using WebRTC, I encountered bugs during testing. My goal is to integrate this project into a webview for my Android app. I conducted testing using phone-pc and phone-phone scenarios. Scenario A: When the PC initialize ...

Encountered an error while reloading the page: "Unable to read property 'ArtisanID' of undefined."

Every time I refresh the page, an error pops up saying: Cannot read property 'ArtisanID' of undefined. Any suggestions on how to troubleshoot this issue? I'm relatively new to this framework and my intuition tells me that the component ins ...

Tips for dismissing loader in Ionic 4

I'm struggling to programmatically dismiss the loader. I've developed two separate methods - one for displaying the loader and another for dismissing it. These methods are called accordingly when needed. async showLoader() { this.loader = a ...

What is the best method for automating the transfer of data from a database to the user interface of a website using html and javascript?

As a volunteer coordinator for a non-profit organization, I have some basic experience working with Python. I am willing to dedicate fewer than 8 hours of learning time to my current project in order to automate certain tasks (or else I will do them manual ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Encountering issues while retrieving information from database through AJAX and PHP

Update: The initial section of this question has been resolved and is now updated with the working code. ~ I'm currently developing a JavaScript application, and I'm encountering challenges with making an AJAX call function properly. While I ha ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Angular: No routes found that match the URL segment

I encountered an issue with my routes module where I am receiving the error message Cannot match any routes. URL Segment: 'edit-fighter' when attempting to navigate using the <a> link. The only route that seems to work is the champions-list ...

Angular allows users to interact with objects in THREE.js by simply clicking on

I've tried numerous solutions, but none of them seem to work - the cube is in the wrong position and only one face is detected. Since the angular event is easy to call. 1. Insert a tag into the HTML code. <div (click)="onClickCanvas($event)"> ...

Ways to determine if a user is using a PC using JavaScript

I am developing a website using node.js that will also serve as the foundation for a mobile app. The idea is to have users access the website on their phones and use it like an app. But I want to implement a feature that detects when the site is being vi ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

Utilize JavaScript's $.post function to export PHP $_POST data directly into a file

After spending hours trying to figure this out, I've come to the realization that I am a complete beginner with little to no knowledge of what I'm doing... The issue I'm facing is related to some JavaScript code being triggered by a button ...

Configure Protractor's configuration file to utilize a personalized reporter

I'm in the process of setting up end-to-end tests using protractor.js, but I am not happy with how the default reporter displays results on my terminal window. Is there a way to customize the reporter configuration to make it easier to read and more ...

What steps can I take to resolve the "this is undefined" issue in VueJS?

Whenever I include the line this.$store.commit('disconnect');, it throws a "this is undefined" error. Any suggestions on how to resolve this issue? store/index.js : export const state = () => ({ log: false, user: {token: null, id: null, u ...

Having trouble retrieving the desired data from the JSON file

My current code is not giving me the expected results while trying to access JSON values with jQuery. Any suggestions on how I can resolve this issue? // JSON response: [{ "private": "8044553.0" }, { "governmentdocs": "98952.0" }, { "officiald ...