Cypress testing: Include custom HTTP header on each HTTP request

Maarten Merken
Apr 26, 2018 · 1 min read

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 :

cy.server({       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.

cypress.json:{
"userAgent": "Testing"
}

Agilix

Consultancy & Development

Maarten Merken

Written by

Freelance Software Engineer

Agilix

Agilix

Consultancy & Development

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade