Skip to main content

Cross Origin Testing

End-to-End Only
info
What you'll learn​
  • What strategies Cypress uses to work around same-origin policy
  • Limitations and workarounds with cross-origin content

Web Security​

Browsers adhere to a strict same-origin policy. This means that browsers restrict access between <iframes> when their origin policies don't match.

Because Cypress works from within the browser, Cypress must be able to directly communicate with your remote application at all times. Unfortunately, browsers naturally try to prevent Cypress from doing this.

To get around these restrictions, Cypress implements some strategies involving JavaScript code, the browser's internal APIs, and network proxying to play by the rules of same-origin policy. It's our goal to fully automate the application under test without you needing to modify your application's code - and we are mostly able to do this.

What Cypress does under the hood​

  • Injects document.domain into text/html pages.
  • Proxies all HTTP / HTTPS traffic.
  • Changes the hosted URL to match that of the application under test.
  • Uses the browser's internal APIs for network level traffic.

When Cypress first loads, the internal Cypress web application is hosted on a random port: something like http://localhost:64874/__/.

After the first cy.visit() command is issued in a test, Cypress changes its URL to match the origin of your remote application, thereby solving the first major hurdle of same-origin policy. Your application's code executes the same as it does outside of Cypress, and everything works as expected.

info
How is HTTPS supported?

Cypress must assign and manage browser certificates to be able to modify the traffic in real time. You'll notice Chrome display a warning that the 'SSL certificate does not match'. This is expected behavior. Under the hood we act as our own CA authority and issue certificates dynamically in order to intercept requests otherwise impossible to access. We only do this for the superdomain currently under test, and bypass other traffic.

Note, that Cypress allows you to optionally specify CA / client certificate information for use with HTTPS sites. See configuring client certificates. If the remote server requests a client certificate for a configured URL, Cypress will supply it.

Limitations​

It's important to note that although we do our very best to ensure your application works normally inside of Cypress, there are some limitations you need to be aware of.

Different superdomain per test requires cy.origin​

Cypress changes its own host URL to match that of your applications. With the exception of cy.origin, Cypress requires that the URLs navigated to have the same superdomain for the entirety of a single test.

If you attempt to visit two different superdomains, the cy.origin command must be used to wrap Cypress commands of the second visited domain. Otherwise, Cypress commands will timeout after the navigation and will eventually error. This is because the commands that were expected to run on the second domain are actually being run on the first domain.

Without cy.origin, you can visit different superdomains in different tests, but not in the same test. Please read our Cross Origin Testing Guide for more information.

Examples of test cases that will error without the use of cy.origin​

  1. .click() an <a> with an href to a different superdomain with subsequent Cypress commands being run.
  2. .submit() a <form> that causes your web server to redirect you a different superdomain where additional Cypress commands are run.
  3. Issue a JavaScript redirect in your application, such as window.location.href = '...', to a different superdomain where additional Cypress commands are run.

In each of these situations, Cypress will lose the ability to automate your application and will error via command timeout unless the cy.origin command is used.

Read on to learn about working around these common problems.

What is a superdomain?​

But what is same superdomain? It's actually very similar to that of same origin! Two URLs have the same origin if the protocol, port (if specified), and host match. Cypress automatically handles hosts of the same superdomain by injecting the document.domain property into the visited text/html pages. This is why navigations without the use of the cy.origin() command are solely scoped to the same superdomain.

caution

Disabling document.domain Injection

In some cases, document.domain injection may cause issues. As of Cypress v12.4.0, disabling document.domain injection is available with the experimentalSkipDomainInjection option. Please read about this experiment for more information

Parts of a URL​

We understand this is a bit complicated to understand, so we have built a nifty chart to help clarify the differences!

Diagram showing the parts of a URL including href broken into protocol, host, pathname, hash and smaller components of hostname, port, path, and search with and example URL

Given the URLs below, all have the same superdomain compared to https://www.cypress.io.

  • https://cypress.io
  • https://docs.cypress.io
  • https://example.cypress.io/commands/querying

The URLs below, however, will have different superdomains/origins compared to https://www.cypress.io.

  • http://www.cypress.io (Different protocol)
  • https://docs.cypress.io:81 (Different port)
  • https://www.auth0.com/ (Different host of different superdomain)

The http://localhost URLs differ if their ports are different. For example, the http://localhost:3000 URL is considered to be a different origin from the http://localhost:8080 URL.

The rules are:

danger

You cannot visit two domains of different superdomains in the same test and continue to interact with the page without the use of the cy.origin() command.

tip

You can visit two or more domains of different origin in different tests without needing cy.origin().

For practical purposes, this means the following:

// This test will run without error
it('navigates', () => {
cy.visit('https://www.cypress.io')
cy.visit('https://docs.cypress.io')
cy.get('selector') // yup all good
})
// this will error because cypress-dx.com doesn't match the cypress.io superdomain
it('navigates', () => {
cy.visit('https://www.cypress.io')
cy.visit('https://www.cypress-dx.com')
cy.get('selector')
})

To fix the above cross-origin error, use cy.origin() to indicate which origin the sequential command should run against:

