Working with Local Storage in Playwright

On This Page What is Local Storage?Accessing Local Storage in Pl

March 29, 2026 · 9 min read · Tool Comparison

Working with Local Storage in Playwright

In, contend Local Storage is essential for simulating user sessions, store user preferences, and testing different scenarios without the need for repetitive setup.

Overview

Local Storage is a knock-down feature in web coating, permit lasting datum 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 accession Local Storage data in the browser context.

const localStorageData = await page.evaluate (() = & gt; localStorage.getItem (& # 8216; key & # 8217;));

2. Setting Data in Local Storage:Set key-value duad use page.evaluate () to simulate user data or predilection.
await page.evaluate (() = & gt; localStorage.setItem (& # 8216; key & # 8217;, & # 8216; value & # 8217;));
3. Modifying Data in Local Storage:Update existing data in Local Storage by setting new value for the same key.

await page.evaluate (() = & gt; localStorage.setItem (& # 8216; key & # 8217;, & # 8216; newValue & # 8217;));

4. Removing Data from Local Storage:Use removeItem () to edit specific key or clear () to take all data.
await page.evaluate (() = & gt; localStorage.removeItem (& # 8216; key & # 8217;));

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: & # 8216; state.json & # 8217;});

This article explores how to interact with Local Storage in Playwright, covering how to access, set, qualify, and recycle Local Storage data efficaciously to streamline your automated examine workflow.

What is Local Storage?

Local Storage is a web storage mechanics that grant websites to store data persistently on a user & # 8217; s browser. It is portion of the Web Storage API and supply a way to save key-value pairs on the client side, without an expiration date, meaning the datum remains even after the browser is closed or the device is restart.

Key Features of Local Storage:

  • Persistent Storage:Unlike biscuit, data stored in Local Storage does not expire and is retained until explicitly blue-pencil.
  • Large Storage Capacity:Typically permit storage of up to 5MB of data per source, lots larger than cookies.
  • Client-Side:Data is stored on the user & # 8217; s browser, reducing waiter load and enhancing performance for sure operations.
  • Key-Value Pair Storage:Data is stored as simple key-value pairs, where both keys and value are strings.

Local Storage is wide used in modern for handling persistent client-side data, make it a valuable tool for quiz and automate scenario like user sessions and preferences in Playwright.

Accessing Local Storage in Playwright

Accessing Local Storage in Playwright is typically perform using the page.evaluate () method, which allows you to run within the page & # 8217; s context. This is essential for retrieving store key-value pairs, validating datum, or apply 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 recover all key-value twain by retell over localStorage key and returning them as an object.

Example codification snippet

await page.goto (& # 8216; https: //example.com & # 8217;);

const localStorageData = await page.evaluate (() = & gt; {
let information = {};
for (let i = 0; i & lt; localStorage.length; i++) {
const key = localStorage.key (i);
datum [key] = localStorage.getItem (key);
}
homecoming data;
});

console.log (localStorageData);

This code fetches all Local Storage point as an object that can be inspected or used for assertions in tests.

Access Specific Local Storage Values

You can also now access individual keys:

const userRole = await page.evaluate (() = & gt; localStorage.getItem (& # 8216; userRole & # 8217;));
console.log (userRole); // e.g., & # 8216; admin & # 8217;

Important Notes

  • Ensure the mark page is amply laden before accessing Local Storage.
  • Accessing Local Storage this way allows testing of persistence mechanisms, user preferences, authentication token, and other critical stored data.
  • For preserve sessions, Playwright too proffer context.storageState () which captures Local Storage together with biscuit.

By leverage page.evaluate () to interact with Local Storage, Playwright enable powerful and flexible test scenario that require inspecting or validating client-side entrepot state. & # 8217; # 139;

Read More:

Setting Data in Local Storage

To set data in Local Storage during Playwright tests, you use the page.evaluate () method to accomplish JavaScript within the context of the webpage. This allow you to programmatically add or modify key-value pairs in the browser & # 8217; s Local Storage, which is essential for assume user settings, feature flags, or authentication tokens before or during test execution.

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

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 distinguish using localStorage.setItem (key, value).

Example

await page.goto (& # 8216; https: //example.com & # 8217;);

await page.evaluate (() = & gt; {
localStorage.setItem (& # 8216; theme & # 8217;, & # 8216; dark & # 8217;);
localStorage.setItem (& # 8216; isLoggedIn & # 8217;, & # 8216; true & # 8217;);
});

After setting these values, the page will behave as if the corresponding Local Storage datum was already present, enable trial to part from a specific state or bypass certain UI flows.

Setting Multiple Entries

You can set multiple items in one evaluate vociferation:

await page.evaluate (() = & gt; {
const datum = {
userToken: & # 8216; abc123xyz & # 8217;,
preferences: JSON.stringify ({newsletter: true}),
};
for (const [key, value] of Object.entries (data)) {
localStorage.setItem (key, value);
}
});

Read More:

Modifying and Removing Data from Local Storage

In Playwright, you can modify or remove data store in Local Storage using JavaScript through the page.evaluate () method. This allows you to simulate user demeanour, reset application state, or manipulate session data during trial.

Modifying Data in Local Storage

To qualify an be item in Local Storage, simply set the new value for the like key using localStorage.setItem (). This will overwrite the previous value for that key.

Example: Modifying a Local Storage item.

await page.evaluate (() = & gt; {
localStorage.setItem (& # 8216; user_token & # 8217;, & # 8216; new_token_value & # 8217;);
});

In this example, the user_token value is updated with a new token (new_token_value).

Removing Data from Local Storage

To take a specific item from Local Storage, use the localStorage.removeItem () method. If you want to take all datum from Local Storage, you can use localStorage.clear ().

Example: Removing a specific item from Local Storage.

await page.evaluate (() = & gt; {
localStorage.removeItem (& # 8216; user_token & # 8217;);
});

This removes the user_token from Local Storage.

Example: Clearing all data in Local Storage.

await page.evaluate (() = & gt; {
localStorage.clear ();
});

This clears all key-value pairs stored in Local Storage for the current domain.

Read More:

Saving and Reusing Local Storage State

In Playwright, salve and reusing Local Storage state is a potent way to persist session information (such as user preferences or authentication token) across multiple tryout runs. By saving the state, you can avoid the need for repetitive actions like logging in, hie up your exam 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 sole cookies but also Local Storage and IndexedDB datum. This method allows you to save the state to a file, which can then be reused in next test.

Example: Save Local Storage state to a file.

await context.storageState ({path: & # 8216; localStorageState.json & # 8217;});

This will relieve the Local Storage province (along with cooky and IndexedDB) into the localStorageState.json file.

How to Reuse Local Storage State

Once you receive saved the Local Storage province, you can reuse it in future tests by load the protected state into a new browser setting. This allows you to hop-skip login steps or other setup activeness, making your tests more efficient.

Example: Load saved Local Storage state.

const circumstance = await browser.newContext ({
storageState: & # 8216; localStorageState.json & # 8217; // Load the saved state
});

This loads the protected localStorageState.json file, conserve the Local Storage data, and permit 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 assist 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 information in Local Storage to bypass login steps across multiple tests, salvage time and improving efficiency.
  • Testing User Preferences:Use Local Storage to store and retrieve user-specific settings like subject, language, or layout penchant to validate personalized experiences.
  • Simulating Authenticated User Flows:Preserve Local Storage data to test features accessible only to logged-in user, such as dashboards or history management sections.
  • Maintaining Application State Across Tests:Reuse Local Storage to impart over province like cart items or organize progress between test steps, mimicking real user interaction.
  • Bypassing Intro or Consent Screens:Save Local Storage after dismissing cookie consent or onboarding modals to skip them in future trial and focus on core functionality.
  • Testing Role-Based Access:Store and reprocess different Local Storage states for various user roles (e.g., admin, user) to test admittance control and role-specific features.

Read More:

Best Practices for Working with Local Storage in Playwright

Following best practices ensures true, maintainable, and unafraid automation when handling Local Storage in Playwright:

  • Isolate Test Data:Use a refreshful browser context for each trial to prevent Local Storage datum from one tryout affecting another.
  • Reset Local Storage Before Each Test:Clear or reinitialize Local Storage at the start of every exam to maintain consistency and avoid flaky results.
  • Avoid Storing Sensitive Information:Do not store sensible data like passwords or personal information in Local Storage during tests, as it can be easily access through scripts.
  • Use storageStatefor Persistence:When tests demand coherent state (e.g., logged-in session), salvage and reuse Local Storage using Playwright & # 8217; s storageState ().
  • Validate Stored Data:Regularly verify that the correct data is being stored or retrieve to ensure coating logic is functioning as expected.
  • Simulate Real Scenarios:Set naturalistic key-value pairs that mirror how users interact with the app instead of habituate mock data that doesn & # 8217; t reflect actual behavior.
  • Keep Local Storage Domain-Specific:Ensure you & # 8217; re accessing or setting Local Storage only within the relevant domain to avoid cross-domain datum conflicts.

Scale Local Storage Testing with BrowserStack Automate

enables scaling your Local Storage screen with Playwright by providing cloud-based access to 1000 of real browsers and devices. This allows you to verify Local Storage demeanor consistently across different environments without local infrastructure direction.

Key Advantages for Local Storage Testing at Scale

  • and Coverage: Run examination on multiple browser edition and real devices simultaneously, ensuring Local Storage data handle works correctly everywhere.
  • Parallel Execution for Speed:Execute multiple Playwright tests that interact with Local Storage in analog, reducing overall test suite runtime significantly.
  • Stable and Ordered Environments:Each test executes in isolated browser circumstance on BrowserStack & # 8217; s cloud, avoiding local imagination conflicts and ensuring a clean Local Storage state for each test scenario.
  • Integrated Testing: Automate Local Storage validation as part of your continuous integration pipeline, triggered on every codification change, with resolution captured in BrowserStack & # 8217; s actionable fascia.
  • Debugging and Analysis Tools:Access video recordings, console logs, and network captures alongside Playwright suggestion information to diagnose Local Storage issues more effectively.

Talk to an Expert

Conclusion

Working with Local Storage in Playwright ply potent control over client-side data, enable 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 stairs. When unite with BrowserStack Automate, these capabilities scale effortlessly across real browsers and device, insure reliable, high-coverage testing for modern web applications.

Useful Resources for Playwright

Tool Comparisons:

Tags
7,000+ Views

# Ask-and-Contributeabout this theme with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free