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

If a Cypress Cucumber scenario appears to sign out when you click a dashboard control, first determine when authentication disappears. A reset between tests is usually test isolation or a Cucumber hook; a logout during one test is more often a request, redirect, expired token, or response that clears the auth cookie. Keep isolation enabled, establish authentication deliberately with cy.session(), visit the dashboard after restoring the session, and inspect network traffic around the action before changing configuration.

Identify the boundary where authentication is lost

Run the failing scenario by itself, then run the surrounding feature or full suite. Record the first point at which the browser is unauthenticated:

  • At the start of a new it test or Cucumber scenario: suspect Cypress test isolation, scenario cleanup, or a missing login setup.
  • Immediately after cy.session(): check that the session was saved after login completed and that you call cy.visit() afterward.
  • After a Before hook: inspect cookie and storage cleanup order.
  • After a dashboard click in the same test: inspect the request, response, navigation, and token validity. Do not assume the control itself logged out.

Cypress documents that tests should run independently, and Cucumber likewise requires scenarios to be independent. See Cypress test isolation and Cucumber state guidance.

Understand what Cypress resets

With end-to-end test isolation enabled, Cypress resets the page to about:blank and clears cookies, localStorage, and sessionStorage before each test. An authenticated browser in one test therefore does not automatically authenticate the next test.

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

Isolation does not clear every storage mechanism. IndexedDB persists, and cy.session() does not capture or clear IndexedDB. If your application stores an access token, refresh token, or user marker there, include that store in your diagnosis rather than expecting cookie cleanup to explain every result.

Check both the global configuration and any suite-level override:

import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    testIsolation: true
  }
});

Also search the project for testIsolation: false, beforeEach, Cucumber Before/After hooks, and helpers that call clearCookies(), clearLocalStorage(), or application logout endpoints.

Restore authentication with cy.session()

cy.session() caches and restores browser cookies, local storage, and session storage. It does not load the dashboard page for you when isolation is enabled, so visit the required URL after the session command.

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

UI login example

function loginAs(user) {
  cy.session(
    ['user', user.email],
    () => {
      cy.visit('/login');
      cy.get('[name=email]').type(user.email);
      cy.get('[name=password]').type(user.password, { log: false });
      cy.get('button[type=submit]').click();

      // Use an application success condition that retries.
      cy.url().should('include', '/dashboard');
      cy.get('[data-testid="account-menu"]').should('be.visible');
    },
    {
      validate() {
        cy.request('/api/me').its('status').should('eq', 200);
      }
    }
  );

  cy.visit('/dashboard');
}

describe('dashboard actions', () => {
  beforeEach(() => {
    loginAs({ email: Cypress.env('USER_EMAIL'), password: Cypress.env('USER_PASSWORD') });
  });

  it('updates a dashboard setting', () => {
    cy.get('[data-testid="settings"]').click();
    cy.get('[data-testid="save"]').click();
    cy.contains('Saved').should('be.visible');
  });
});

The session ID should include every value that changes the authenticated context, such as the user, tenant, role, or feature setup. An ID that is too broad can restore a cached session created for a different account.

Do not cache before login has finished

A click or redirect finishing is not necessarily proof that the server has issued the cookie or that the application has stored its token. Put a retryable assertion after the login operation: a protected URL, visible authenticated element, successful API response, or app-specific token check. Cypress notes that cy.getCookie() itself does not retry; if you use it, assert in a way that matches your application’s timing rather than relying on an immediate read.

Use validate() when sessions can expire or be invalidated. If validation fails, Cypress reruns the session setup instead of continuing with a stale cache.

Authenticate through an API when the UI is not under test

For dashboard tests whose scope is not the login form, an API login can be faster and less fragile. Cypress API requests share the browser cookie jar: matching cookies are sent with the request, and returned Set-Cookie headers are applied to the browser. That convenience also means an API response can remove authentication.

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.
function loginByApi() {
  cy.session(['api-user', Cypress.env('USER_EMAIL')], () => {
    cy.request('POST', '/auth/login', {
      email: Cypress.env('USER_EMAIL'),
      password: Cypress.env('USER_PASSWORD')
    }).its('status').should('eq', 200);
  }, {
    validate() {
      cy.request('GET', '/api/me').its('status').should('eq', 200);
    }
  });

  cy.visit('/dashboard');
}

describe('reports', () => {
  beforeEach(loginByApi);

  it('opens a report', () => {
    cy.get('[data-testid="report-link"]').click();
    cy.contains('Report').should('be.visible');
  });
});

Adapt paths, payloads, and status assertions to your application. A successful login endpoint alone does not prove that the dashboard’s authorization check will accept the resulting cookie or token.

Audit Cucumber hooks and scenario state

Cucumber’s World and step-definition state do not automatically isolate the external browser’s cookie jar. If the browser is shared, Cucumber recommends clearing cookies in a Before hook so each scenario starts clean. The ordering matters: clear stale state first, then perform the scenario’s login.

import { Before } from '@badeball/cypress-cucumber-preprocessor';

Before(() => {
  cy.clearCookies();
  cy.clearLocalStorage();
  // Establish authentication after cleanup, not before it.
});

If a hook clears cookies after a login step, or a second hook runs in an unexpected order, it can create the exact appearance of a dashboard logout. Temporarily log hook execution and inspect the Application panel after each hook. Keep scenarios independent rather than relying on the previous scenario’s browser state.

Trace what a dashboard action does

When the loss occurs within one test, open Cypress’s command log and browser network panel. Add targeted intercepts around the action:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
cy.intercept('**/api/**').as('api');
cy.get('[data-testid="archive"]').click();
cy.wait('@api').then(({ request, response }) => {
  cy.log(`${request.method} ${request.url}`);
  cy.log(`status: ${response?.statusCode}`);
});

Look specifically for:

  • Navigation to a sign-in route or a 401/403 response followed by a redirect.
  • An explicit logout request triggered by the action or an error handler.
  • An expired access or refresh token and a failed refresh exchange.
  • A Set-Cookie header with an expired date, Max-Age=0, or an empty authentication value.
  • A response from an API setup call that replaces the correct cookie with a cookie for another domain, path, or session.
  • Cross-origin behavior: the cookie’s domain, path, Secure, and SameSite attributes may prevent it being sent where the dashboard expects it.

Compare the cookie before and after the click, and check the response that changed it. If no cookie changes, inspect local/session storage and the application’s in-memory auth store; a page reload can expose a token that was never persisted.

Choose an approach deliberately

Approach When it fits Main trade-off
cy.session() with UI login The scenario establishes or verifies the real login interface. Slower setup; the success assertion must wait for completed authentication.
cy.session() with API login Dashboard behavior is in scope, but login UI is not. Exercises API authentication and shared cookies, not the login form.
Isolation enabled plus cached session per test You want independent tests without repeating a full login. Requires a complete session ID, validation, and an explicit dashboard visit.
testIsolation: false The suite intentionally models one continuous browser session. State leaks, ordering dependencies, and sequence-only passes become more likely.
Cucumber Before cleanup A shared browser must begin each scenario clean. Incorrect ordering can erase the login you intended to use.

When disabling isolation is acceptable

Cypress allows { testIsolation: false } on an end-to-end describe block:

describe('continuous workflow', { testIsolation: false }, () => {
  it('logs in', () => {
    cy.visit('/login');
    // login steps
  });

  it('continues in the dashboard', () => {
    cy.visit('/dashboard');
  });
});

Use this only when persistence across tests is part of the behavior being modeled. It weakens independent execution and can make a test pass only after another test has prepared cookies or storage. For ordinary dashboard coverage, leave isolation on and restore authentication in each test or scenario.

Troubleshooting checklist

The next scenario is signed out

  • Confirm isolation is enabled and expected.
  • Call the login/session helper in that scenario’s setup.
  • Check that a Cucumber cleanup hook runs before, not after, login.
  • Ensure the session ID differs for different users or tenants.

The dashboard is blank after cy.session()

  • Call cy.visit('/dashboard') after the session command.
  • Do not assume restored cookies also restore the current page.
  • Check IndexedDB or in-memory stores if the application needs them.

The session is cached while login is still running

  • Replace fixed waits with a retryable URL, UI, or protected-endpoint assertion.
  • Verify redirects and asynchronous token exchange have completed.
  • Add validate() to detect an unusable restored session.

A click signs out immediately

  • Inspect the action’s request and every response header.
  • Search for logout calls, token-refresh failures, 401 responses, and clearing Set-Cookie values.
  • Compare browser cookies and storage immediately before and after the click.

Tests pass alone but fail in the suite

  • Run scenarios in a different order and in parallel where supported.
  • Remove hidden dependencies on prior World variables, cookies, or database records.
  • Keep isolation enabled unless sequence is explicitly the behavior under test.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your workflow is collecting page images rather than testing authentication, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; failed loads, bot checks/CAPTCHAs, blank pages, timeouts, and cache hits are not billed as clean shots. Responses identify the result with X-Page-Verdict and X-Billed headers. Its MCP tools let Claude, Cursor, or another MCP client call take_screenshot, get_page_info, and capture_pdf.

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.
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 the complete options, including device presets, full-page capture, CSS selectors, custom JavaScript, cookies, headers, waiting rules, PDF settings, caching, signed links, webhooks, bulk capture, and usage reporting.

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.

FAQ

Should every Cucumber scenario log in through the UI?

No. Test the login UI in dedicated scenarios; use a validated API-created session for dashboard scenarios when that better matches their scope.

Can a successful dashboard response prove the session is healthy?

Only if the response exercises the same authentication path the dashboard uses. A dedicated protected endpoint in validate() gives a clearer session check.

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

Why does clearing cookies not fix a logout caused by storage?

Authentication may live in IndexedDB, session storage, local storage, or an in-memory application store. Inspect all stores your application uses and align cleanup and restoration with that design.

Frequently Asked Questions

Should every Cucumber scenario log in through the UI?

No. Test the login UI in dedicated scenarios; use a validated API-created session for dashboard scenarios when that better matches their scope.

Can a successful dashboard response prove the session is healthy?

Only if the response exercises the same authentication path the dashboard uses. A dedicated protected endpoint in validate() gives a clearer session check.

Why does clearing cookies not fix a logout caused by storage?

Authentication may live in IndexedDB, session storage, local storage, or an in-memory application store. Inspect all stores your application uses and align cleanup and restoration with that design.

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

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.