How do you keep login and cookies between tests?
cy.session keeps a login between tests: setup runs once, and the cookies and storage are cached and restored in later tests with the same id. Without it the login does not survive, because test isolation clears cookies and storage before every test. The validate option checks that the restored session is still alive, otherwise setup runs again, and each role gets its own id.
Cypress · State and sessions
Every test starts with a login, so 40 tests log in 40 times. How do you keep the session?
Cypress has always cleared cookies and localStorage between tests, and since version 12 test isolation also resets the page and sessionStorage, all of it across every domain. So a login done in one test does not survive to the next. The old Cypress.Cookies.preserveOnce was removed, and copying cookies between tests by hand is brittle. The modern answer is cy.session.
How it works
cy.session(id, setup, options) runs setup (the login) once for that id and caches cookies, localStorage and sessionStorage. In later tests with the same id Cypress clears the current state and restores the saved one without logging in. The validate option checks that the restored session is still alive; if not, setup runs again.
Life of a session
Example: from copying cookies to cy.session
// Before: a login in every test
beforeEach(() => {
cy.visit('/login');
cy.get('[data-cy=email]').type('qa@example.com');
cy.get('[data-cy=password]').type('secret');
cy.get('[data-cy=submit]').click();
});
// After: log in once, then restore
Cypress.Commands.add('login', (user: string) => {
cy.session(
user,
() => {
cy.request('POST', '/api/login', { user }); // faster than the UI
},
{
validate: () => {
cy.request('/api/me').its('status').should('eq', 200);
},
},
);
});
beforeEach(() => cy.login('qa'));
Logging in through cy.request inside setup is faster and more stable than the UI. A dedicated test of the login form itself still goes through the interface.
Limits and alternatives
By default a session is cached within one spec; cacheAcrossSpecs: true shares it across specs. After cy.session the page is blank, so cy.visit is needed in the test itself. Different roles use different ids. The Playwright counterpart is storageState: a setup project logs in, saves the state to JSON, and other projects load it through dependencies.
What exactly is cleared and cached
Before setup and before a restore Cypress clears cookies, localStorage and sessionStorage for all domains, and with test isolation on it clears the page too. The cache holds the same: cookies, localStorage and sessionStorage of every domain the session touched. The cache lives in memory, so a new cypress run starts empty. A practical consequence: a test that checks the login must not depend on another test's session.
What counts as a failed check in validate: a thrown error, a promise resolving to false or rejecting, a failing Cypress command, or a last command yielding false. Returning a plain false without a promise is not enough. If validate fails right after setup, the test fails with an error: the freshly created session is useless. If it fails after a restore, Cypress runs setup again.
// Separate roles and reuse across specs
cy.session(
['admin', 'v2'], // id: role + setup version
() => loginViaApi('admin'),
{
validate: () => {
cy.request('/api/me').its('status').should('eq', 200);
},
cacheAcrossSpecs: true, // in-memory cache for one run
},
);
cy.visit('/dashboard'); // we open the page ourselves
If the login changed (another endpoint or cookie), the old cache within a run no longer matches the code, so a version inside the id is useful. A separate case is tests that check the login form itself: a session gets in their way, since they start from a guaranteed clean state.
Common mistakes
- One
idfor different users: a test gets someone else's session. - No
validate: an expired token fails far from its cause. - Forgetting
cy.visitafter the restore: the test starts on a blank page.
Check yourself
The token in the session cache has expired. Which option catches it and what happens?
Answer
validate: after the restore Cypress runs it, and if the check fails the session is recreated through setup.
Why does a login in the first test not carry over to the second, though cookies were not deleted by hand?
Answer
Because of test isolation Cypress itself clears cookies and storage before each test. Keeping them needs cy.session.
cy.session: it runs the login once, caches cookies and storages and restores them in later tests. Middle/Senior: I add validate, log in through the API in setup and use a separate id per role. The old preserveOnce was removed in version 12, and copying cookies by hand is brittle.