{"id":15586,"library":"cypress-data-session","title":"Cypress Data Session","description":"cypress-data-session is a Cypress plugin designed to streamline test data setup and reuse by implementing a powerful caching mechanism. It provides the `cy.dataSession` command, allowing developers to define how test data (like user objects, authentication tokens, or complex API responses) is created, validated, cached, and recreated if necessary. This plugin significantly speeds up test execution by avoiding repetitive, expensive data creation operations across multiple tests or even different spec files. Currently at v3.0.0, the package sees consistent maintenance and bug fixes, with major versions introducing breaking changes tied to Cypress core updates. Its key differentiator from Cypress's native `cy.session` command is its flexibility: `cy.dataSession` can cache *anything* (not just browser session state), provides direct access to cached data, supports custom validation logic, dependent caching, time limits, use count limits, and offers static utility methods, making it highly adaptable for complex test scenarios.","status":"active","version":"3.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/bahmutov/cypress-data-session","tags":["javascript","cypress","cypress-commands","typescript"],"install":[{"cmd":"npm install cypress-data-session","lang":"bash","label":"npm"},{"cmd":"yarn add cypress-data-session","lang":"bash","label":"yarn"},{"cmd":"pnpm add cypress-data-session","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Internal logging utility.","package":"debug","optional":false}],"imports":[{"note":"Importing this package registers the `cy.dataSession` command on the global Cypress object. It's primarily a side-effect import. Use `import` for module systems and `require` in CommonJS support files if not using a bundler.","wrong":"const cypressDataSession = require('cypress-data-session');","symbol":"cy.dataSession (command registration)","correct":"import 'cypress-data-session';"},{"note":"The `setupNodeEvents` function is used in `cypress.config.ts/js` to register Node.js events for inter-process communication, especially when using `shareAcrossSpecs`.","wrong":"const { setupNodeEvents } = require('cypress-data-session/src/plugin');","symbol":"setupNodeEvents","correct":"import { setupNodeEvents } from 'cypress-data-session/plugin';"},{"note":"This utility function allows programmatic clearing of all cached data sessions. It's generally imported from the main package entry point, as there is no dedicated 'utils' export path in `package.json`.","wrong":"const { clearAllDataSessions } = require('cypress-data-session/src/utils');","symbol":"clearAllDataSessions","correct":"import { clearAllDataSessions } from 'cypress-data-session';"}],"quickstart":{"code":"import { defineConfig } from 'cypress';\nimport { setupNodeEvents } from 'cypress-data-session/plugin';\n\n// cypress.config.ts\nexport default defineConfig({\n  e2e: {\n    setupNodeEvents(on, config) {\n      setupNodeEvents(on, config); // Register plugin tasks\n      // IMPORTANT: return the config object\n      return config;\n    },\n    baseUrl: 'http://localhost:3000', // Example base URL\n    specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}',\n  },\n});\n\n// cypress/support/e2e.ts\nimport 'cypress-data-session'; // Registers cy.dataSession command\n\n// cypress/e2e/user.cy.ts\ndescribe('User Management with Data Session', () => {\n  const userSessionName = 'testUser';\n  let createdUserId: string; // Store ID for cleanup\n\n  beforeEach(() => {\n    cy.dataSession({\n      name: userSessionName,\n      setup: () => {\n        cy.log('Creating new user via API...');\n        // In a real app, this would be an API call to create a user\n        return cy.request('POST', '/api/users', {\n          username: 'testuser_' + Date.now(), // Unique username\n          password: 'password123',\n        }).then((response) => {\n          expect(response.status).to.eq(201);\n          createdUserId = response.body.id;\n          return { id: createdUserId, token: response.body.token }; // Data to cache\n        });\n      },\n      validate: (cachedData: { id: string, token: string }) => {\n        cy.log(`Validating user: ${cachedData.id}`);\n        // Check if the user still exists and the token is valid\n        return cy.request({\n          method: 'GET',\n          url: `/api/users/${cachedData.id}`, \n          headers: { Authorization: `Bearer ${cachedData.token}` },\n          failOnStatusCode: false,\n        }).then(response => response.status === 200);\n      },\n      recreate: (cachedData: { id: string, token: string }) => {\n        cy.log(`Recreating session for user: ${cachedData.id}`);\n        // Use the cached token to log in or set session state\n        cy.setCookie('authToken', cachedData.token);\n        cy.visit('/'); // Navigate to the app after setting session\n      },\n      onInvalidated: () => {\n        cy.log(`Data session '${userSessionName}' was invalidated. Performing cleanup if needed.`);\n        // Optional: specific cleanup actions if validation fails\n      },\n      shareAcrossSpecs: true, // Allow sharing this session across multiple spec files\n      // expire: 3600000, // Optional: expire session after 1 hour\n      recomputeOnRetry: true, // Optional: recompute session if a test retries\n    }).then((user) => {\n      cy.log(`Using cached/created user: ${JSON.stringify(user)}`);\n      cy.wrap(user).as('currentUser'); // Alias the user data for the test\n      createdUserId = user.id; // Ensure ID is updated for current test run\n    });\n  });\n\n  it('should display the dashboard for the logged-in user', () => {\n    cy.get('.welcome-message').should('be.visible').and('contain', 'Welcome, testuser');\n    cy.get('@currentUser').its('id').should('eq', createdUserId);\n  });\n\n  it('should allow the user to access their profile page', () => {\n    cy.visit('/profile');\n    cy.get('.profile-details').should('contain', `User ID: ${createdUserId}`);\n  });\n\n  after(() => {\n    // Cleanup the created user from the backend after all tests complete\n    // This ensures a clean state for subsequent test runs\n    if (createdUserId) {\n      cy.request('DELETE', `/api/users/${createdUserId}`, { failOnStatusCode: false });\n    }\n  });\n});","lang":"typescript","description":"This quickstart demonstrates how to configure `cypress-data-session` in `cypress.config.ts`, register the command in the support file, and then use `cy.dataSession` within a test spec to create, validate, and reuse a 'user' data object across tests, including backend cleanup."},"warnings":[{"fix":"Ensure your Cypress installation is at version 15.10 or higher. Update your `cypress.config.js/ts` to use `setupNodeEvents` from the plugin correctly to register necessary tasks.","message":"Version 3.0.0 of `cypress-data-session` introduces a breaking change by no longer relying on `Cypress.env` for internal state management and instead using `Cypress.expose`. This change requires Cypress v15.10+.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Verify `cypress.config.ts/js` includes `import { setupNodeEvents } from 'cypress-data-session/plugin';` and calls `setupNodeEvents(on, config);` within the `e2e.setupNodeEvents` function.","message":"When `shareAcrossSpecs` option is enabled, the data session value is saved in the plugin process. This means that if `cypress-data-session` plugin's `setupNodeEvents` is not correctly registered in `cypress.config.js/ts`, sessions cannot be shared across different spec files.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For data that needs to persist across browser reloads or multiple spec files, ensure `shareAcrossSpecs: true` is included in your `cy.dataSession` options. Use `cy.dataSession`'s validation logic to handle data integrity checks.","message":"Directly clearing `Cypress.env` or reloading the browser can inadvertently clear `cy.dataSession` values if `shareAcrossSpecs` is not set to `true`, as the session data is typically stored in `Cypress.expose` (post v3) which resets on spec reloads or new specs.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Add `import 'cypress-data-session';` to your `cypress/support/e2e.ts` (or `cypress/support/index.ts` for older Cypress versions) file. Ensure your `cypress.config.ts` correctly points to your support file.","cause":"The `cypress-data-session` plugin has not been correctly imported into your Cypress support file, or the support file itself is not loaded.","error":"TypeError: cy.dataSession is not a function"},{"fix":"Provide a valid string for the `name` property within the `cy.dataSession` options object, e.g., `{ name: 'myUniqueSession', ... }`.","cause":"The `name` option passed to `cy.dataSession` must be a non-empty string.","error":"Cypress command 'dataSession' failed because the session name was not a string."},{"fix":"In your `cypress.config.ts/js`, ensure you `import { setupNodeEvents } from 'cypress-data-session/plugin';` and then call `setupNodeEvents(on, config);` inside your `e2e.setupNodeEvents` function, returning the `config` object.","cause":"The `setupNodeEvents` function from `cypress-data-session/plugin` was not called in your `cypress.config.ts/js`, or it was called incorrectly.","error":"Error: Cypress plugin 'dataSession' was not able to register its tasks. This usually happens if setupNodeEvents was not called."}],"ecosystem":"npm"}