| | |

Cypress 20 ๐ŸŒฒ Cross-Origin Testing โ€” cy.origin and multi-domain flows

โฑ๏ธ Estimated read: 16 min | |

Modern authentication rarely stays on one domain. A login flow starts on your application, redirects to an identity provider like Okta, Auth0, or Google, and returns with a token. Cypress treats each distinct originโ€”scheme, host, and portโ€”as a separate security boundary, and since Cypress 14, navigating between origins without cy.origin() is refused outright . The command serializes the test context into the target origin, runs the callback there, and serializes the result back, creating a controlled bridge across domains that the browser would otherwise block.

This chapter covers cy.origin() in depth: the exact origin comparison rules that determine when it is required, the args serialization mechanism that passes data into the callback, the Cypress.require() dependency loading that makes shared code available inside the secondary origin, and the SSO login pattern that combines cy.origin() with cy.session() for cached cross-domain authentication. It also addresses the most common failure modeโ€”redirects that land on a different origin before cy.origin() can be calledโ€”and the strategies for handling OAuth flows that navigate away from the application under test. By the end, you will be able to test any multi-domain workflow without hitting cross-origin errors.

Key point: cy.origin() runs a callback inside a different origin and serializes data across the boundary using the structured clone algorithm. Variables defined outside the callback are invisible inside it unless passed through args. The command cannot be nested, and it cannot be called if the browser is already on the target origin.


Why cy.origin exists

The security boundary. Browsers enforce the same-origin policy: JavaScript running on https://app.example.com cannot read the DOM of https://auth.example.com. Cypress runs test code inside the browser, so it inherits this restriction. Before Cypress 14, Cypress worked around the boundary by injecting document.domain, which allowed subdomains of the same parent domain to communicate. Chrome removed the document.domain setter, and Cypress replaced the workaround with cy.origin(), which injects a separate Cypress instance into the secondary origin and establishes bidirectional communication between the two .

The serialization constraint. The two Cypress instancesโ€”one in the primary origin, one in the secondaryโ€”communicate by serializing messages. Data passed into cy.origin() through args is copied with the structured clone algorithm, which handles strings, numbers, booleans, arrays, plain objects, dates, maps, and sets, but rejects functions and DOM elements . This is not an implementation detail; it is the defining constraint of the API. A callback cannot close over variables from the test scope because the callback is extracted and executed in a different JavaScript context.

The redirect trap. The most common cy.origin() failure is not a serialization errorโ€”it is a timing error. If cy.visit() triggers a server-side redirect to the identity provider, Cypress lands on the new origin before the test can call cy.origin(). Calling cy.origin() with the identity provider’s URL then throws cy.origin() requires the first argument to be a different origin than top because the browser is already there . The solution requires either wrapping the initial visit inside cy.origin() or triggering the redirect through a UI action that the test can control.


a. Origin comparison rules and when the command is required

Cypress compares origins by scheme, host, and port. The path is irrelevant. A test running on https://app.cypress.io can visit https://app.cypress.io/settings without cy.origin() because only the path changed. Visiting https://auth.cypress.io requires it because the subdomain differs. Visiting https://app.cypress.io:8443 requires it because the port differs .

// cypress/e2e/origin-rules.cy.ts
describe('Origin comparison', () => {
  it('does not require cy.origin for same-origin navigation', () => {
    cy.visit('https://app.example.com/dashboard');
    // Same scheme, host, and port; path differs only
    cy.visit('https://app.example.com/settings');  // โœ… no cy.origin needed
  });

  it('requires cy.origin for a different subdomain', () => {
    cy.visit('https://app.example.com');
    cy.origin('https://auth.example.com', () => {
      // Runs inside the auth subdomain
      cy.visit('/login');                           // โœ… scoped to auth.example.com
      cy.get('#username').type('user@example.com');
    });
  });

  it('requires cy.origin for a different port', () => {
    cy.visit('http://localhost:3000');
    cy.origin('http://localhost:4000', () => {
      cy.visit('/api/health');                      // โœ… different port, different origin
      cy.get('body').should('contain', 'ok');
    });
  });
});

Calling cy.origin() with the current origin throws an error. Before Cypress 14, injectDocumentDomain allowed subdomains of the same parent to communicate without cy.origin(). That option is deprecated and will be removed, so tests relying on it should migrate to explicit cy.origin() calls .

The same-origin rule also applies to subdomains with injectDocumentDomain disabled (the default since Cypress 14). A test on app.example.com cannot reach auth.example.com without cy.origin(), even though both share the example.com parent.


b. Passing data with args and the serialization boundary

Every value the callback needs must be passed through the args option. Variables defined outside the callback are not visible inside it. A missing variable throws a ReferenceError that names the variable and points to args as the fix .

// cypress/e2e/login-origin.cy.ts
describe('Passing data across origins', () => {
  it('passes credentials through args', () => {
    const credentials = {
      username: 'alice@example.com',
      password: 'secret123',                      // sensitive: avoid logging
    };

    cy.visit('https://app.example.com');
    cy.get('[data-test="sso-button"]').click();   // triggers redirect to IdP

    cy.origin(
      'https://auth.example.com',
      { args: { credentials } },                  // โœ… copied into secondary origin
      ({ credentials }) => {
        // Inside the callback, only args values are available
        cy.get('#username').type(credentials.username);
        cy.get('#password').type(credentials.password, { log: false });
        cy.get('button[type="submit"]').click();
      }
    );

    // Back on the primary origin
    cy.url().should('include', 'app.example.com/dashboard');
  });
});

The structured clone algorithm copies plain objects, arrays, strings, numbers, booleans, dates, maps, and sets. Functions do not survive the copy. A page object instance passed through args arrives as a plain object with its properties but without its methods. The correct pattern is to pass the selectors the page object needs, not the instance itself, or to load the page object class inside the callback with Cypress.require() .

The yielded value from the callback is also serialized back to the primary origin with the same rules. A callback cannot return a DOM element or a function; it can return strings, numbers, plain objects, and other cloneable values.


c. Loading dependencies and shared code with Cypress.require

Inside the cy.origin() callback, require() and import() are not available because the callback is extracted and executed outside the normal test bundle. Cypress.require() is the replacement: it loads npm packages and local files into the secondary origin’s context. The experimentalOriginDependencies configuration option must be enabled .

// cypress.config.ts
import { defineConfig } from 'cypress';

export default defineConfig({
  experimentalOriginDependencies: true,           // โœ… enables Cypress.require
  e2e: {
    // other config
  },
});
// cypress/e2e/shared-code.cy.ts
describe('Shared code in secondary origin', () => {
  it('uses a page object loaded inside the callback', () => {
    cy.visit('https://app.example.com');
    cy.get('[data-test="sso-button"]').click();

    cy.origin('https://auth.example.com', () => {
      // Load the page object class inside the secondary origin
      const { LoginPage } = Cypress.require('../support/pages/login-page');
      const loginPage = new LoginPage();           // โœ… instance created inside

      loginPage.fillUsername('alice@example.com');
      loginPage.fillPassword('secret123');
      loginPage.submit();
    });
  });

  it('loads a lodash utility inside the callback', () => {
    cy.origin('https://auth.example.com', () => {
      const _ = Cypress.require('lodash');         // โœ… npm package available
      cy.get('#username').type(_.capitalize('alice'));
    });
  });
});

Custom commands defined in cypress/support/commands.ts are available in the primary origin automatically. To make them available inside cy.origin() callbacks, load the commands file once in a before() hook inside the origin. Code loaded this way stays available for every later cy.origin() call for the same origin until the spec file ends .

before(() => {
  cy.origin('https://auth.example.com', () => {
    Cypress.require('../support/commands');        // โœ… makes custom commands available
  });
});

The Cypress.require() call must use a static string argument. Dynamic values, destructured require, or multi-line expressions do not work. Only .js, .jsx, .ts, .tsx, .mjs, and .json files are supported .


Complete Example Session

// ============================================
// PART 1: CONFIGURATION
// ============================================
// cypress.config.ts
import { defineConfig } from 'cypress';

export default defineConfig({
  experimentalOriginDependencies: true,           // enables Cypress.require
  e2e: {
    baseUrl: 'https://app.example.com',
  },
});

// ============================================
// PART 2: SSO LOGIN COMMAND WITH SESSION CACHING
// ============================================
// cypress/support/commands.ts
Cypress.Commands.add('loginWithSSO', (email: string, password: string) => {
  cy.session([email, password], () => {
    // Start on the app origin
    cy.visit('/login');

    // Click the SSO button; the app redirects to the IdP
    cy.get('[data-test="sso-button"]').click();

    // ============================================
    // PART 3: ENTERING THE IDENTITY PROVIDER ORIGIN
    // ============================================
    cy.origin(
      'https://auth.example.com',
      { args: { email, password } },              // data must pass through args
      ({ email, password }) => {
        // ============================================
        // PART 4: INTERACTING WITH THE IDP LOGIN FORM
        // ============================================
        cy.get('#username').type(email);
        cy.get('#password').type(password, { log: false });
        cy.get('button[type="submit"]').click();
      }
    );

    // ============================================
    // PART 5: RETURNING TO THE APPLICATION ORIGIN
    // ============================================
    // Cypress is back on the app origin after the redirect
    cy.url().should('include', '/dashboard');
  });
});

// ============================================
// PART 6: USING THE COMMAND IN A TEST
// ============================================
describe('Orders with SSO authentication', () => {
  beforeEach(() => {
    cy.loginWithSSO('alice@example.com', 'secret123');
    cy.visit('/orders');                          // required after cy.session
  });

  // ============================================
  // PART 7: FIRST TEST CREATES THE SESSION
  // ============================================
  it('lists orders after SSO login', () => {
    cy.get('[data-test="order-row"]').should('have.length.at.least', 1);
  });

  // ============================================
  // PART 8: SUBSEQUENT TESTS RESTORE THE SESSION
  // ============================================
  it('opens an order without re-authenticating', () => {
    // cy.session restored the cached cookies; setup did not run
    cy.get('[data-test="order-row"]').first().click();
    cy.url().should('include', '/orders/');
  });

  // ============================================
  // PART 9: USING Cypress.require FOR SHARED CODE
  // ============================================
  it('loads a page object inside the IdP callback', () => {
    cy.visit('/settings');
    cy.get('[data-test="reauth-button"]').click();

    cy.origin('https://auth.example.com', () => {
      const _ = Cypress.require('lodash');        // npm package
      cy.get('#username').type(_.toLower('ALICE@EXAMPLE.COM'));
      cy.get('#password').type('secret123', { log: false });
      cy.get('button[type="submit"]').click();
    });

    cy.url().should('include', '/settings');
  });

  // ============================================
  // PART 10: HANDLING REDIRECT-BASED OAUTH
  // ============================================
  it('handles an OAuth flow that redirects immediately', () => {
    // When cy.visit redirects to the IdP, wrap the visit inside cy.origin
    cy.origin('https://auth.example.com', () => {
      cy.visit('https://app.example.com/oauth/authorize?client_id=test');
      // Now on the IdP origin; complete the consent
      cy.get('#approve-button').click();
    });

    // After approval, the browser returns to the app origin
    cy.url().should('include', 'app.example.com/callback');
  });
});

The ten parts above cover the full cy.origin() workflow: configuration, the SSO login command with cy.session(), entering the IdP origin, interacting with its form, returning to the application origin, using the command across tests with session caching, loading dependencies with Cypress.require(), and handling the redirect trap that occurs when the initial visit lands on a different origin before cy.origin() can be called.


Quick Reference

Origin Comparison Rules

URL DifferenceRequires cy.origin()?Reason
Path onlyNoSame origin
Port differsYesDifferent origin
Subdomain differsYesDifferent host
Scheme differsYesDifferent origin
Same origin passedErrorRedundant

cy.origin Options

OptionTypePurpose
originStringTarget origin URL
argsObjectData serialized into callback
callbackFunctionCode executed in secondary origin

Serialization Rules

TypeCopies AcrossExample
String, number, booleanYes'hello', 42, true
Array, plain objectYes{ user: 'alice' }
Date, Map, SetYesnew Date()
FunctionNo() => {}
DOM elementNoelement
Class instance methodsNoInstance arrives without methods

Cypress.require Support

FeatureSupportedNotes
npm packagesYesCypress.require('lodash')
Local filesYesCypress.require('./utils')
File extensions.js, .ts, .jsx, .tsx, .mjs, .jsonOthers rejected
Dynamic stringsNoMust be static literal
Outside callbackNoErrors if used elsewhere

Best Practices

โœ… Do This:

// Pass every needed value through args
cy.origin(url, { args: { username, password } }, ({ username, password }) => {  // โœ…
  cy.get('#user').type(username);
});

// Load shared code with Cypress.require inside the callback
cy.origin(url, () => {
  const { LoginPage } = Cypress.require('../support/pages');  // โœ…
});

// Wrap the initial visit inside cy.origin when a redirect is expected
cy.origin('https://auth.example.com', () => {
  cy.visit('https://app.example.com/oauth');  // โœ… redirect stays inside origin
});

// Combine with cy.session for cached SSO authentication
cy.session([email, password], () => {
  cy.origin(idpUrl, { args: { email, password } }, () => { /* login */ });  // โœ…
});

// Use { log: false } when typing secrets in the secondary origin
cy.get('#password').type(password, { log: false });  // โœ…

โŒ Don’t Do This:

// Don't close over variables from the test scope
const user = 'alice';
cy.origin(url, () => {
  cy.get('#user').type(user);  // โŒ ReferenceError: user is not defined
});

// Don't nest cy.origin() calls
cy.origin(urlA, () => {
  cy.origin(urlB, () => { /* ... */ });  // โŒ nested origins not allowed
});

// Don't call cy.origin() when already on the target origin
cy.visit('https://auth.example.com');
cy.origin('https://auth.example.com', () => { /* ... */ });  // โŒ error

// Don't pass a page object instance through args
cy.origin(url, { args: { loginPage } }, ({ loginPage }) => {
  loginPage.fill();  // โŒ methods are lost in serialization
});

// Don't use require() or import() inside the callback
cy.origin(url, () => {
  const _ = require('lodash');  // โŒ use Cypress.require()
});

Common Pitfalls

PitfallWhy It HappensFix
ReferenceError inside callbackVariable not passed through argsPass all values explicitly
cy.origin() requires different originAlready on target origin after redirectWrap initial visit in cy.origin()
Nested cy.origin() errorCalled inside another origin callbackMove to top level of test
Page object methods missingInstance serialized, methods lostUse Cypress.require() to load class
Cypress.require undefinedexperimentalOriginDependencies not enabledEnable in config
Custom commands unavailable in IdPNot loaded into secondary originLoad via Cypress.require() in before()

Real-World Examples

1. Basic SSO login through an identity provider

cy.origin('https://auth.example.com', { args: { email, password } }, ({ email, password }) => {
  cy.get('#username').type(email);
  cy.get('#password').type(password, { log: false });
  cy.get('#submit').click();
});

2. Passing a simple value through args

cy.origin(url, { args: { userId: 42 } }, ({ userId }) => {
  cy.get('#user-id').should('have.value', userId);
});

3. Loading lodash inside the callback

cy.origin(url, () => {
  const _ = Cypress.require('lodash');
  cy.get('#name').type(_.capitalize('alice'));
});

4. SSO login cached with cy.session

cy.session('sso', () => {
  cy.visit('/login');
  cy.get('[data-test="sso"]').click();
  cy.origin(idpUrl, { args: { email, password } }, ({ email, password }) => {
    cy.get('#username').type(email);
    cy.get('#password').type(password);
    cy.get('#submit').click();
  });
});

5. Handling a redirect that lands on the IdP immediately

cy.origin(idpUrl, () => {
  cy.visit('https://app.example.com/oauth/authorize');
  cy.get('#approve').click();
});

6. Loading custom commands into the secondary origin

before(() => {
  cy.origin(idpUrl, () => {
    Cypress.require('../support/commands');
  });
});

7. Checking a value returned from the secondary origin

cy.origin(idpUrl, () => {
  return cy.get('#session-token').invoke('text');
}).then((token) => {
  expect(token).to.have.length.greaterThan(0);
});

8. Navigating to multiple origins in succession

cy.origin('https://auth.example.com', () => { cy.visit('/login'); });
cy.origin('https://api.example.com', () => { cy.visit('/health'); });

9. Using Cypress.require for a local utility file

cy.origin(url, () => {
  const { formatEmail } = Cypress.require('../support/utils');
  cy.get('#email').type(formatEmail('ALICE'));
});

10. Typing a password without logging it

cy.origin(idpUrl, { args: { password } }, ({ password }) => {
  cy.get('#password').type(password, { log: false });
});

Visual

The Origin Boundary and Serialization Bridge

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  PRIMARY ORIGIN                    SECONDARY ORIGIN โ”‚
โ”‚  app.example.com                   auth.example.com โ”‚
โ”‚                                                     โ”‚
โ”‚  Test code                         Callback code    โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”‚
โ”‚  โ”‚ const user = 'alice'โ”‚          โ”‚               โ”‚โ”‚
โ”‚  โ”‚                     โ”‚          โ”‚  cy.get()     โ”‚โ”‚
โ”‚  โ”‚ cy.origin(          โ”‚  args    โ”‚  works here   โ”‚โ”‚
โ”‚  โ”‚   url,              โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บโ”‚               โ”‚โ”‚
โ”‚  โ”‚   { args: { user } },โ”‚  clone  โ”‚  But 'user'   โ”‚โ”‚
โ”‚  โ”‚   callback          โ”‚          โ”‚  must come    โ”‚โ”‚
โ”‚  โ”‚ )                   โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚  from args    โ”‚โ”‚
โ”‚  โ”‚                     โ”‚  yield   โ”‚               โ”‚โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ”‚
โ”‚                                                     โ”‚
โ”‚  โš ๏ธ Variables outside callback are NOT visible     โ”‚
โ”‚  โš ๏ธ Functions and DOM elements do NOT clone         โ”‚
โ”‚  โœ… Strings, numbers, objects, arrays DO clone      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Redirect Trap

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WHY cy.origin() SOMETIMES THROWS                   โ”‚
โ”‚                                                     โ”‚
โ”‚  โŒ WRONG: cy.visit() redirects to IdP first        โ”‚
โ”‚                                                     โ”‚
โ”‚  cy.visit('/login') โ”€โ”€โ–บ app.example.com            โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ  server 302                               โ”‚
โ”‚  browser lands on auth.example.com                  โ”‚
โ”‚         โ”‚                                           โ”‚
โ”‚         โ–ผ                                           โ”‚
โ”‚  cy.origin('https://auth.example.com', () => {...}) โ”‚
โ”‚  โ”€โ”€โ–บ ERROR: already on that origin                  โ”‚
โ”‚                                                     โ”‚
โ”‚  โœ… RIGHT: wrap the visit inside cy.origin()        โ”‚
โ”‚                                                     โ”‚
โ”‚  cy.origin('https://auth.example.com', () => {      โ”‚
โ”‚    cy.visit('https://app.example.com/oauth');       โ”‚
โ”‚    // redirect happens INSIDE the origin callback   โ”‚
โ”‚    cy.get('#approve').click();                      โ”‚
โ”‚  });                                                โ”‚
โ”‚                                                     โ”‚
โ”‚  Or: trigger redirect via UI click, then call       โ”‚
โ”‚  cy.origin() after the browser has left the app.    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

SSO Login with cy.session

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  CACHED CROSS-ORIGIN AUTHENTICATION                 โ”‚
โ”‚                                                     โ”‚
โ”‚  cy.session([email, password], () => {              โ”‚
โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚    โ”‚  PRIMARY: app.example.com                   โ”‚ โ”‚
โ”‚    โ”‚  cy.visit('/login')                         โ”‚ โ”‚
โ”‚    โ”‚  click SSO button                           โ”‚ โ”‚
โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚                      โ”‚                              โ”‚
โ”‚                      โ–ผ                              โ”‚
โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚    โ”‚  SECONDARY: auth.example.com                โ”‚ โ”‚
โ”‚    โ”‚  cy.origin(idpUrl, { args }, callback)      โ”‚ โ”‚
โ”‚    โ”‚  fill form, submit                          โ”‚ โ”‚
โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚                      โ”‚                              โ”‚
โ”‚                      โ–ผ                              โ”‚
โ”‚    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚    โ”‚  PRIMARY: app.example.com                   โ”‚ โ”‚
โ”‚    โ”‚  cy.url().should('include', '/dashboard')   โ”‚ โ”‚
โ”‚    โ”‚  โ—„โ”€โ”€ session cached here                    โ”‚ โ”‚
โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚  });                                                โ”‚
โ”‚                                                     โ”‚
โ”‚  Second test: cy.session restores cookies,          โ”‚
โ”‚  setup never runs again.                            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Commandcy.origin(origin, options?, callback)
Origin comparisonScheme + host + port; path ignored
Required sinceCypress 14 (document.domain removed)
Data passingargs with structured clone algorithm
Functions/DOMNot cloneable; load classes with Cypress.require()
Nested originsNot allowed; use sequential top-level calls
Redirect handlingWrap initial visit inside cy.origin()
Session cachingCombine with cy.session() for SSO
Dependency loadingCypress.require() with experimentalOriginDependencies
Same-origin callThrows error

Key takeaways:

  • cy.origin() is mandatory for cross-origin navigation since Cypress 14. The document.domain workaround is gone. Any visit to a different scheme, host, or port requires the command, including subdomains of the same parent domain .
  • The callback runs in an isolated context. Variables from the test scope are invisible inside it. Every value the callback needs must be passed through args, and the structured clone algorithm determines what survives the trip .
  • Page object instances lose their methods. The structured clone algorithm copies properties but not prototype methods. Load the class inside the callback with Cypress.require() and instantiate it there, or pass the selectors the callback needs as plain data .
  • The redirect trap requires wrapping the initial visit. When cy.visit() redirects to the IdP before cy.origin() is called, the browser is already on the target origin and the command throws. Wrap the visit inside cy.origin(), or trigger the redirect through a UI action that the test can intercept .
  • cy.session() and cy.origin() are designed together. An SSO login command combines the two: the session caches the result, and the origin callback performs the cross-domain interaction. Every test after the first restores the cached session without repeating the IdP flow.
  • Cypress.require() is the only way to load dependencies inside the callback. Standard require() and import() do not work because the callback is extracted from the test bundle. Enable experimentalOriginDependencies and use static string arguments .
  • Nested cy.origin() calls are not allowed. When a test visits multiple secondary origins, each call must be at the top level of the test, executed sequentially, not nested inside another origin callback .

Remember: Cross-origin testing in Cypress is a serialization problem disguised as a navigation problem. The browser enforces the boundary, cy.origin() crosses it, and args is the only bridge for data. The callback is not a closureโ€”it is a separate program running in a separate context with only the arguments it was given. Pass what it needs, load what it requires, and never assume it can see the test scope. The SSO pattern combines this bridge with cy.session(): the first test crosses the boundary and caches the result, and every later test restores the session without crossing it again. That is the shape of a reliable multi-domain suite.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!