Cypress 20 ๐ฒ Cross-Origin Testing โ cy.origin and multi-domain flows
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 Difference | Requires cy.origin()? | Reason |
|---|---|---|
| Path only | No | Same origin |
| Port differs | Yes | Different origin |
| Subdomain differs | Yes | Different host |
| Scheme differs | Yes | Different origin |
| Same origin passed | Error | Redundant |
cy.origin Options
| Option | Type | Purpose |
|---|---|---|
origin | String | Target origin URL |
args | Object | Data serialized into callback |
callback | Function | Code executed in secondary origin |
Serialization Rules
| Type | Copies Across | Example |
|---|---|---|
| String, number, boolean | Yes | 'hello', 42, true |
| Array, plain object | Yes | { user: 'alice' } |
| Date, Map, Set | Yes | new Date() |
| Function | No | () => {} |
| DOM element | No | element |
| Class instance methods | No | Instance arrives without methods |
Cypress.require Support
| Feature | Supported | Notes |
|---|---|---|
| npm packages | Yes | Cypress.require('lodash') |
| Local files | Yes | Cypress.require('./utils') |
| File extensions | .js, .ts, .jsx, .tsx, .mjs, .json | Others rejected |
| Dynamic strings | No | Must be static literal |
| Outside callback | No | Errors 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
ReferenceError inside callback | Variable not passed through args | Pass all values explicitly |
cy.origin() requires different origin | Already on target origin after redirect | Wrap initial visit in cy.origin() |
Nested cy.origin() error | Called inside another origin callback | Move to top level of test |
| Page object methods missing | Instance serialized, methods lost | Use Cypress.require() to load class |
Cypress.require undefined | experimentalOriginDependencies not enabled | Enable in config |
| Custom commands unavailable in IdP | Not loaded into secondary origin | Load 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
| Item | Value |
|---|---|
| Command | cy.origin(origin, options?, callback) |
| Origin comparison | Scheme + host + port; path ignored |
| Required since | Cypress 14 (document.domain removed) |
| Data passing | args with structured clone algorithm |
| Functions/DOM | Not cloneable; load classes with Cypress.require() |
| Nested origins | Not allowed; use sequential top-level calls |
| Redirect handling | Wrap initial visit inside cy.origin() |
| Session caching | Combine with cy.session() for SSO |
| Dependency loading | Cypress.require() with experimentalOriginDependencies |
| Same-origin call | Throws error |
Key takeaways:
cy.origin()is mandatory for cross-origin navigation since Cypress 14. Thedocument.domainworkaround 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 beforecy.origin()is called, the browser is already on the target origin and the command throws. Wrap the visit insidecy.origin(), or trigger the redirect through a UI action that the test can intercept . cy.session()andcy.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. Standardrequire()andimport()do not work because the callback is extracted from the test bundle. EnableexperimentalOriginDependenciesand 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.
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!