How Cypress Manages Cookies and localStorage Across Test Isolation
Cypress automatically clears cookies, localStorage, and sessionStorage before each test by emitting automation events to the server and invoking native browser APIs, unless users explicitly configure preservation rules.
Test isolation is a fundamental guarantee of the Cypress testing framework that prevents state leakage between tests. In the cypress-io/cypress repository, the driver implements this through a coordinated architecture spanning automation events, server-side protocols, and direct browser API access. Understanding how Cypress manages cookies and localStorage across test isolation helps you debug authentication flows and optimize test suite performance.
The Automation Architecture Behind Cookie Management
Cypress handles cookies through thin wrapper commands that dispatch automation events rather than manipulating the browser directly. In packages/driver/src/cy/commands/cookies.ts, commands like cy.getCookie, cy.setCookie, and cy.clearCookies build automation requests using Cypress.automation(event, options).
These events travel to packages/server/lib/automation/cookie/automation.ts, where the server receives the automation event and forwards the request to the underlying browser protocol—whether CDP (Chrome DevTools Protocol), Bidi, or WebKit. After executing a same-origin request, the driver synchronizes its internal cookie jar with the browser state (logged via debugCookies('clear:cookies …')) to ensure subsequent commands access up-to-date data.
Handling localStorage and sessionStorage Across Origins
Storage management commands reside in packages/driver/src/cy/commands/storage.ts, which implements cy.clearLocalStorage, cy.clearSessionStorage, and cy.getAllLocalStorage. The driver maintains references to the current page’s window.localStorage and window.sessionStorage in packages/driver/src/cypress/local_storage.ts.
For cross-origin scenarios involving remote iframes, the driver coordinates storage access through postMessage mechanisms with postMessageStorageTimeoutMs handling. When clearing storage, Cypress invokes native window.localStorage.clear() and window.sessionStorage.clear() methods for the current origin, ensuring no residual data persists between tests.
The Session Manager: Enforcing Test-Level Isolation
Before every test executes, the session manager defined in packages/driver/src/cy/commands/sessions/manager.ts runs a cleanup routine. This manager contains dedicated branches for clearCookies, clearLocalStorage, and clearSessionStorage that:
- Emit
Cypress.emit('clear:cookies')to purge the server-side cookie jar - Call
window.localStorage.clear()andwindow.sessionStorage.clear()for the current origin - Clear storage for additional origins recorded during the test run
This architecture guarantees that each test starts with an empty cookie jar and cleared storage, providing deterministic isolation unless specific preservation rules are configured.
Preserving State Between Tests
You can override the default clearing behavior to maintain specific authentication tokens or user preferences across tests. Configure preservation rules using:
Cypress.Cookies.defaults({
preserve: ['session_id', 'auth_token']
})
Cypress.LocalStorage.defaults({
preserve: ['userPrefs', 'authToken']
})
The session manager consults these defaults before issuing clear commands, allowing selective state retention while maintaining isolation for all other data.
Practical Implementation Examples
Verify automatic clearing before a test:
it('starts with clean state', () => {
// Cypress automatically cleared cookies & localStorage here
cy.getCookies().should('be.empty')
cy.window().then((win) => {
expect(win.localStorage.length).to.eq(0)
})
})
Explicitly clear storage during a test:
cy.clearCookies()
cy.clearLocalStorage()
cy.clearSessionStorage()
Using cy.session() for isolated authentication contexts:
cy.session('admin', () => {
cy.loginAsAdmin() // sets auth cookie & localStorage
})
// The next cy.session call receives a fresh browser context
cy.session('guest', () => {
// No auth cookie or localStorage from the previous session
})
Summary
- Automation events handle cookie operations via
packages/driver/src/cy/commands/cookies.ts, sending requests topackages/server/lib/automation/cookie/automation.tsfor protocol-level execution - Native storage APIs manage localStorage and sessionStorage through
packages/driver/src/cy/commands/storage.ts, with cross-origin coordination handled inpackages/driver/src/cypress/local_storage.ts - Session manager enforces isolation by running
clearCookies,clearLocalStorage, andclearSessionStorageroutines frompackages/driver/src/cy/commands/sessions/manager.tsbefore each test - Preservation rules allow selective state retention via
Cypress.Cookies.defaults()andCypress.LocalStorage.defaults()configurations - Cross-origin support uses
postMessagewith timeout handling to access storage in remote iframes
Frequently Asked Questions
Does Cypress automatically clear cookies between tests?
Yes. According to the cypress-io/cypress source code, the session manager automatically emits clear:cookies events and invokes storage clearing methods before each test unless you configure specific cookies or keys to preserve using Cypress.Cookies.defaults() or Cypress.LocalStorage.defaults().
How does Cypress handle localStorage in cross-origin iframes?
Cypress accesses cross-origin storage by posting messages to remote iframes and awaiting replies, as implemented in packages/driver/src/cypress/local_storage.ts. The system uses postMessageStorageTimeoutMs to handle timeouts during these cross-origin storage retrieval operations.
What is the difference between cy.clearCookies() and the session manager's automatic clearing?
cy.clearCookies() is an explicit command you can call within a test that dispatches an automation event to clear cookies immediately. The session manager's automatic clearing runs before each test starts, ensuring a clean state without requiring explicit commands in your test code.
Can I preserve authentication state across multiple tests?
Yes. You can preserve specific cookies and localStorage entries by configuring defaults before your tests run. Use Cypress.Cookies.defaults({ preserve: ['auth_token'] }) for HTTP cookies and Cypress.LocalStorage.defaults({ preserve: ['user'] }) for Web Storage data to maintain authentication state across test isolation boundaries.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →