# How Cypress Implements Sessions and Authentication State Management

> Learn how Cypress manages authentication state and sessions. Discover its in-memory cache, WebSocket persistence, and secure handling of cookies, localStorage, and IndexedDB.

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

---

**Cypress stores authentication data in an in-memory session cache on the server, using WebSocket messages to persist and restore cookies, localStorage, and IndexedDB between tests.**

Cypress manages authentication state through a lightweight in-process session cache that lives entirely within the Cypress server process. This architecture enables fast, isolated session storage that persists across specs without relying on external databases or filesystem operations. Understanding how Cypress implements sessions and authentication state management reveals why the `cy.session()` command can restore login states instantly while maintaining strict isolation between test runs.

## In-Memory Session Cache Architecture

The core session storage implementation resides in [`packages/server/lib/session.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/session.ts). This module maintains two distinct in-memory maps that store `Cypress.ServerSessionData` objects:

- **globalSessions**: Persists authentication state across multiple spec files when `cacheAcrossSpecs: true` is enabled
- **specSessions**: Stores temporary session data that exists only for the current spec file

```typescript
type State = {
  globalSessions: StoredSessions
  specSessions: StoredSessions
}

```

These maps are pure in-memory data structures with no filesystem or database dependencies, ensuring microsecond-level read/write performance and automatic cleanup when the Cypress process exits.

### Session Storage API

The session module exports several pure functions that manipulate this state:

**`saveSession(data)`** – Writes a `Cypress.ServerSessionData` object to the appropriate map based on the `cacheAcrossSpecs` flag.

**`getSession(id)`** – Retrieves a session by ID from either `globalSessions` or `specSessions`, throwing an error if the ID is absent.

**`getActiveSessions()`** – Returns the current set of global sessions, primarily used by the Cypress UI to display cached login states.

**`clearSessions(clearAll)`** – Empties `specSessions` unconditionally, and clears `globalSessions` only when `clearAll` is true.

## WebSocket Communication Protocol

Communication between the browser driver and the server-side cache occurs through Cypress's internal WebSocket channel defined in [`packages/server/lib/socket.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/socket.ts). The server registers specific message handlers that bridge the in-memory cache with the browser's authentication state.

### Server-Side Message Handlers

The socket layer implements three critical message types:

- **`save:session`** – Invokes `session.saveSession(data)` to persist authentication data sent from the browser
- **`get:session`** – Invokes `session.getSession(id)` to return cached session data when `cy.session()` requests restoration
- **`clear:sessions`** – Invokes `session.clearSessions(flag)` to clear per-spec sessions or all sessions, typically triggered by logout operations or cleanup commands

### Driver-Side State Collection

In [`packages/driver/src/commands/session.ts`](https://github.com/cypress-io/cypress/blob/main/packages/driver/src/commands/session.ts), the driver collects the browser's current authentication state—including cookies, `localStorage`, `sessionStorage`, and IndexedDB—and packages it into a `Cypress.ServerSessionData` object. When a test calls `cy.session()`, the driver emits the `save:session` request to transmit this data to the server. During subsequent test runs, the driver issues `get:session` requests to retrieve the cached state and reinject it into the browser, eliminating the need to repeat authentication flows.

## Practical Implementation with cy.session()

The `cy.session()` command orchestrates this entire flow. When you define a session with `cacheAcrossSpecs: true`, Cypress stores the authentication state in `globalSessions`, making it available to subsequent spec files.

```javascript
// cypress/e2e/login.cy.js
describe('Login flow', () => {
  // First run – Cypress stores the auth state
  it('logs in and caches the session', () => {
    cy.session('user-session', () => {
      cy.visit('/login')
      cy.get('#username').type('alice')
      cy.get('#password').type('s3cr3t')
      cy.get('button[type=submit]').click()
      // Cypress automatically records cookies + storage here
    }, { cacheAcrossSpecs: true })
  })

  // Subsequent tests – the stored session is restored instantly
  it('visits a protected page without re-logging in', () => {
    cy.visit('/dashboard')
    cy.contains('Welcome, Alice')
  })
})

```

To clear cached sessions programmatically, you can use the built-in cleanup commands or emit the `clear:sessions` message directly:

```javascript
// Reset the cached session after logout
cy.clearCookies()
cy.clearLocalStorage()
cy.clearAllSessions() // Emits 'clear:sessions' with clearAll=true

```

## Summary

- **Cypress session and authentication state management** relies on an in-memory cache in [`packages/server/lib/session.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/session.ts) that stores cookies, storage, and IndexedDB data.
- The cache maintains two maps: `globalSessions` for cross-spec persistence and `specSessions` for temporary storage.
- WebSocket messages (`save:session`, `get:session`, `clear:sessions`) in [`packages/server/lib/socket.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/socket.ts) synchronize state between the browser driver and server.
- The `cy.session()` command in the driver packages browser state and transmits it to the server, enabling instant restoration in subsequent tests.
- Because the cache exists only in the server process, session data is isolated per Cypress run and automatically clears when the process exits.

## Frequently Asked Questions

### Where does Cypress store session data?

Cypress stores session data in an in-memory cache within the Node.js server process, specifically in the `globalSessions` and `specSessions` maps defined in [`packages/server/lib/session.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/session.ts). This data is never written to disk or external databases, ensuring fast access and automatic cleanup when the test run completes.

### How does cy.session() communicate between the browser and the server?

The `cy.session()` command uses Cypress's internal WebSocket channel to communicate. The browser driver emits `save:session` messages to store authentication state and `get:session` messages to retrieve it, with handlers in [`packages/server/lib/socket.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/socket.ts) managing the interaction with the in-memory cache.

### What is the difference between globalSessions and specSessions?

`globalSessions` persists authentication data across multiple spec files when `cacheAcrossSpecs: true` is set, while `specSessions` contains data that exists only for the current spec file and is automatically cleared when the spec completes. Both are stored in memory and managed by the functions in [`packages/server/lib/session.ts`](https://github.com/cypress-io/cypress/blob/main/packages/server/lib/session.ts).

### How do I clear cached sessions in Cypress?

You can clear sessions using `cy.clearCookies()`, `cy.clearLocalStorage()`, or `cy.clearAllSessions()`, which emits the `clear:sessions` WebSocket message with `clearAll: true` to empty both `globalSessions` and `specSessions` maps on the server.