How to Preserve Cookies Across a Cypress Test Suite
Keep Cypress cookies and login state reliable with cy.session(), setCookie(), isolation choices, cross-spec caching, and common fixes.

Use cy.session() for authentication and other server-created state. For a known cookie value, recreate it in beforeEach with cy.setCookie(). Disable test isolation only for a narrowly scoped suite that intentionally shares browser state.
With test isolation enabled, Cypress clears cookies, localStorage, and sessionStorage before each test, so a cookie created by one test normally does not exist in the next. See the Cypress test isolation documentation.
1. Choose the right method
| Situation | Use | Reason |
|---|---|---|
| Login creates authentication on the server | cy.session() |
Caches and restores cookies, local storage, and session storage. |
| Cookie value is known beforehand | cy.setCookie() in beforeEach |
Every test starts with deterministic state. |
| Tests are one intentional stateful workflow | testIsolation: false |
State remains available inside that suite, but tests can become order-dependent. |
| Reuse is needed across spec files in one run | cacheAcrossSpecs: true |
Shares the in-memory session cache on one machine during one Cypress run. |
2. Preserve login state with cy.session()
Place this helper in your Cypress support file:

const login = (name = 'user1') => {
cy.session(
name,
() => {
cy.request({
method: 'POST',
url: '/login',
body: { name, password: 's3cr3t' },
})
},
{
validate() {
cy.visit('/user_profile')
cy.contains(`Hello ${name}`)
},
cacheAcrossSpecs: true,
},
)
}
Cypress.Commands.add('login', login)
Use it before visiting a protected page:
describe('account', () => {
beforeEach(() => {
cy.login('user1')
cy.visit('/dashboard')
})
it('shows the dashboard', () => {
cy.contains('Dashboard').should('be.visible')
})
})
The setup callback runs when the session is absent. Cypress then preserves all cookies, localStorage, and sessionStorage captured by setup. The validate callback determines whether a cached session remains usable; a failed validation causes setup to run again. Cypress clears the page and browser context while establishing or restoring the session, so call cy.visit() after cy.session() before interacting with the page. Read the cy.session() API reference.
Use a complete session id
The first argument identifies the cache entry. Include every input that changes authentication state, such as username, tenant, or role:
cy.session(['user', name, role], setupLogin, options)
When using cacheAcrossSpecs, keep the id, setup, validation, and option values identical in every spec.
3. Recreate a known cookie in each test
This pattern suits consent cookies, feature flags, and other values known before the test:
beforeEach(() => {
cy.setCookie('cookieConsent', 'accepted')
cy.visit('/dashboard')
})
it('skips the consent prompt', () => {
cy.get('[data-testid="dashboard"]').should('be.visible')
})
Cypress uses the current hostname as the default cookie domain. For a cookie shared by subdomains, pass an explicit domain:
cy.setCookie('session', 'value', {
domain: '.example.test',
path: '/',
secure: true,
httpOnly: false,
})
Browser-side JavaScript cannot create an httpOnly cookie. Create that cookie through a server login, cy.request(), or a test-only endpoint.
4. Disable isolation only for an intentional stateful suite
describe('Marketing pages', { testIsolation: false }, () => {
before(() => {
cy.setCookie('cookieConsent', 'accepted')
cy.visit('/home')
})
it('shows the home page', () => {
cy.contains('Welcome').should('be.visible')
})
it('shows the about page', () => {
cy.visit('/about')
cy.contains('About').should('be.visible')
})
})
Cookies and the page remain available between tests in this block. State can leak, and failures may depend on execution order. Run each test alone while reviewing the suite. Prefer cy.session() or explicit setup when tests should be independently runnable.
5. Reuse sessions across spec files
cy.session(
['user', 'user1'],
() => {
cy.request('POST', '/login', {
name: 'user1',
password: 's3cr3t',
})
},
{
validate: () => cy.request('/api/me').its('status').should('eq', 200),
cacheAcrossSpecs: true,
},
)
cacheAcrossSpecs: true works only during the same cypress run on the same machine. The cache is in memory, empty at the start of a new run, and is not shared by parallel CI machines. Each worker must establish its own session.
6. Complete authenticated spec
describe('billing', () => {
beforeEach(() => {
cy.session(['billing-user', 'user1'], () => {
cy.request({
method: 'POST',
url: '/login',
body: { name: 'user1', password: 's3cr3t' },
})
}, {
validate() {
cy.request('/api/me').its('status').should('eq', 200)
},
cacheAcrossSpecs: true,
})
cy.visit('/billing')
})
it('loads invoices', () => {
cy.get('[data-testid="invoices"]').should('be.visible')
})
})
7. Migrate removed cookie APIs
Cypress.Cookies.defaults and Cypress.Cookies.preserveOnce were removed. Replace them with cy.session() for authentication or explicit cy.setCookie() setup for known values. See the Cypress migration guide.
8. Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Cookie exists in one test but not the next | Isolation cleared browser state. | Set it in beforeEach or create a session. |
Page is logged out after cy.session() |
No page was loaded after restore, or validation accepts an expired session. | Call cy.visit() afterward and validate a protected endpoint or page. |
| Two users share a cached session | The session id is identical. | Include username, tenant, and role in the id. |
| Cross-subdomain cookie is missing | Domain defaulted to one hostname. | Set the parent domain explicitly and verify path, Secure, and SameSite requirements. |
| Cross-spec caching fails in CI | Specs run on different machines or runs. | Log in once per CI worker; do not expect a shared durable cache. |
| Tests pass only in order | State leaked with isolation disabled. | Restore isolation and move setup to beforeEach. |
| Cannot set an httpOnly cookie | Browser JavaScript cannot write it. | Use server login or cy.request(). |
9. Reliability, speed, and cost
- Reliability: deterministic setup prevents hidden ordering dependencies. Validate sessions against an authenticated API or page.
- Speed:
cy.session()avoids repeating expensive login work while retaining test isolation. Keep validation lightweight. - Parallel CI: each worker has its own browser and session cache, so seed credentials or log in per worker.
- Security: use dedicated test accounts, keep secrets in Cypress environment variables, and never print cookie values.
- Cost: session caching reduces repeated application login work but is not a durable cross-run cache.
10. Or skip the browser setup
If you need a clean image of a page rather than an interactive Cypress assertion, ScreenshotNeo provides one GET request for a screenshot or PDF. Before capture it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing result. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

See the ScreenshotNeo API documentation for configuration options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Create a free ScreenshotNeo account with 1,000 screenshots each month and no credit card.
11. FAQ
Does cy.session() preserve only cookies?
No. It preserves cookies, localStorage, and sessionStorage captured during setup.
Can sessions be shared between parallel machines?
No. Cross-spec caching is limited to one Cypress run on one machine.
Should test isolation be disabled globally?
Usually no. Scope intentional state sharing to one small suite.
Why is a fixed cookie gone?
Isolation clears it before the next test. Recreate it in beforeEach.


