Using Playwright's storageState

Optimize your Playwright tests with storageState to speed up execution, maintain consistent sessions, and scale testing across browsers and devices.

Get Started free
Using Playwright's storageState
Home Guide Using Playwright’s storageState

Using Playwright’s storageState

Playwright’s storageState feature simplifies managing authentication and session data during test automation. By capturing and reusing browser storage such as cookies, localStorage, and IndexedDB, it enables tests to bypass repetitive login steps and execute more efficiently.

Overview

Playwright’s storageState provides an efficient way to capture and reuse session data such as cookies and localStorage, enabling faster and more stable tests.

How It Works

  • Capturing storageState: After performing a login or any action that sets session data (cookies, localStorage, etc.), you can capture the state using context.storageState({ path: ‘state.json’ }).
  • Reusing storageState: To reuse the saved state in future tests, load the storageState by passing it into your browser context: use: { storageState: ‘state.json’ } in the Playwright config.
  • Supports Cookies & Storage: It stores cookies, localStorage, and IndexedDB data, which helps persist user authentication or session information across tests.
  • Cross-Browser and Contexts: You can use the same storageState across different browsers or multiple contexts, enabling tests that need various user roles or environments.

Benefits of Using storageState

  • Speeds Up Test Execution: By reusing the authentication state, tests avoid repeated login steps, leading to faster execution.
  • Improves Test Stability: Avoids inconsistent test results caused by session changes or repeated logins, ensuring a stable testing environment.
  • Reduces Redundancy: Eliminates the need for redundant login steps across multiple tests, improving efficiency in large test suites.
  • Easy Authentication Management: Simplifies testing of authenticated flows by preserving the session state between tests, reducing setup time.
  • Better Resource Management: Reduces the overhead of recreating session data and handling session expiration during each test run.

This article explains how to effectively use Playwright’s storageState to capture, reuse, and manage session data, improving test efficiency and stability.

What is storageState in Playwright?

storageState in Playwright is a method that allows you to capture and persist the browser’s session data, including cookies, localStorage, and IndexedDB. This feature enables tests to reuse authentication and session information across different test runs, which helps speed up test execution by avoiding repetitive login steps.

By saving the session state to a file, you can load it in future tests to maintain the same user state, making your test automation more efficient and stable.

Playwright Testing

How to Capture storageState

Capturing storageState in Playwright is a straightforward process. After performing actions like logging into a website, you can save the session data (such as cookies, localStorage, and IndexedDB) to a file.

This allows you to reuse the authentication state in subsequent tests, speeding up your test execution.

Steps to Capture storageState

1. Create a Browser Context

First, create a browser context that simulates a real user session. A context can have its own session, cookies, and local storage.

const context = await browser.newContext();

2. Perform Actions (e.g., Log In):

Perform the actions that establish the session, such as logging into the application. This will generate the session data you want to capture.

