Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk5 min

How to Use cy.session() to Speed Up Cypress Authentication

Cache Cypress authentication with cy.session() while validating restored sessions, keeping IDs safe, and navigating correctly under test isolation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use cy.session() to cache the browser state created by a successful login, then restore that state instead of repeating the login flow in every test. Put the login and a success assertion inside the session’s setup callback, validate that restored sessions are still authenticated, and call cy.visit() after cy.session() to open the page your test needs.

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

cy.session(id, setup, options) runs a setup callback, then caches the browser’s cookies, localStorage, and sessionStorage. When Cypress encounters the same ID again, it restores that saved state and skips setup if the session remains valid. This avoids repeating the login work; it does not automatically navigate to the page under test.

As an Amazon Associate I earn from qualifying purchases.

The command follows the configured testIsolation behavior. With isolation enabled, Cypress clears the page when caching and restoring browser context. That is why the test should visit its target route after the session call.

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

Build a reusable UI-login session

Define the login flow in a custom command or shared helper so tests use the same ID, setup, validation, and options. This example uses a form-based login and a protected API endpoint to check authentication:

const login = (username, password) => {
  cy.session(
    ['login', username],
    () => {
      cy.visit('/login')
      cy.get('[data-test=name]').type(username)
      cy.get('[data-test=password]').type(password, { log: false })
      cy.get('form').contains('Log In').click()
      cy.url().should('contain', '/login-successful')
    },
    {
      validate() {
        cy.request('/api/user').its('status').should('eq', 200)
      },
    }
  )
}

it('shows the account page', () => {
  login(Cypress.env('username'), Cypress.env('password'))
  cy.visit('/account')
  // assertions for the test
})

Replace the selectors, routes, and endpoint with your application’s. The assertion inside setup matters: Cypress should not cache state until the login flow has actually completed. The example suppresses password text in the Command Log with { log: false }. Keep credentials out of source control; Cypress documents accessing environment values inside session setup in its environment-variable guidance.

Choose an ID that represents the authentication state

The ID must change when an input that affects the resulting session changes. Include non-secret identifiers such as username, role, or tenant where relevant. Cypress accepts strings, arrays, or objects and deterministically serializes arrays and objects. Do not put passwords, tokens, or other secrets in the ID: it is visible in Cypress reporting and debugging tools.

Validate restored authentication

Use validate to make an authenticated request or visit a protected page and assert that it succeeds. If validation fails while restoring a cached session, Cypress runs setup again. If it fails immediately after setup, the test fails instead, which helps expose an incomplete login rather than caching it as valid.

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

Use an API login when the application supports one

If the application offers a test-appropriate authentication endpoint, a request can establish a session without driving the login form. Cypress documents using cy.request() inside setup, checking the response, and allowing server-set authentication cookies to populate the browser cookie jar. For bearer-token authentication, save the token in localStorage, which is included in the cached browser state. Validate against an authenticated-user endpoint that returns success only for an authenticated user.

A request-based flow is not automatically better: choose it when the API represents the authentication behavior your tests need and when its resulting cookie or token is the same state the application uses. Keep a UI login test where verifying the real form and redirect is itself important. Cypress’s API testing guide covers API login, cookies, bearer tokens, and validation.

Reuse a session across spec files

Set cacheAcrossSpecs: true when multiple specs in the same Cypress run on the same machine should share a session:

cy.session(
  ['login', username],
  setupLogin,
  {
    validate: validateLogin,
    cacheAcrossSpecs: true,
  }
)

This cache is limited to one cypress run on one machine. It does not persist across separate runs or across parallel CI machines. Each participating spec must call the session with consistent ID, setup, validation, and option values. A shared custom command or helper reduces accidental mismatches.

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

What speed improvement to expect

Cypress’s test-performance guide estimates that a full login flow—filling a form, submitting, and waiting for a redirect—typically takes 2–5 seconds per test. It illustrates that 100 tests could add 3–8 minutes of authentication overhead. These are Cypress’s published estimates, not a guaranteed result for every application; actual savings depend on your login flow, app response time, and how often setup can be skipped. See Cypress’s test-performance guide.

Troubleshoot common session failures

The page is blank or commands cannot find page elements

With testIsolation: true, the page is cleared as Cypress caches and restores browser context. Call cy.visit('/target-route') after the session command returns, before interacting with the page.

A request returns 401 after restoring the session

The cached authentication may have expired, or setup may have completed before authentication was actually established. Assert login success inside setup and make validate fail for an unauthenticated user, such as by checking a protected endpoint’s status. Cypress can then rerun setup when validation fails on restore.

The test restores the wrong user, tenant, or role

Add every non-secret input that changes the session to the ID. For example, a role-specific session should distinguish the role as well as the username. Never solve this by adding credentials or bearer tokens to the ID.

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

A session is not reused by another spec

Confirm that both specs set cacheAcrossSpecs: true and use matching IDs, setup callbacks, validation, and options. Confirm they run in the same cypress run on the same machine; parallel workers have separate caches and must establish their own sessions.

Disabling test isolation appears to fix a failure

Do not treat disabled isolation as a general speed fix. Cypress cautions that retaining browser state can let one test affect another and create inconsistent results, including when running a test with .only(). Understand the configuration’s effects and preserve independent test setup where possible.

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

Version and documentation notes

Cypress’s API reference records that cacheAcrossSpecs was added in 10.9.0, setup became required in 11.0.0, and cy.session() became available by default in 12.0.0 after removal of experimentalSessionAndOrigin. Those are version-history notes, not a statement of the current release. Check the current API reference and your project’s installed Cypress version for version-specific behavior. Cypress also discusses authentication reuse in its end-to-end testing guide and Why Cypress? overview.

Or skip the browser setup

If your task is capturing a website screenshot rather than testing an application’s login flow, ScreenshotNeo offers a screenshot API and MCP server. A single request can return an image or PDF; it removes cookie banners, newsletter popups, and chat widgets before capture, and bot checks, blank pages, and failed loads are not billed. AI agents can use its MCP server, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

For example, this cURL request captures a page as WebP (replace the URL and API key):

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 request options and setup. Sign up for 1,000 free screenshots a month, with no card required.

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 *

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.