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

Newbie: Troubleshooting Vue Errors - "Vue is not recognized"

I'm currently at the beginning stages of learning Vue and am practicing implementing it. However, I keep encountering the errors "vue was used before it was defined" and "Vue is not defined". Below are excerpts from my HTML and JS files for reference. ...

Is there an issue with Vue-router 2 where it changes the route but fails to update the view

I am currently facing an issue with the login functionality on a website that utilizes: Vue.js v2.0.3 vue-router v2.0.1 vuex v0.8.2 In routes.js, there is a basic interceptor setup router.beforeEach((to, from, next) => { if (to.matched.some(record ...

Clicking on a flex card will trigger the opening of a new page where the parsed data will be displayed in a stylish manner using JavaScript

Currently, I am attempting to showcase the data retrieved from the following URL: . My objective is to format the parsed data with a specific style. However, I have encountered difficulties accomplishing this using `window.open()`. Any assistance in resolv ...

Encountered an issue while processing the firebase get request with the following error message: 'Unauthorized request in Angular'

Here are my rules: Utilizing a Firebase database Calling an API URL from this section https://i.stack.imgur.com/auAmd.png I am attempting to retrieve data from a Firebase API in an Angular application, but I keep encountering an 'Unauthorized reque ...

Executing a series of HTTP requests sequentially using Angular 5

I need some guidance on sending an array of HTTP requests in sequential order within my application. Here are the details: Application Entities : Location - an entity with attributes: FanZone fanZone, and List<LocationAdministrator> locationAdmins ...

What is the best way to adjust the screen to display the toggle element when it is opened?

Here is the code I'm currently using to create a toggle button that shows or hides extra content when clicked: $(".toggle .button").click(function() { $(this).next().slideToggle('fast'); }); The issue I am encountering is that if t ...

Troubleshooting PHP webpage with dysfunctional Python AJAX functionality

I have been working on developing a website that integrates with a python script to control GPIO pins on my Raspberry Pi. Unfortunately, I've encountered some issues with the code and need some assistance in troubleshooting. Could someone please revi ...

Instructions for passing the chosen value to Django

I am struggling to set up a search button using Ajax and Django. I need to send the selected value to the server, but I can't seem to retrieve the value from the select HTML tag. The variable value always ends up empty ({"obj":""}). Any ideas? HTML : ...

What strategies can be employed to streamline the code provided?

Can someone help simplify this JavaScript code for me? I would really appreciate it. Thank you! $(function() { $("#show1").click(function() { $("#showmore1").toggle(); }) $("#show2").click(function() { $("#showmore2").toggle(); ...

Issue with Slick Grid not updating after Ajax request

I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

Tips for preventing unstyled content flash when updating CSS files dynamically

The following jQuery function is used to replace CSS files: function UpdateTheme(theme) { var links = $("link"); var _t = theme; $.each(links, function (i, link) { var _h = $(link).attr('href'); _updatedHr ...

Tips for formatting angular text sections

Within the scope of a controller, I have a status variable. After a successful rest PUT request, I add a message to this JavaScript variable. This message is displayed in my template using the {{status}} Is there a way to customize the styling of this mes ...

What is the best way to remove text from a box when a user clicks on it?

After successfully placing G in the selected box upon clicking it, I now want to work on removing it when clicked again. I'm encountering an issue with my current code - can anyone help me identify what's wrong and suggest a solution? Below is ...

Can NODE_PATH be configured in Typescript?

Before, I worked on my React app with ES6 and used NODE_PATH='src' to import files starting from the src folder. However, since switching to Typescript, I've realized that NODE_PATH is not supported. After some investigation, I discovered th ...

What is the best way to swap out an HTML file with another without altering the link?

I'm working on an HTML file, which is basically a webpage. My goal is to create a functionality where clicking a button will dynamically replace the content of the page with another HTML file, complete with its own CSS, JavaScript functions, and other ...

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...

The menu is about to receive some custom styling

I have come across a webpage where I need to make some modifications, but I am unable to locate the script responsible for applying the inline style. This issue only seems to be occurring on the mobile version with the dropdown menu. <div class="is-dri ...

transferring iterative information via ajax data flow

My form includes hidden input fields that are manually declared in the AJAX data without a loop. How can I efficiently loop through them in the AJAX data? Below is my form script: <form method="POST" name="myform"> <?php for($i=1;$i<=5;$i+ ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...