← Back to library
Cypressauthadvancedv12+
Cache auth session with cy.session
Persist login state across tests so the API login runs once per spec, not per test.
1Cypress.Commands.add('loginWithSession', (email, password) => {
2 cy.session(
3 [email, password], // cache key — change it to invalidate the session
4 () => {
5 cy.request({ method: 'POST', url: '/api/login', body: { email, password } })
6 .then(({ body }) => {
7 window.localStorage.setItem('auth_token', body.token);
8 });
9 },
10 { cacheAcrossSpecs: true } // reuse across multiple spec files
11 );
12});
13
14// Usage in any test:
15// cy.loginWithSession('user@test.com', 'password');
16// cy.visit('/dashboard');#cy.session#cache#performance#auth