it('navigates', () => {
cy.visit('https://example.cypress.io')
cy.visit('https://www.cypress-dx.com')
cy.origin('https://www.cypress-dx.com', () => {
cy.get('selector') // yup all good
})
})
it('navigates', () => {
cy.visit('https://www.cypress.io')
})

// split visiting different origin in another test
it('navigates to new origin', () => {
cy.visit('https://cypress-dx.com')
cy.get('selector') // yup all good
})

Cross-origin iframes​

If your site embeds an <iframe> that is a cross-origin frame, Cypress won't be able to automate or communicate with this <iframe>.

Examples of uses for cross-origin iframes​

  • Embedding a Vimeo or YouTube video.
  • Displaying a credit card form from Stripe or Braintree.
  • Displaying an embedded login form from Auth0.
  • Showing comments from Disqus.

If you'd like support for this (check our open issue), or you can disable web security.

Insecure Content​

Because of the way Cypress is designed, if you're testing an HTTPS site, Cypress will error anytime you attempt to navigate back to an HTTP site. This behavior helps highlight a pretty serious security problem with your application.

Example of accessing insecure content​

test.cy.js
cy.visit('https://example.cypress.io')

In your application code, you set cookies and store a session on the browser. Now let's imagine you have a single insecure link (or JavaScript redirect) in your application code.

index.html
<html>
<a href="http://example.cypress.io/page2">Page 2</a>
</html>

Cypress will immediately fail with the following test code:

test.cy.js
cy.visit('https://example.cypress.io')
cy.get('a').click() // will fail

Browsers refuse to display insecure content on a secure page. Because Cypress initially changed its URL to match https://example.cypress.io when the browser followed the href to http://example.cypress.io/page2, the browser will refuse to display the contents.

Now you may be thinking, This sounds like a problem with Cypress because when I work with my application outside of Cypress it works just fine.

However, the truth is, Cypress is exposing a security vulnerability in your application, and you want it to fail in Cypress.

cookies that don't have their secure flag set to true will be sent as clear text to the insecure URL. This leaves your application vulnerable to session hijacking.

This security vulnerability exists even if your web server forces a 301 redirect back to the HTTPS site. The original HTTP request was still made once, exposing insecure session information.

The solution​

Update your HTML or JavaScript code to not navigate to an insecure HTTP page and instead only use HTTPS. Additionally make sure that cookies have their secure flag set to true.

If you're in a situation where you don't control the code, or otherwise cannot work around this, you can bypass this restriction in Cypress by disabling web security.

Same port per test​

Cypress requires that the URLs navigated to have the same port (if specified) for the entirety of a single test. This matches the behavior of the browser's normal same-origin policy.

Common Workarounds​

Let's investigate how you might encounter cross-origin errors in your test code and break down how to work around them in Cypress.

External Navigation​

The most common situation where you might encounter this error is when you click on an <a> that navigates to another superdomain.

index.html
<html>
<a href="https://example.cypress.io">Cypress</a>
</html>
test.cy.js
cy.visit('http://localhost:8080') // where your web server + HTML is hosted
cy.get('a').click() // browser navigates to https://cypress.io
cy.get('selector').should('exist') // Cypress errors
warning

We don't recommend visiting a superdomain that you don't control in your tests which you can read more about here

If you control this superdomain, either by owning the hosted instance or by other means, we recommend testing this superdomain with cy.origin.

test.cy.js
cy.visit('http://localhost:8080') // where your web server + HTML is hosted
cy.get('a').click() // browser navigates to https://example.cypress.io
cy.origin('https://example.cypress.io', () => {
// declare cy.origin command on expected domain
cy.get('selector').should('exist') // Yup all good
})

If you're not in control of this superdomain, we recommend you test that the href property is correct instead of performing the navigation. This will help lead to more deterministic tests.

// this test verifies the behavior and will run considerably faster
cy.visit('http://localhost:8080')
cy.get('a').should('have.attr', 'href', 'https://example.cypress.io') // no page load!

If for any reason the two above methods cannot be used, cy.request() may be an option to verify content as cy.request() is NOT bound to CORS or same-origin policy.

cy.visit('http://localhost:8080')
cy.get('a').then(($a) => {
// pull off the fully qualified href from the <a>
const url = $a.prop('href')

// make a cy.request to it
cy.request(url).its('body').should('include', '</html>')
})

Form Submission Redirects​

When you submit a regular HTML form, the browser will follow the HTTP(s) request.

index.html
<html>
<form method="POST" action="/submit">
<input type="text" name="email" />
<input type="submit" value="Submit" />
</form>
</html>
test.cy.js
cy.visit('http://localhost:8080')
cy.get('form').submit() // submit the form!

If your back end server handling the /submit route does a 30x redirect to a different superdomain, you'll need to use the cy.origin command if running additional Cypress commands after submitting the form.

routes.js
// node / express code on localhost:8080 server
app.post('/submit', (req, res) => {
// redirect the browser to cypress.io
res.redirect('https://example.cypress.io')
})

You can test this with cy.origin, which may look like the following test case:

