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.
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.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →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.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallWhat 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.
Rank #4
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.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsA 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.
Best Value
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.
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.
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.
Quick Recap
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.




