DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk6 min

How to Fix Common cy.session() Issues in Cypress

Diagnose common Cypress cy.session() failures by checking page isolation, login setup, validation, IDs, browser storage, and cache scope.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If Cypress commands fail after cy.session(), visit the page you need after restoring the session: with testIsolation enabled, Cypress clears the page, and restoring cookies and storage does not load your app. For 401s, wrong accounts, or missing state, check that login completes before setup ends, validate authentication, and use a session ID that distinguishes every state-changing input.

What cy.session() restores—and what it does not

cy.session() saves cookies, localStorage, and sessionStorage after its setup and validation steps. When Cypress encounters the same session ID later, it can restore that browser data instead of repeating login setup. It does not cache or load the application page. See the Cypress cy.session() API reference.

As an Amazon Associate I earn from qualifying purchases.

That distinction explains the most common failure: authentication data may be restored correctly while the browser is still on a blank page. The right fix depends on whether the symptom is a blank page, an authentication failure, the wrong identity, missing storage, or an assumption about reuse across specs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Commands fail after cy.session(): visit the page under test

When testIsolation is enabled, Cypress clears the page. After the session command, explicitly load the route your test needs before querying or interacting with the app. Cypress states: “When testIsolation is enabled, ensure that you’re calling cy.visit() after calling cy.session(), otherwise your tests will be running on a blank page.”

beforeEach(() => {
  cy.session('user', () => {
    cy.visit('/login')
    cy.get('[name=email]').type(Cypress.env('email'))
    cy.get('[name=password]').type(Cypress.env('password'), { log: false })
    cy.get('button[type=submit]').click()
    cy.url().should('include', '/dashboard')
  })

  // Restoring a session does not visit this page for you.
  cy.visit('/dashboard')
})

Keep the login-success assertion in the setup callback. That proves the login flow completed before Cypress saves the session. Do not use the post-restore page as evidence that setup succeeded: it is a separate step.

With testIsolation: false, Cypress does not clear the page before setup, though it still clears cookies and storage before setup. A visit is not needed solely to reload the page after cy.session() in that configuration. Disabling isolation can let one test affect another, so it is not a universal fix; make each test’s required state explicit.

401 after restoring a session: validate authentication

A 401 usually means the restored session is no longer authenticated, or setup finished before the application had established authentication. Add a validate callback that checks a protected page or authenticated API endpoint. Cypress validates sessions both after creating one and after restoring one.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
cy.session('user', () => {
  cy.visit('/login')
  cy.get('[name=email]').type(Cypress.env('email'))
  cy.get('[name=password]').type(Cypress.env('password'), { log: false })
  cy.get('button[type=submit]').click()
  cy.url().should('include', '/dashboard')
}, {
  validate() {
    cy.request('/api/me').its('status').should('eq', 200)
  }
})

cy.visit('/dashboard')

Use the endpoint and expected response that actually demonstrate authentication in your app. If validation fails on a restored session, Cypress reruns setup. If it fails immediately after setup, the test fails, exposing an incomplete login rather than silently accepting it.

Wrong user or role restored: make the ID represent the session

The session ID identifies the state produced by setup. If username, role, tenant, login method, or another changing input affects that state, include it in the ID. Otherwise Cypress can treat distinct logins as the same session and restore the wrong account.

const sessionId = {
  username: Cypress.env('email'),
  role: 'admin',
  tenant: 'north'
}

cy.session(sessionId, () => {
  // Log in as the specified identity and role.
})

Cypress deterministically stringifies array and object IDs, so structured IDs are suitable. Do not put passwords, access tokens, or other secrets in the ID: IDs appear in the reporter.

Missing or recreated storage: inspect saved and applied data

Use the Sessions Instrument Panel and command log to tell whether Cypress created, restored, or recreated a session. This separates a cache-selection problem from data that was never fully applied.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Cypress.session.getSession(id) inspects the saved session data.
  • Cypress.session.getCurrentSessionData() inspects the cookies and storage currently applied in the browser.

If expected attributes are absent, setup or validation may have finished before the application wrote them. Wait for a reliable application signal—such as the authenticated route, a visible signed-in element, or a successful protected request—before the session is saved. Cypress documents these inspection helpers in its session API.

Cross-spec reuse: know the cache boundary

cacheAcrossSpecs defaults to false. When enabled, its cache is in memory for one cypress run on one machine; it does not persist to disk, carry into a new run, or transfer between parallel CI machines. Each machine must establish its own session.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Specs that reuse a cross-spec session must call cy.session() consistently: use the same ID, setup, validation, and cacheAcrossSpecs value. If a later spec unexpectedly logs in again, first check whether it is in the same run and on the same machine, then compare those session definitions.

Old cookie-preservation code or subdomain surprises

Cypress.Cookies.defaults and Cypress.Cookies.preserveOnce were removed; Cypress recommends cy.session() for preserving cookies and browser storage. Check the migration notes if a test still relies on the older APIs: Cypress migration guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cookie commands use the hostname rather than the superdomain by default. If a test expects a cookie to be shared across subdomains, verify the cookie’s domain option instead of assuming that preservation across one host covers every subdomain.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

A practical troubleshooting order

  1. Classify the symptom: blank page, 401, wrong identity, missing storage, or cross-spec reuse.
  2. Check the command log and Sessions Instrument Panel to see whether Cypress created, restored, or recreated the session.
  3. Make setup prove login success with an assertion before it ends.
  4. Add or repair validate so it checks the authenticated state.
  5. Build the ID from all inputs that change session state; exclude secrets.
  6. After cy.session(), call cy.visit() for the route under test when isolation is enabled.
  7. For missing data, compare saved and applied state with Cypress.session helpers and wait for the app to apply storage.
  8. For cross-spec behavior, verify identical session definitions and remember the one-run, one-machine boundary.
  9. For legacy cookie code, check the migration and the cookie domain expected by the test.

Version behavior to check

The API history records cacheAcrossSpecs as added in Cypress 10.9.0, setup as required in 11.0.0, and the experimental session-and-origin flag as removed when the command became available by default in 12.0.0. Verify examples against the Cypress version installed in your project and the current API reference, particularly when migrating older tests.

Or skip the browser setup

If your task is to capture a page rather than debug Cypress authentication, ScreenshotNeo is a website screenshot API and MCP server. One GET request can return a screenshot or PDF; its clean-shot workflow accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture, with each step configurable. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server provides screenshot tools for AI agents, and 1,000 screenshots per month are free with no card; paid plans start at $5 for 3,000.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for parameters and response details. Sign up for 1,000 free screenshots a month, no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does cy.session() restore the page I was on?

No. It restores browser cookies and storage; load the page your test needs separately.

Does cacheAcrossSpecs share a session across parallel CI workers?

No. Its cache is limited to one Cypress run on one machine.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.