Cypress 17 ๐ฒ Authentication โ cy.session and login state caching
Logging in before every test is the single largest source of wasted time in an end-to-end suite. A login flow that takes three seconds, repeated across two hundred tests, adds ten minutes to every CI runโand most of those tests do not care about the login itself, only about the state it produces. cy.session() solves this by caching the browser’s cookies and storage after a successful login, then restoring that state instantly on subsequent calls instead of repeating the form submission.
This chapter covers cy.session() in depth: how the setup function creates a session, how the id determines what gets cached, how the validate option checks whether a restored session is still usable, and how test isolation interacts with session clearing. It also covers caching sessions across spec files with cacheAcrossSpecs, switching between multiple users in a single test, handling cross-domain authentication through cy.origin(), and debugging sessions that fail to restore. By the end, you will be able to replace repeated login flows with a single cached session that every test in the suite shares.
Key point: cy.session(id, setup) runs setup only when no cached session exists for id. On subsequent calls, it restores the cached cookies and storage instead. The id must uniquely identify the user or role, and setup must assert that login succeeded before it returnsโotherwise Cypress caches an empty or partial session.
Why cy.session exists
The repeated-login cost. A test that verifies a checkout flow needs an authenticated user, but the login is incidental to the checkout. Without caching, every test that needs authentication repeats the same form fill, submit, and redirect wait. cy.session() separates authentication from the test’s actual subject: the first call performs the login, and every later call restores the result in milliseconds. The test suite runs faster, and the login flow itself is tested once, in its own dedicated test, rather than hundreds of times as a side effect.
The test isolation guarantee. Cypress clears cookies and storage before every test when testIsolation is enabled. This is correct for isolationโone test cannot leak state into anotherโbut it means a session created in a before() hook is wiped before the first test runs. cy.session() is designed to work with this clearing: it creates the session once, caches it on Cypress’s backend, and restores it at the start of each test that calls it. The clearing and the restoration are two halves of the same mechanism.
The identity problem. A suite that tests an admin user and a regular user needs two distinct sessions. A suite that tests three different accounts needs three. cy.session() accepts an id that serves as the cache key: calls with the same id share a session, and calls with different ids maintain separate sessions. The id is the mechanism that lets a single test switch between users without logging out and back in.
a. Creating and restoring a session
The cy.session() command accepts an id, a setup function, and an optional options object. The setup function contains the login steps. It runs only when no cached session exists for the given id. After setup completes, Cypress captures all cookies, localStorage, and sessionStorage across every origin visited during setup and stores them under that id .
// cypress/support/commands.ts
Cypress.Commands.add('login', (username: string, password: string) => {
// The id is an array so Cypress caches a separate session per user
cy.session([username, password], () => {
// setup runs only on the first call for this id
cy.visit('/login');
cy.get('[data-test="username"]').type(username);
cy.get('[data-test="password"]').type(password, { log: false });
cy.get('form').submit();
// Assert the redirect so setup does not return before the session exists
cy.url().should('include', '/dashboard'); // โ
guarantees cacheable state
});
});
// cypress/e2e/orders.cy.ts
describe('Orders', () => {
beforeEach(() => {
// First test: setup runs. Every later test: cached session restored.
cy.login('alice@example.com', 'secret123');
cy.visit('/orders'); // required after cy.session when isolation is on
});
it('lists past orders', () => {
cy.get('[data-test="order-row"]').should('have.length.at.least', 1);
});
it('opens order details', () => {
cy.get('[data-test="order-row"]').first().click();
cy.url().should('include', '/orders/');
});
});
The assertion at the end of setup is not optional decoration. Cypress caches the session immediately when setup returns, so if setup returns before the login has actually completedโwhile the redirect is still pending, before the cookie is setโCypress caches an unauthenticated state. The cy.url().should('include', '/dashboard') blocks until the redirect finishes, guaranteeing that the cookies exist when the cache snapshot is taken .
The cy.visit() after cy.session() is also required. When test isolation is enabled, cy.session() clears the page before and after it runs. The session is restored, but no page is loaded. The test must navigate explicitly to the page it wants to test .
b. Validating and switching sessions
The validate option checks whether a restored session is still usable. Without it, cy.session() trusts the cached state completely: if the cookie expired server-side or the token was revoked, the test proceeds with a dead session and fails later with a confusing 401. With validate, Cypress runs the check after restoring and re-runs setup if the check fails .
Cypress.Commands.add('login', (username: string) => {
cy.session(
username, // id: one session per user
() => {
// setup: runs only when no valid cached session exists
cy.request({
method: 'POST',
url: '/api/login',
body: { username, password: 'test-password' },
}).then(({ body }) => {
window.localStorage.setItem('authToken', body.token);
});
},
{
validate() {
// Runs after restore; re-runs setup if this assertion fails
cy.request({
url: '/api/whoami',
headers: { Authorization: localStorage.getItem('authToken') },
}).its('status').should('eq', 200); // โ
verifies session is live
},
}
);
});
Switching users in a single test works because each user has a different id. Cypress clears the previous session’s data before restoring the new one, so no logout step is needed .
it('switches from admin to viewer', () => {
cy.login('admin@example.com'); // creates or restores admin session
cy.visit('/admin');
cy.get('[data-test="delete-all"]').should('be.visible');
cy.login('viewer@example.com'); // replaces session with viewer's
cy.visit('/admin');
cy.get('[data-test="delete-all"]').should('not.exist');
});
The id is displayed in the Command Log and the reporter, which is why it should never contain a password or token. An array of non-sensitive valuesโ[username, role]โis the recommended shape: it uniquely identifies the session without exposing credentials .
c. Caching across specs and working with cross-domain auth
By default, a session lives only for the duration of the spec file that created it. A second spec file calling cy.session() with the same id runs setup again. The cacheAcrossSpecs: true option extends the session’s lifetime to the entire cypress run, so every spec in the run shares it .
// cypress/support/login.ts โ shared helper imported by every spec
export const login = (username = 'alice@example.com') => {
cy.session(
username,
() => {
cy.request('POST', '/api/login', { username, password: 'test-pass' })
.then(({ body }) => window.localStorage.setItem('token', body.token));
},
{
cacheAcrossSpecs: true, // โ
persists across spec files
validate() {
cy.request('/api/whoami').its('status').should('eq', 200);
},
}
);
};
The cross-spec cache lives in memory for a single Cypress run on a single machine. It is not written to disk and is not shared between machines, so parallel CI runs still execute setup at least once per machine .
For authentication through an identity provider on another domain, cy.origin() goes inside setup, not inside cy.session(). cy.session() cannot be called inside a cy.origin() callback, but it caches cookies and storage for every origin visited during setupโincluding the provider’s domain and the application’s domain .
Cypress.Commands.add('loginWithSSO', () => {
cy.session('sso-user', () => {
cy.visit('https://app.example.com/login');
cy.contains('button', 'Sign in with SSO').click();
// The provider interaction runs inside cy.origin
cy.origin('https://auth.example.com', () => {
cy.get('#username').type('user@example.com');
cy.get('#password').type('secret', { log: false });
cy.get('button[type="submit"]').click();
});
// Back on the app domain; assert the redirect completed
cy.url().should('include', '/dashboard');
});
});
Complete Example Session
// ============================================
// PART 1: CUSTOM COMMAND WITH SESSION CACHING
// ============================================
// cypress/support/commands.ts
Cypress.Commands.add('login', (username: string) => {
cy.session(
username,
() => {
// ============================================
// PART 2: SETUP FUNCTION
// ============================================
cy.visit('/login');
cy.get('[data-test="username"]').type(username);
cy.get('[data-test="password"]').type('test-password', { log: false });
cy.get('form').submit();
// ============================================
// PART 3: GUARDING ASSERTION
// ============================================
// Blocks until the redirect finishes, guaranteeing cookies exist
cy.url().should('include', '/dashboard');
},
{
// ============================================
// PART 4: VALIDATE FUNCTION
// ============================================
validate() {
cy.request('/api/whoami').its('status').should('eq', 200);
},
// ============================================
// PART 5: CROSS-SPEC CACHING
// ============================================
cacheAcrossSpecs: true,
}
);
});
// ============================================
// PART 6: FIRST TEST CREATES THE SESSION
// ============================================
describe('Orders', () => {
beforeEach(() => {
cy.login('alice@example.com'); // setup runs here, once
cy.visit('/orders'); // required after cy.session
});
it('shows the order list', () => {
cy.get('[data-test="order-row"]').should('have.length.at.least', 1);
});
// ============================================
// PART 7: SECOND TEST RESTORES THE SESSION
// ============================================
it('opens a single order', () => {
// cy.session restored the cached cookies; setup did not run
cy.get('[data-test="order-row"]').first().click();
cy.url().should('include', '/orders/');
});
// ============================================
// PART 8: SWITCHING USERS IN ONE TEST
// ============================================
it('admin sees the delete button, viewer does not', () => {
cy.login('admin@example.com'); // new id: creates admin session
cy.visit('/orders');
cy.get('[data-test="delete-order"]').should('be.visible');
cy.login('viewer@example.com'); // new id: replaces with viewer session
cy.visit('/orders');
cy.get('[data-test="delete-order"]').should('not.exist');
});
// ============================================
// PART 9: SSO LOGIN WITH cy.origin
// ============================================
it('logs in through the identity provider', () => {
cy.session('sso-user', () => {
cy.visit('/login');
cy.contains('button', 'Sign in with SSO').click();
cy.origin('https://auth.example.com', () => {
cy.get('#username').type('sso@example.com');
cy.get('#password').type('secret', { log: false });
cy.get('button[type="submit"]').click();
});
cy.url().should('include', '/dashboard');
});
cy.visit('/profile');
});
// ============================================
// PART 10: DEBUGGING A CACHED SESSION
// ============================================
it('inspects cached session data', () => {
cy.session('debug-user', () => {
cy.visit('/login');
cy.get('[data-test="username"]').type('debug@example.com');
cy.get('[data-test="password"]').type('pass', { log: false });
cy.get('form').submit();
cy.url().should('include', '/dashboard');
});
// Retrieve what was actually cached for this id
cy.then(async () => {
const sessionData = await Cypress.session.getSession('debug-user');
// Inspect cookies and localStorage keys to verify setup captured everything
cy.log(JSON.stringify(sessionData));
});
});
});
The ten parts above cover the complete lifecycle: defining a session-caching login command, writing setup with a guarding assertion, adding validate for session health checks, enabling cross-spec caching, creating and restoring sessions across tests, switching between two users in one test, handling SSO through cy.origin(), and inspecting the cached data when something looks wrong.
Quick Reference
cy.session Arguments
| Argument | Type | Purpose |
|---|---|---|
id | String, Array, Object | Unique cache key; shown in Command Log |
setup | Function | Login steps; runs only when no valid cache exists |
options.validate | Function | Health check after restore; re-runs setup on failure |
options.cacheAcrossSpecs | Boolean | Persist session for the entire cypress run |
Session Clearing Behavior
| Setting | Page Cleared | Session Data Cleared |
|---|---|---|
testIsolation: true (default) | Yes, before and after | Yes, before and after |
testIsolation: false | No | Yes, before and after |
Cypress.session Helpers
| Method | Purpose |
|---|---|
clearAllSavedSessions() | Remove every cached session |
getSession(id) | Inspect cached data for debugging |
getCurrentSessionData() | Inspect active browser storage |
clearCurrentSessionData() | Clear active browser storage |
Where to Call cy.visit()
| Test Isolation | After cy.session() |
|---|---|
| Enabled | cy.visit() required |
| Disabled | cy.visit() optional; page persists |
Best Practices
โ Do This:
// Assert the redirect inside setup to guarantee cacheable state
cy.url().should('include', '/dashboard'); // โ
// Build the id from non-sensitive values that distinguish sessions
cy.session([username, role], () => { /* ... */ }); // โ
// Add a validate function to catch expired sessions
validate() {
cy.request('/api/whoami').its('status').should('eq', 200); // โ
}
// Call cy.visit() after cy.session() when isolation is enabled
cy.login('user');
cy.visit('/orders'); // โ
// Use cacheAcrossSpecs for shared login in multi-spec runs
cy.session(id, setup, { cacheAcrossSpecs: true }); // โ
// Put cy.origin() inside setup for SSO flows
cy.session(id, () => {
cy.origin(providerUrl, () => { /* ... */ }); // โ
});
โ Don’t Do This:
// Don't skip the guarding assertion; setup may cache an empty session
cy.session('user', () => {
cy.get('form').submit(); // โ returns before redirect completes
});
// Don't put a password in the id; it appears in the Command Log
cy.session(password, () => { /* ... */ }); // โ sensitive data in reporter
// Don't call cy.session() inside cy.origin()
cy.origin(url, () => {
cy.session('user', () => { /* ... */ }); // โ not allowed
});
// Don't rely on the page after cy.session() without visiting
cy.session('user', setup);
cy.get('[data-test="orders"]'); // โ page was cleared
// Don't use before() for cy.session with isolation on
before(() => {
cy.session('user', setup); // โ session cleared before first test
});
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Session not restored in second test | Called cy.session() in before() | Move to beforeEach() |
| Cached session is unauthenticated | setup returned before login completed | Add cy.url().should() guarding assertion |
Page is blank after cy.session() | Test isolation cleared the page | Call cy.visit() after the session |
| Session recreated every test | id changes between calls | Use a stable, non-sensitive id |
| Expired session used silently | No validate function | Add validate with a status assertion |
| SSO login fails | cy.session() called inside cy.origin() | Put cy.origin() inside setup |
| Cross-spec session not shared | cacheAcrossSpecs not set | Add { cacheAcrossSpecs: true } |
Real-World Examples
1. Caching a login custom command
Cypress.Commands.add('login', (email: string) => {
cy.session(email, () => {
cy.request('POST', '/api/login', { email, password: 'pass' });
cy.visit('/dashboard');
});
});
2. Adding a validate check
cy.session('user', setup, {
validate() {
cy.request('/api/me').its('status').should('eq', 200);
},
});
3. Switching users in a single test
cy.login('admin@example.com');
cy.visit('/admin');
cy.login('viewer@example.com');
cy.visit('/admin');
4. Caching across spec files
cy.session('shared-user', setup, { cacheAcrossSpecs: true });
5. Inspecting a cached session for debugging
cy.then(async () => {
const data = await Cypress.session.getSession('user-id');
cy.log(JSON.stringify(data));
});
6. Clearing all saved sessions
Cypress.session.clearAllSavedSessions();
7. SSO login with cy.origin inside setup
cy.session('sso', () => {
cy.visit('/login');
cy.contains('Sign in with SSO').click();
cy.origin('https://auth.example.com', () => {
cy.get('#username').type('user');
cy.get('#submit').click();
});
});
8. Login via API without visiting the login page
cy.session('api-user', () => {
cy.request('POST', '/api/login', { user: 'alice', pass: 'secret' })
.then(({ body }) => localStorage.setItem('token', body.token));
});
9. Conditional caching for login-flow tests
const login = (user: string, cache = true) => {
const doLogin = () => { cy.visit('/login'); /* ... */ };
cache ? cy.session(user, doLogin) : doLogin();
};
10. Using getCurrentSessionData to verify storage
cy.session('user', setup).then(async () => {
const data = await Cypress.session.getCurrentSessionData();
expect(data.cookies.length).to.be.greaterThan(0);
});
Visual
The cy.session Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FIRST CALL vs SUBSEQUENT CALLS โ
โ โ
โ cy.session('user', setup) โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Is there a valid cached session for 'user'?โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโดโโโโโ โ
โ โ โ โ
โ NO YES โ
โ โ โ โ
โ โผ โผ โ
โ โโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ setupโ โ Restore cookies + storage โ โ
โ โ runs โ โ Run validate() if provided โ โ
โ โโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ โ
โ โผ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Cache cookies, localStorage, sessionStorageโ โ
โ โ across all origins visited during setup โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ cy.session() ends; page is cleared (isolation on) โ
โ Test calls cy.visit() to load the page under test โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Session ID as Cache Key
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ONE ID, ONE SESSION โ
โ โ
โ cy.session('alice', setupA) โโโบ Session A cached โ
โ cy.session('alice', setupA) โโโบ Session A restored โ
โ โ
โ cy.session('bob', setupB) โโโบ Session B cached โ
โ cy.session('bob', setupB) โโโบ Session B restored โ
โ โ
โ Switching users: โ
โ cy.session('alice') โโโบ clears Bob's data โ
โ restores Alice's data โ
โ (No logout step needed) โ
โ โ
โ โ ๏ธ Same id + different setup = test failure โ
โ cy.session('user', setupA) โ
โ cy.session('user', setupB) โโโบ Error: session โ
โ already exists โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Test Isolation and Page Clearing
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHAT testIsolation CONTROLS โ
โ โ
โ testIsolation: true (default) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Before test: cookies + storage cleared โ โ
โ โ cy.session(): page cleared, session restoredโ โ
โ โ After cy.session(): page cleared โ โ
โ โ Test must call cy.visit() โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ testIsolation: false โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Before test: nothing cleared โ โ
โ โ cy.session(): storage cleared, page stays โ โ
โ โ After cy.session(): page stays โ โ
โ โ cy.visit() optional โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ When isolation is off, set up session in before() โ
โ and visit the shared page once. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Command | cy.session(id, setup, options?) |
| Caching scope | Spec file by default; entire run with cacheAcrossSpecs |
| Required after call | cy.visit() when testIsolation: true |
| Guarding assertion | cy.url().should() at end of setup |
| Validate option | Health check; re-runs setup on failure |
| Session switching | Different id replaces previous session |
| SSO handling | cy.origin() inside setup |
| Debug helper | Cypress.session.getSession(id) |
| Clear all | Cypress.session.clearAllSavedSessions() |
| ID recommendation | Array of non-sensitive values |
Key takeaways:
setupruns once perid, not once per test. The firstcy.session()call with a givenidexecutes the login; every subsequent call restores the cached state. This is the entire performance benefit: one login instead of hundreds.- The guarding assertion is mandatory. Cypress caches the session the moment
setupreturns. Ifsetupreturns before the redirect completes, the cache contains an unauthenticated state. Endsetupwith an assertion that proves login finished. cy.visit()is required aftercy.session()when isolation is enabled. The session command clears the page before and after it runs. The cookies are restored, but no page is loaded. The test must navigate to its subject explicitly.- The
idis both cache key and log entry. It must uniquely identify the session, and it must not contain passwords or tokens because it appears in the Command Log and reporter. Use an array of stable, non-sensitive values. validatecatches dead sessions. A restored cookie may have expired server-side. Thevalidatefunction checks the session’s health after restore and re-runssetupif the check fails, preventing confusing downstream failures.- Switching users requires no logout. Calling
cy.session()with a differentidclears the previous session’s data and restores the new one. A single test can act as an admin, then a viewer, without an intervening logout. cacheAcrossSpecsextends the session to the entire run. Without it, every spec file runssetupagain. With it, the first spec creates the session and every later spec in the samecypress runrestores it.
Remember: cy.session() treats authentication as a cached dependency rather than a repeated step. The setup function defines how to log in, the id defines who is logged in, and the cache stores the browser state that proves it. The test suite pays the login cost once, then restores it for every test that needs it. The two rules that make it work are the guarding assertionโwithout it, the cache stores an empty sessionโand the explicit cy.visit()โwithout it, the restored session has no page to act on. Follow both, and the login flow becomes a one-time setup that the rest of the suite inherits.
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!