test.cy.js
cy.visit('http://localhost:8080')
cy.get('form').submit() // submit the form!
cy.origin('cypress.io', () => {
cy.url().should('contain', 'cypress.io')
})

A common use case for this is Single sign-on (SSO), OAuth, Open ID Connect (OIDC), or Authentication as a Service platforms, such as Auth0, Okta, Amazon Cognito, and others.

In these situations, if controlling the domain under test, we recommend that you test these with cy.origin.

test.cy.js
cy.visit('http://localhost:8080')
cy.get('#login').click() // click a login button, which takes us to our authentication page.
cy.origin('cypress.io', () => {
cy.get('#username').type('User1')
cy.get('#password').type('Password123')

// prompts a sign in that redirects to http://localhost:8080 with a token, cookie, or other means of acknowledgement
cy.get('button').contains('Sign In').click()
})

cy.get('#user-name-welcome').should('equal', 'Welcome, User1!')

If for any reason you can't leverage cy.origin, programmatic authentication is still an option. In this situation you may POST to a different server and are redirected elsewhere (typically with the session token in the URL). If that's the case, you can still test this behavior with cy.request().

In fact we can likely bypass the initial visit altogether and POST directly to your SSO server.

cy.request('POST', 'https://sso.corp.com/auth', {
username: 'foo',
password: 'bar',
}).then((response) => {
// pull out the location redirect
const loc = response.headers['Location']

// parse out the token from the url (assuming its in there)
const token = parseOutMyToken(loc)

// do something with the token that your web application expects
// likely the same behavior as what your SSO does under the hood
// assuming it handles query string tokens like this
cy.visit('http://localhost:8080?token=' + token)

// if you don't need to work with the token you can sometimes
// visit the location header directly
cy.visit(loc)
})

JavaScript Redirects​

When we say JavaScript Redirects we are talking about any kind of code that does something like this:

index.html
<html>
<button id="nav">Navigate to Cypress example</button>
<script>
document.querySelector('#nav').addEventListener('click', () => {
window.location.href = 'https://example.cypress.io'
})
</script>
</html>

You can test this with cy.origin, which may look like the following test case:

test.cy.js
cy.visit('http://localhost:8080')
cy.get('#nav').submit() // trigger a javascript redirect!
cy.origin('https://example.cypress.io', () => {
cy.url().should('contain', 'cypress.io')
})

Cross-Origin Errors with cy.origin​

Sometimes, when using cy.origin and especially with websites that are not under your immediate test control, cross-origin errors may still tend to creep up. We don't recommend visiting or interacting with sites you do not control. However, if this is necessary, most of these issues can usually be remedied by applying` the modify obstructive third-party code experimental flag or by disabling web security.

Disabling Web Security​

So if you cannot work around any of the issues using the suggested workarounds above, including modifying obstructive third-party code with cy.origin, you may want to disable web security.

One last thing to consider here is that every once in a while we discover bugs in Cypress that lead to cross-origin errors that can otherwise be fixed. If you think you're experiencing a bug, open an issue.

caution
Chrome only

Disabling web security is only supported in Chrome-based browsers. Settings in chromeWebSecurity will have no effect in other browsers. We will log a warning in this case.

chromeWebSecurity warning in stdout

If you rely on disabling web security, you will not be able to run tests on browsers that do not support this feature.

Set chromeWebSecurity to false​

Setting chromeWebSecurity to false in Chrome-based browsers allows you to do the following:

  • Display insecure content
  • Navigate to any superdomain without cross-origin errors with or without cy.origin
  • Access cross-origin iframes that are embedded in your application

Still here? That's cool, let's disable web security!

Set chromeWebSecurity to false in the Cypress configuration​

const { defineConfig } = require('cypress')

module.exports = defineConfig({
chromeWebSecurity: false,
})

Modifying Obstructive Third Party Code​

Cypress today has the concept of modifying obstructive code, which is code that may interfere with Cypress being able to run your web application. The experimentalModifyObstructiveThirdPartyCode flag provides the same benefits of the modifyObstructiveCode flag, but additionally applies it to third-party .js and .html that is being either loaded or navigated to inside your application. In addition to this, this flag also does the following:

  • Adjusts the User Agent in Electron to appear more chrome-like. This option can be overridden with the userAgent config option.
  • Removes Subresource Integrity (SRI) from modified scripts as they will not execute otherwise.
  • Updates the Sec-Fetch-Dest Metadata header from iframe to document in cases where requests come from the application under test.

Want to enable experimentalModifyObstructiveThirdPartyCode? Let's do it!

const { defineConfig } = require('cypress')

module.exports = defineConfig({
experimentalModifyObstructiveThirdPartyCode: true,
})

Other workarounds​

There are other ways of testing the interaction between two superdomains. The browser has a natural security barrier called origin policy this means that state like localStorage, cookies, service workers and many other APIs are not shared between them anyways. Cypress does offer APIs around localStorage, sessionStorage, and cookies that are not limited to this restriction.

As a best practice, you should not visit or interact with any website not under your control.

If your organization uses Single Sign On (SSO) or OAuth then you might choose to test a 3rd party service other than your superdomain, which can be tested with cy.origin().

We've written several other guides specifically about handling this situation.