In Playwright, managing Local Storage is essential for simulating user sessions, storing user preferences, and testing different scenarios without the need for repetitive setup.
Overview
Local Storage is a powerful feature in web applications, allowing persistent data storage on the client-side.
Key Ways to Interact with Local Storage in Playwright
1. Accessing Local Storage: Use page.evaluate() to run JavaScript and access Local Storage data in the browser context.
const localStorageData = await page.evaluate(() => localStorage.getItem(‘key’));
2. Setting Data in Local Storage: Set key-value pairs using page.evaluate() to simulate user data or preferences.
await page.evaluate(() => localStorage.setItem(‘key’, ‘value’));3. Modifying Data in Local Storage: Update existing data in Local Storage by setting new values for the same key.
await page.evaluate(() => localStorage.setItem(‘key’, ‘newValue’));
4. Removing Data from Local Storage: Use removeItem() to delete specific keys or clear() to remove all data.
await page.evaluate(() => localStorage.removeItem(‘key’));
5. Saving Local Storage State: Use context.storageState() to save the current Local Storage state and reuse it in future tests.
await context.storageState({ path: ‘state.json’ });
This article explores how to interact with Local Storage in Playwright, covering how to access, set, modify, and reuse Local Storage data effectively to streamline your automated testing workflow.
What is Local Storage?
Local Storage is a web storage mechanism that allows websites to store data persistently on a user’s browser. It is part of the Web Storage API and provides a way to save key-value pairs on the client side, without an expiration date, meaning the data remains even after the browser is closed or the device is restarted.
Key Features of Local Storage:
- Persistent Storage: Unlike cookies, data stored in Local Storage does not expire and is retained until explicitly deleted.
- Large Storage Capacity: Typically allows storage of up to 5MB of data per origin, much larger than cookies.
- Client-Side: Data is stored on the user’s browser, reducing server load and enhancing performance for certain operations.
- Key-Value Pair Storage: Data is stored as simple key-value pairs, where both keys and values are strings.
Local Storage is widely used in modern web applications for handling persistent client-side data, making it a valuable tool for testing and automating scenarios like user sessions and preferences in Playwright.
Accessing Local Storage in Playwright
Accessing Local Storage in Playwright is typically done using the page.evaluate() method, which allows you to run JavaScript within the page’s context. This is essential for retrieving stored key-value pairs, validating data, or using Local Storage values to drive test logic.
How to Access Local Storage
- Navigate to the target page using page.goto().
- Use page.evaluate() to execute JavaScript that reads the Local Storage items.
- You can retrieve all key-value pairs by iterating over localStorage keys and returning them as an object.
Example code snippet
await page.goto(‘https://example.com’);const localStorageData = await page.evaluate(() => {
let data = {};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
data[key] = localStorage.getItem(key);
}
return data;
});console.log(localStorageData);
This code fetches all Local Storage items as an object that can be inspected or used for assertions in tests.
Access Specific Local Storage Values
You can also directly access individual keys:
const userRole = await page.evaluate(() => localStorage.getItem(‘userRole’));
console.log(userRole); // e.g., ‘admin’
Important Notes
- Ensure the target page is fully loaded before accessing Local Storage.
- Accessing Local Storage this way allows testing of persistence mechanisms, user preferences, authentication tokens, and other critical stored data.
- For saving sessions, Playwright also offers context.storageState() which captures Local Storage together with cookies.
By leveraging page.evaluate() to interact with Local Storage, Playwright enables powerful and flexible test scenarios that require inspecting or validating client-side storage state.’#139;
Setting Data in Local Storage
To set data in Local Storage during Playwright tests, you use the page.evaluate() method to execute JavaScript within the context of the webpage. This allows you to programmatically add or modify key-value pairs in the browser’s Local Storage, which is essential for simulating user settings, feature flags, or authentication tokens before or during test execution.
How to Set Local Storage Data
- Navigate to the target page or use a blank page if needed.
- Execute JavaScript with page.evaluate() to set Local Storage keys using localStorage.setItem(key, value).
Example
await page.goto(‘https://example.com’);await page.evaluate(() => {
localStorage.setItem(‘theme’, ‘dark’);
localStorage.setItem(‘isLoggedIn’, ‘true’);
});
After setting these values, the page will behave as if the corresponding Local Storage data was already present, enabling tests to start from a specific state or bypass certain UI flows.
Setting Multiple Entries
You can set multiple items in one evaluate call:
await page.evaluate(() => {
const data = {
userToken: ‘abc123xyz’,
preferences: JSON.stringify({ newsletter: true }),
};
for (const [key, value] of Object.entries(data)) {
localStorage.setItem(key, value);
}
});Read More: Web Scraping with Playwright
Modifying and Removing Data from Local Storage
In Playwright, you can modify or remove data stored in Local Storage using JavaScript through the page.evaluate() method. This allows you to simulate user behavior, reset application states, or manipulate session data during tests.
Modifying Data in Local Storage
To modify an existing item in Local Storage, simply set the new value for the same key using localStorage.setItem(). This will overwrite the previous value for that key.
Example: Modifying a Local Storage item.
await page.evaluate(() => {
localStorage.setItem(‘user_token’, ‘new_token_value’);
});In this example, the user_token value is updated with a new token (new_token_value).
Removing Data from Local Storage
To remove a specific item from Local Storage, use the localStorage.removeItem() method. If you want to remove all data from Local Storage, you can use localStorage.clear().
Example: Removing a specific item from Local Storage.
await page.evaluate(() => {
localStorage.removeItem(‘user_token’);
});This removes the user_token from Local Storage.
Example: Clearing all data in Local Storage.
await page.evaluate(() => {
localStorage.clear();
});This clears all key-value pairs stored in Local Storage for the current domain.
Read More: Playwright Test Report: Comprehensive Guide
Saving and Reusing Local Storage State
In Playwright, saving and reusing Local Storage state is a powerful way to persist session data (such as user preferences or authentication tokens) across multiple test runs. By saving the state, you can avoid the need for repetitive actions like logging in, speeding up your tests and improving overall efficiency.
How to Save Local Storage State
To save the current Local Storage state, you can use the context.storageState() method, which captures not only cookies but also Local Storage and IndexedDB data. This method allows you to save the state to a file, which can then be reused in future tests.
Example: Save Local Storage state to a file.
await context.storageState({ path: ‘localStorageState.json’ });This will save the Local Storage state (along with cookies and IndexedDB) into the localStorageState.json file.
How to Reuse Local Storage State
Once you have saved the Local Storage state, you can reuse it in future tests by loading the saved state into a new browser context. This allows you to skip login steps or other setup actions, making your tests more efficient.
Example: Load saved Local Storage state.
const context = await browser.newContext({
storageState: ‘localStorageState.json’ // Load the saved state
});This loads the saved localStorageState.json file, preserving the Local Storage data, and allowing you to continue from the same session state as the previous test.
Use Cases for Local Storage in Playwright
Reusing and managing Local Storage in Playwright helps streamline automated testing by maintaining user states and simulating real-world scenarios. Here are some common use cases:
- Skipping Repetitive Logins: Store authentication tokens or session data in Local Storage to bypass login steps across multiple tests, saving time and improving efficiency.
- Testing User Preferences: Use Local Storage to store and retrieve user-specific settings like theme, language, or layout preferences to validate personalized experiences.
- Simulating Authenticated User Flows: Preserve Local Storage data to test features accessible only to logged-in users, such as dashboards or account management sections.
- Maintaining Application State Across Tests: Reuse Local Storage to carry over states like cart items or form progress between test steps, mimicking real user interactions.
- Bypassing Intro or Consent Screens: Save Local Storage after dismissing cookie consent or onboarding modals to skip them in future tests and focus on core functionality.
- Testing Role-Based Access: Store and reuse different Local Storage states for various user roles (e.g., admin, user) to test access control and role-specific features.
Best Practices for Working with Local Storage in Playwright
Following best practices ensures reliable, maintainable, and secure automation when handling Local Storage in Playwright:
- Isolate Test Data: Use a fresh browser context for each test to prevent Local Storage data from one test affecting another.
- Reset Local Storage Before Each Test: Clear or reinitialize Local Storage at the start of every test to maintain consistency and avoid flaky results.
- Avoid Storing Sensitive Information: Do not store sensitive data like passwords or personal information in Local Storage during tests, as it can be easily accessed through scripts.
- Use storageState for Persistence: When tests require consistent state (e.g., logged-in sessions), save and reuse Local Storage using Playwright’s storageState().
- Validate Stored Data: Regularly verify that the correct data is being stored or retrieved to ensure application logic is functioning as expected.
- Simulate Real Scenarios: Set realistic key-value pairs that mirror how users interact with the app instead of using mock data that doesn’t reflect actual behavior.
- Keep Local Storage Domain-Specific: Ensure you’re accessing or setting Local Storage only within the relevant domain to avoid cross-domain data conflicts.
Scale Local Storage Testing with BrowserStack Automate
BrowserStack Automate enables scaling your Local Storage testing with Playwright by providing cloud-based access to thousands of real browsers and devices. This allows you to verify Local Storage behavior consistently across different environments without local infrastructure management.
Key Advantages for Local Storage Testing at Scale
- Cross-Browser and Cross-Device Coverage: Run tests on multiple browser versions and real devices simultaneously, ensuring Local Storage data handling works correctly everywhere.
- Parallel Execution for Speed: Execute multiple Playwright tests that interact with Local Storage in parallel, reducing overall test suite runtime significantly.
- Stable and Consistent Environments: Each test executes in isolated browser contexts on BrowserStack’s cloud, avoiding local resource conflicts and ensuring a clean Local Storage state for each test scenario.
- Integrated CI/CD Testing: Automate Local Storage validation as part of your continuous integration pipeline, triggered on every code change, with results captured in BrowserStack’s actionable dashboards.
- Debugging and Analysis Tools: Access video recordings, console logs, and network captures alongside Playwright trace data to diagnose Local Storage issues more effectively.
Conclusion
Working with Local Storage in Playwright provides powerful control over client-side data, enabling you to simulate real-world user sessions, preserve application states, and test personalized user experiences efficiently.
By accessing, modifying, and reusing Local Storage, you can streamline test execution and reduce redundant setup steps. When combined with BrowserStack Automate, these capabilities scale effortlessly across real browsers and devices, ensuring reliable, high-coverage testing for modern web applications.
Useful Resources for Playwright
- Playwright Automation Framework
- Playwright Java Tutorial
- Playwright Python tutorial
- Playwright Debugging
- End to End Testing using Playwright
- Visual Regression Testing Using Playwright
- Mastering End-to-End Testing with Playwright and Docker
- Page Object Model in Playwright
- Scroll to Element in Playwright
- Understanding Playwright Assertions
- Cross Browser Testing using Playwright
- Playwright Selectors
- Playwright and Cucumber Automation
Tool Comparisons:




