Cypress testing: Include custom HTTP header on each HTTP request

We’re currently implementing Cypress for more resilient end-to-end tests, it is an amazing tool and it looks promising. However, the docs are not being kept up to date.

We want to sent a custom HTTP header in a request and, according to the docs should be done with the cy.server command and its options.

This is not working, so by reverse-engineering (looking into the code on GitHub) we’ve found out that you should provide a different option, namely onAnyRequest.

So this is the final code for sending a custom header on each Cypress HTTP request :

       onAnyRequest:   function (route,  proxy) {
           proxy.xhr.setRequestHeader('CUSTOM-HEADER',  'Header value');

In combination with the userAgent property in cypress.json, we can now detect whether our application is ran in a testing environment.

"userAgent": "Testing"
Like what you read? Give Maarten Merken a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.