# How Cypress Manages Cookies and localStorage Across Test Isolation

> Learn how Cypress manages cookies and localStorage with automatic clearing and custom rules for effective test isolation. Ensure a clean slate for every test.

- Repository: [Cypress.io/cypress](https://github.com/cypress-io/cypress)
- Tags: internals
- Published: 2026-07-12

---

**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`](https://github.com/cypress-io/cypress/blob/main/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`](https://github.com/cypress-io/cypress/blob/main/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`](https://github.com/cypress-io/cypress/blob/main/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`](https://github.com/cypress-io/cypress/blob/main/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`](https://github.com/cypress-io/cypress/blob/main/packages/driver/src/cy/commands/sessions/manager.ts) runs a cleanup routine. This manager contains dedicated branches for `clearCookies`, `clearLocalStorage`, and `clearSessionStorage` that:

1. Emit `Cypress.emit('clear:cookies')` to purge the server-side cookie jar
2. Call `window.localStorage.clear()` and `window.sessionStorage.clear()` for the current origin
3. 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:

```javascript
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:**

```javascript
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:**

```javascript
cy.clearCookies()
cy.clearLocalStorage()
cy.clearSessionStorage()

```

**Using `cy.session()` for isolated authentication contexts:**

```javascript
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`](https://github.com/cypress-io/cypress/blob/main/packages/driver/src/cy/commands/cookies.ts), sending requests to [`packages/server/lib/automation/cookie/automation.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/automation/cookie/automation.ts) for protocol-level execution
- **Native storage APIs** manage localStorage and sessionStorage through [`packages/driver/src/cy/commands/storage.ts`](https://github.com/cypress-io/cypress/blob/main/packages/driver/src/cy/commands/storage.ts), with cross-origin coordination handled in [`packages/driver/src/cypress/local_storage.ts`](https://github.com/cypress-io/cypress/blob/main/packages/driver/src/cypress/local_storage.ts)
- **Session manager** enforces isolation by running `clearCookies`, `clearLocalStorage`, and `clearSessionStorage` routines from [`packages/driver/src/cy/commands/sessions/manager.ts`](https://github.com/cypress-io/cypress/blob/main/packages/driver/src/cy/commands/sessions/manager.ts) before each test
- **Preservation rules** allow selective state retention via `Cypress.Cookies.defaults()` and `Cypress.LocalStorage.defaults()` configurations
- **Cross-origin support** uses `postMessage` with 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`](https://github.com/cypress-io/cypress/blob/main/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.