| | |

Cypress 17 ๐ŸŒฒ Authentication โ€” cy.session and login state caching

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

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

ArgumentTypePurpose
idString, Array, ObjectUnique cache key; shown in Command Log
setupFunctionLogin steps; runs only when no valid cache exists
options.validateFunctionHealth check after restore; re-runs setup on failure
options.cacheAcrossSpecsBooleanPersist session for the entire cypress run

Session Clearing Behavior

SettingPage ClearedSession Data Cleared
testIsolation: true (default)Yes, before and afterYes, before and after
testIsolation: falseNoYes, before and after

Cypress.session Helpers

MethodPurpose
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 IsolationAfter cy.session()
Enabledcy.visit() required
Disabledcy.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

PitfallWhy It HappensFix
Session not restored in second testCalled cy.session() in before()Move to beforeEach()
Cached session is unauthenticatedsetup returned before login completedAdd cy.url().should() guarding assertion
Page is blank after cy.session()Test isolation cleared the pageCall cy.visit() after the session
Session recreated every testid changes between callsUse a stable, non-sensitive id
Expired session used silentlyNo validate functionAdd validate with a status assertion
SSO login failscy.session() called inside cy.origin()Put cy.origin() inside setup
Cross-spec session not sharedcacheAcrossSpecs not setAdd { 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

ItemValue
Commandcy.session(id, setup, options?)
Caching scopeSpec file by default; entire run with cacheAcrossSpecs
Required after callcy.visit() when testIsolation: true
Guarding assertioncy.url().should() at end of setup
Validate optionHealth check; re-runs setup on failure
Session switchingDifferent id replaces previous session
SSO handlingcy.origin() inside setup
Debug helperCypress.session.getSession(id)
Clear allCypress.session.clearAllSavedSessions()
ID recommendationArray of non-sensitive values

Key takeaways:

  • setup runs once per id, not once per test. The first cy.session() call with a given id executes 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 setup returns. If setup returns before the redirect completes, the cache contains an unauthenticated state. End setup with an assertion that proves login finished.
  • cy.visit() is required after cy.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 id is 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.
  • validate catches dead sessions. A restored cookie may have expired server-side. The validate function checks the session’s health after restore and re-runs setup if the check fails, preventing confusing downstream failures.
  • Switching users requires no logout. Calling cy.session() with a different id clears 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.
  • cacheAcrossSpecs extends the session to the entire run. Without it, every spec file runs setup again. With it, the first spec creates the session and every later spec in the same cypress run restores 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.

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!