const page = await context.newPage();
await page.goto(‘https://example.com/login’);
await page.fill(‘#username’, ‘user’);
await page.fill(‘#password’, ‘password’);
await page.click(‘#login-button’);

3. Capture the storageState:

After the actions are completed, capture the session state (cookies, localStorage, etc.) and save it to a JSON file.

await context.storageState({ path: ‘state.json’ });

4. Reuse the Captured storageState:

In subsequent tests, you can load this captured state to reuse the same authentication session without having to log in again.

const context = await browser.newContext({
storageState: ‘state.json’
});

This process saves time in your test suite, especially when authentication is required, by eliminating the need to log in for every test.

Using storageState to Reuse Authentication State

One of the primary uses of storageState in Playwright is to reuse authentication state across multiple tests. By saving the session data (cookies, localStorage, and IndexedDB) to a file after a successful login, you can load the saved state in future tests to avoid repeating the login process, making your tests faster and more efficient.

Steps to Reuse Authentication State Using storageState

1. Capture the Authentication State

First, perform a login to capture the session state. Save the authentication state to a file, for example, authState.json. This will include cookies and localStorage data that were created during the login process.

const context = await browser.newContext();
const page = await context.newPage();

// Perform login
await page.goto(‘https://example.com/login’);
await page.fill(‘#username’, ‘user’);
await page.fill(‘#password’, ‘password’);
await page.click(‘#login-button’);

// Save the authentication state
await context.storageState({ path: ‘authState.json’ });

2. Reuse the Authentication State in Future Tests

In subsequent tests, you can load the saved storageState file to maintain the same authentication state. This eliminates the need to log in again, saving valuable time.

const context = await browser.newContext({
storageState: ‘authState.json’ // Reuse saved authentication state
});
const page = await context.newPage();

// Now you can directly interact with the authenticated page
await page.goto(‘https://example.com/dashboard’);

By reusing authentication state with storageState, you can make your Playwright tests faster and more efficient, while ensuring a stable and consistent user context across different test scenarios.

Use Cases for storageState

Here are some common use cases where storageState can significantly improve test efficiency and consistency:

1. Reusing Authentication State

  • Scenario: Many applications require users to log in before accessing certain pages or features. Instead of logging in for each test, you can capture the authentication state (cookies, localStorage) after logging in once, and reuse it across tests.
  • Benefit: Speeds up tests by eliminating the need for repetitive login steps.

2. Testing Different User Roles

  • Scenario: In applications with multiple user roles (e.g., admin, regular user, guest), you can capture separate storageState for each role and load the appropriate state to test different user flows.
  • Benefit: Allows you to quickly switch between different user roles without needing to perform separate logins.

3. Persistent Sessions Across Tests

  • Scenario: When testing a multi-step process or workflows that span multiple tests, storageState ensures that session data (like shopping cart contents, form progress) persists across tests.
  • Benefit: Ensures continuity and saves time by maintaining the session state between tests.

4. Avoiding Session Expiry

  • Scenario: For applications where session tokens expire after a period, you can capture the valid session state before it expires and reuse it to avoid session-related failures during tests.
  • Benefit: Prevents issues related to expired sessions, ensuring more stable and reliable tests.

5. Scaling Tests in CI/CD Pipelines

  • Scenario: In CI/CD pipelines where tests need to run across multiple browsers or devices, storageState can be used to ensure consistent user sessions without needing to log in repeatedly across different environments.
  • Benefit: Speeds up execution by using pre-captured session states, making it easier to scale tests across multiple platforms.

6. Testing Session-Based Features

  • Scenario: For applications that rely on session data (e.g., user preferences, items in a cart), storageState can be used to capture and restore session-specific data between tests.
  • Benefit: Ensures that session-based features are tested accurately, without manually setting up session data for each test.

By using storageState in these scenarios, Playwright users can significantly reduce test setup time, increase test reliability, and make test suites more efficient.

Best Practices for Using storageState

To make the most of Playwright’s storageState and ensure efficient, stable, and secure test automation, follow these best practices:

  • Regenerate storageState Regularly: Ensure that storageState is refreshed periodically to avoid issues with expired session tokens or outdated data.
  • Use Separate storageState Files for Different User Roles: Capture and store different session states for various user roles (admin, user, guest) to test different workflows.
  • Exclude storageState from Version Control: Always add storageState files to .gitignore to prevent sensitive data from being exposed in version control.
  • Capture storageState After Logging In: Save the session state immediately after a successful login to reuse it in subsequent tests, reducing the need for repetitive login steps.
  • Use beforeAll for State Setup: Capture storageState in the beforeAll hook to set up the session once and reuse it across multiple tests, saving time during test execution.
  • Use storageState for Multi-Step Flows: Save and reuse storageState to maintain session continuity across different tests, especially for multi-step workflows like shopping carts or form submissions.
  • Clear storageState When Necessary: Use context.clearCookies() and context.clearLocalStorage() to reset the session when starting tests that require a fresh state.
  • Use Secure Storage for Sensitive Data: Protect sensitive session data by using encrypted storage or environment variables, and avoid exposing it in plain text.
  • Optimize storageState for CI/CD Pipelines: Store and reuse storageState in CI/CD pipelines to speed up test execution and eliminate the need for logging in repeatedly.
  • Keep storageState Files Small and Focused: Only capture relevant session data needed for your tests to keep storageState files manageable and easier to maintain.

Integrating storageState in Playwright Test Configuration

Integrating storageState in Playwright test configuration allows you to streamline your test setup by reusing authentication states across multiple tests, eliminating the need to log in every time. This integration is particularly useful in CI/CD environments, where consistent session handling is crucial for efficient test execution.

Steps to Integrate storageState in Playwright Test Configuration

1. Capture storageState

First, you need to capture the authentication state after performing the login process. You can do this manually in a test or as part of your setup:

const context = await browser.newContext();
const page = await context.newPage();

// Perform login
await page.goto(‘https://example.com/login’);
await page.fill(‘#username’, ‘user’);
await page.fill(‘#password’, ‘password’);
await page.click(‘#login-button’);

// Capture storage state
await context.storageState({ path: ‘authState.json’ });

2. Integrate storageState in playwright.config.ts

To use the saved storageState in your Playwright tests, configure it in the Playwright test configuration file (playwright.config.ts). This allows Playwright to automatically load the session state before each test, skipping the login process

3. Use storageState in Individual Tests (Optional)

If you want to load storageState for specific tests, you can configure it within the test itself. This allows more flexibility if certain tests require different session states.

4. Handling Multiple storageState Files for Different Roles

If you need to test multiple roles (e.g., admin, user, guest), you can create separate storageState files for each role and load the appropriate one in your configuration or individual tests.

By integrating storageState in the Playwright test configuration, you can efficiently reuse authentication sessions, reducing test execution time and improving the stability of your tests.

This approach is especially useful for large test suites that require multiple test scenarios involving different user roles or persistent sessions.

Common Pitfalls and Troubleshooting

While using storageState in Playwright can significantly improve the efficiency of your tests, there are some common pitfalls that may arise. Here’s a guide to help troubleshoot and resolve these issues:

1. Stale or Expired storageState

  • Problem: Session data in storageState may become stale or expired, especially when dealing with session cookies or tokens that have limited lifetimes.
  • Solution: Regularly regenerate the storageState file, especially when working with applications that have frequent session expiration. Ensure that the state file is updated when the session data changes.

2. Missing or Incorrectly Captured Session Data

  • Problem: Not all session data may be captured in storageState, particularly if dynamic storage mechanisms like sessionStorage or IndexedDB are used.
  • Solution: Verify that all relevant session data is included in the captured storageState. Playwright captures cookies, localStorage, and optionally IndexedDB by default. If additional session data is needed, ensure it is properly handled.

3. Conflicting or Overwritten State Files

  • Problem: If multiple tests are sharing the same storageState file or overwriting it, tests may fail due to inconsistent session states.
  • Solution: Use separate storageState files for different test scenarios or user roles. Ensure that each test has its own dedicated state file, especially when testing different user flows.

4. Incompatible Browsers or Contexts

  • Problem: Trying to use a storageState captured in one browser or context (e.g., Chromium) in another (e.g., Firefox or WebKit) can lead to inconsistencies or failures because each browser handles storage differently.
  • Solution: Ensure you are using storageState files only within the context of the same browser or create separate state files for different browsers. Do not mix state files between browsers with different storage implementations.

5. Invalid or Missing Session Data After Switching Contexts

  • Problem: When switching between multiple browser contexts or users, the session data may not persist as expected, leading to issues like authentication failures.
  • Solution: Make sure to create separate contexts for different users or roles, as each context has its own session and cookies. Ensure the correct storageState is loaded for each context.

6. storageState File Not Being Loaded Properly

  • Problem: Playwright may fail to load the storageState file properly, resulting in session-related errors or login issues.
  • Solution: Double-check the path to the storageState file and ensure it is correctly referenced in your test configuration or code. Verify that the file exists and is readable by Playwright.

7. Issues with Dynamic Web Applications

  • Problem: Web applications that rely on dynamic content or JavaScript for session management may experience issues with storageState because the session state may change frequently.
  • Solution: Ensure that you capture the storageState after all necessary JavaScript has executed, and the session is fully initialized. Use Playwright’s waiting mechanisms to ensure the page is fully loaded before capturing the state.

8. Session Conflicts Between Tests

  • Problem: Running tests that share the same session or storageState file may lead to conflicts, especially if multiple tests modify the session concurrently.
  • Solution: Use isolated sessions by either using separate storageState files for each test or clearing the session data between tests to prevent conflicts. Use Playwright’s context.clearCookies() and context.clearLocalStorage() to reset the session as needed.

Scale Your Playwright Testing with BrowserStack Automate

BrowserStack Automate provides a robust cloud infrastructure to run your Playwright tests at scale across thousands of real desktop and mobile browsers without the hassle of managing your own devices or environments. With support for parallel test execution, you can run hundreds of tests concurrently to drastically reduce your test suite’s runtime.

Key benefits include:

  • Extensive Device and Browser Coverage: Test on over 3,500 real browsers and devices, ensuring accurate cross-platform validation.
  • Seamless CI/CD Integration: Easily integrate with popular CI/CD tools like Jenkins, GitHub Actions, and GitLab for continuous testing workflows.
  • AI-Powered Self-Healing: Automatic detection and real-time fixing of flaky or broken locators to maintain stable test suites.
  • Comprehensive Debugging: Access video recordings, console logs, network requests, and Playwright Trace Viewer logs from a unified dashboard for fast root-cause analysis.
  • Local Testing Support: Securely test internal or locally hosted applications through BrowserStack’s Local Testing feature.
  • Configurable Environments: Specify browser versions, screen resolutions, OS platforms, and other parameters to match your target user environments.

By leveraging BrowserStack Automate, teams can accelerate Playwright test execution, gain confidence in cross-browser compatibility, and free themselves from infrastructure overheads, enabling faster delivery of high-quality applications.

Talk to Expert

Conclusion

Playwright’s storageState is a powerful feature that streamlines test automation by capturing and reusing session data, such as cookies and localStorage, across multiple tests. This improves test efficiency, reduces redundancy, and ensures consistent authentication states.

By following best practices and integrating storageState into your test configuration, you can speed up test execution and enhance reliability. Combined with tools like BrowserStack Automate, Playwright testing can be scaled effortlessly across different browsers and real devices, ensuring comprehensive and efficient test coverage.

Try BrowserStack Now

Useful Resources for Playwright

Tool Comparisons:

Tags
Automation Testing Real Device Cloud Website Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord