Using Existing Browser Sessions for Automation with Cypress

Introduction

In this blog, let's see how we can use existing browser sessions for automation with Cypress.

One common challenge in test automation is speeding up tests, especially when dealing with login flows or sessions. A great way to save time is by reusing existing browser sessions rather than logging in repeatedly during every test run. Here’s how you can make the most of session management with Cypress

Why Use Existing Sessions?

  • Improves Test Speed: No need to log in every time a test runs.
  • Reduces Flakiness: Avoids issues from repeated authentication (e.g., MFA timeouts).
  • Easier State Management: Helps maintain test context across multiple test cases.

How to Reuse Browser Sessions in Cypress?

Use cy.session() to Save and Restore Sessions

Cypress 9.6+ introduced the cy.session() API, which allows saving sessions and restoring them automatically in future tests.

Cypress.Commands.add('login', () => {
    cy.visit('/login');
    cy.get('hashtag#username').type('testuser');
    cy.get('hashtag#password').type('password123');
    cy.get('button[type="submit"]').click();
});

describe('Reuse Session Example', () => {
    beforeEach(() => {
        cy.session('loginSession', () => {
            cy.login();
        });
    });

    it('should visit the dashboard', () => {
        cy.visit('/dashboard');
        cy.contains('Welcome, testuser').should('be.visible');
    });
});

How it works?

  • Cypress saves the session (cookies, local storage, etc.) under a unique identifier.
  • On subsequent tests, the session is restored, skipping the login steps.

Use Local Storage / Cookies Directly

If cy.session() isn’t enough for your use case, you can manually manage cookies or local storage.

Cypress.Commands.add('setSession', () => {
    cy.setCookie('session_id', 'your-session-id');
    localStorage.setItem('auth_token', 'your-auth-token');
});

Leverage Browser Debugging (for Dev Sessions)

In some cases (like development testing), you can directly connect to the browser session Cypress is running using tools like Chrome DevTools Protocol or persistent browser contexts.

Best Practices for Using Sessions

  1. Clear Sessions After Tests: Avoid stale sessions by clearing cookies/local storage at the end.
  2. Handle Environment Differences: Ensure sessions are restored correctly between different test environments.
  3. Monitor for Expiry Issues: Automate session renewal if tokens expire during long test runs.

Note. Reusing sessions is a great way to boost your test efficiency, especially for login-heavy flows. With tools like cy.session() and smart cookie management, your tests can run faster and smoother! ??

Summary

In this blog, here we tried to understand the use of existing browser sessions for automation with Cypress.