How To Manage Cookies Using Playwright in 2026 For Test Efficiency

Master cookie management in Playwright to improve test efficiency by setting, modifying, and reusing cookie states across your test scenarios.

Written by Bhumika Babbar Bhumika Babbar
Reviewed by Sourabh G Sourabh G
Last updated: 29 July 2026 18 min read

Key Takeaways

  • Cookies store session and login data in the browser; Playwright manages them at the context level, keeping each test isolated.
  • They come in three types, session, persistent, and third-party, each determining how you set, save, or inspect them in a test.
  • storageState() lets you save a login once and reuse it everywhere, cutting repeated logins; just refresh it regularly and keep it out of version control.

Whenever you run test suites, you are stuck with multiple logins, declaring and redeclaring user authentication and fetching backend data, again and again.

Running thousands of test suites and cross-verifying every tiny detail leads to flaky tests, faulty CI runs, or prolonged test timeouts.

Cookie management in Playwright solves this by letting you debug your test cases faster, skip login flows, and run parallel tests for browser sessions without inviting any code leakage.

Let’s learn more about how to manage cookies, from retrieving and setting to saving and reusing them.

Why Is Cookie Management Is a Testing Problem, Not Just a Browser Feature

Cookies are small pieces of data stored by a web browser that are used to remember information about a user’s interactions with a website.

They are essential for maintaining user sessions, storing preferences, and enabling features like personalised content, authentication, and tracking.

Every time a test can’t reuse a session, it reruns code: one more login flow, one more wait for a redirect, one more place where a slow network call turns a 3-second test into a 12-second one. Running multiple tests across hundreds of specs can delay execution cycles.

Once a suite grows past a dozen tests, it creates disruption for your CI pipeline. It can also leak cookies; one cookie can silently answer another test’s request.

That’s why Playwright helps you inject cookies into a test suite or test case directly. You don’t need to log in again and again, which can bring efficiency for your QA teams.

What Are the Types of Cookies?

Below are the different types of cookies you can inject into your test suite:

  • Session Cookies: Temporary cookies that are erased when the browser is closed. They are typically used for maintaining session information while a user navigates a website.
  • Persistent Cookies: These cookies remain on the user’s device after the browser is closed and are used for storing user preferences or authentication information for subsequent visits.
  • Third-Party Cookies: Set by domains other than the one the user is currently visiting. These are often used for tracking and targeted advertising.

How Playwright Handles Cookies Differently

In Playwright, cookies are used in browser context, not on the webpage you are UI testing on.

Browser context is an isolated, incognito-like session. Every context you create gets its own local storage, browser instance, session, and authentication state.

This means that two tests cannot leak cookies into each other. Users can also open multiple authentication sessions at once, no matter from where they’re being redirected. Like an admin or a guest user can log in side by side without deploying separate browser instances.

This is a meaningfully different feature that lets you manage cookies on a browser level rather than a page level, where isolation is handled manually. By providing context-level automation, QA teams can ensure that sessions and user preferences are maintained across multiple test steps, reducing test flakiness and improving reliability.

// Every cookie operation is scoped to the browser context, not the page


const context = await browser. newContext();

const page = await context. newPage();

Understanding and managing cookies effectively in Playwright is crucial for testing authenticated workflows, user sessions, and personalised features, making it a key component of any automated test strategy.

Cookie APIs in Playwright

Playwright provides a set of robust cookie management APIs through the browser context object, allowing you to programmatically get, set and delete and clear cookies within the browser context.

Before you set or reuse anything, you usually need to see what’s actually stored in the browser. Especially when you’re debugging why a login didn’t go through, or confirming an authentication cookie was issued correctly after a form submission.

1. context.cookies (urls?)

Retrieves an array of cookies for the current browser context. If URLs are specified, it returns only cookies relevant to those URLs. This is useful for inspecting existing cookies for debugging or conditional logic.

const allCookies = await context. cookies();

console.log(allCookies);

const scopedCookies = await context. cookies('https://app.example.com');

const multiSiteCookies = await context. cookies([

  'https://app.example.com',

  'https://auth.example.com'

]);

const sessionCookie = allCookies.find(c => c.name === 'session_id');

console.log(sessionCookie);

Array of cookies for the current browser context Terminal

Array of cookies for the current browser context Localhost

2. context. addCookies (cookies): Adds one or more cookies to the browser context. Each cookie object typically requires properties such as name, value, and either url or domain/path. This method is essential for setting session tokens or simulating logged-in states before navigation.

await context. addCookies([

  {

    name: 'user_token',

    value: 'abcd1234',

    domain: 'example.com',

    path: '/',

    httpOnly: true,

    secure: true,

    expires: Math.floor(Date.now() / 1000) + 3600 // 1 hour from now

  }

]);

Modifying a cookie means re-adding it. Playwright doesn’t have a separate “update” method. If you call addCookies() again with the same name, domain and path, it overwrites the existing cookie’s value:

// "Modifying" a cookie is just re-adding it with new values

await context. addCookies([

  {

    name: 'user_token',

    value: 'newtoken5678',

    domain: 'example.com',

    path: '/',

    expires: Math.floor(Date.now() / 1000) + 7200

  }

]);

Adding and modifying cookies to the browser context Terminal

Adding and modifying cookies to the browser context Localhost

3. context. clearCookies(): Clears all cookies in the current browser context, helping to reset session state between tests or scenarios.

There’s no dedicated deleteCookie() method in Playwright. Deletion is handled one of two ways, depending on what you need.

To remove one specific cookie, overwrite it with an immediate expiry:

await context. addCookies([

  {

    name: 'user_token',

    value: '',

    domain: 'example.com',

    path: '/',

    expires: 0 // expires immediately

  }

]);

To wipe everything in the context, use clearCookies(). It is the more common choice between tests, since it guarantees a clean slate:

await context. clearCookies();

Deleting and clearing cookies to the browser context Terminal

Deleting and clearing cookies to the browser context Localhost

If your suite has ever failed only on a re-run or only when run after a specific other test cycle, an uncleared cookie is usually the cause.

4.  storageState(): Skipping Logins at Scale

context. StorageState() captures the entire session, cookies, local storage, and IndexedDB and writes it to a file. Load that file into a new context later, and you land on the page already authenticated, no login form in sight.

Saving it, typically done once, after a real login:

await context. storageState({ path: 'authState.json' });

Reusing it in every test after that:

const context = await browser. newContext({

  storageState: 'authState.json' // starts already authenticated

});

storageState Skipping Logins at Scale Terminal

storageState Skipping Logins at Scale Localhost

Playwright’s cookie APIs operate at the browser context level, which isolates cookie storage per context, important for running parallel tests without session collision.

This set of cookie APIs makes Playwright highly flexible for managing browser states and simulating user sessions programmatically during automated testing.

How to Get and Inspect Cookies

In Playwright, you can easily retrieve and inspect cookies using the context.cookies() method. This allows you to examine session data, authentication tokens, and other cookie-based information in your automated tests.

Steps to Get and Inspect Cookies in Playwright:

1. Get All Cookies for a Domain

Use context.cookies() to retrieve cookies for a specific domain or page.

const cookies = await context.cookies(‘https://example.com’);
console.log(cookies); // Logs an array of cookies

2. Inspect Specific Cookies

After retrieving the cookies, you can filter or inspect them based on properties such as name, value, domain, and expires.

const cookies = await context.cookies(‘https://example.com’);
const sessionCookie = cookies.find(cookie => cookie.name === ‘session_id’);
console.log(sessionCookie); // Logs the session cookie

3. Get Cookies for the Current Page

If no domain is specified, context.cookies() retrieves all cookies for the current page.

const cookies = await context.cookies();
console.log(cookies); // Logs cookies for the current page

Why Inspect Cookies?

  • Authentication Validation: Verify if the authentication cookies (e.g., session or JWT) are set correctly after login.
  • Session Management: Ensure session data is being stored and sent correctly for persistent sessions.
  • Testing Features: Check cookies set for user preferences, cart data, or other features dependent on cookies.

Using these methods, you can easily retrieve and inspect cookies, enabling better control over session data during automated testing with Playwright.

Setting and Modifying Cookies

Playwright allows you to set and modify cookies in a browser context using the context.addCookies() method. This enables you to programmatically add new cookies or update existing ones before navigating to a page, which is useful for simulating authenticated sessions or controlling user preferences during tests.

How to Set Cookies

To set cookies, use context.addCookies() with an array of cookie objects. Each cookie object must include essential fields like name, value, and either domain or path. Additionally, you can specify attributes like httpOnly, secure, sameSite, and expires to mimic real browser behavior.

Example:

await context.addCookies([{
name: ‘user_token’,
value: ‘abcd1234’,
domain: ‘example.com’,
path: ‘/’,
httpOnly: true,
secure: true,
expires: Math.floor(Date.now() / 1000) + 3600 // Expires in 1 hour
}]);

How to Modify Cookies

To modify an existing cookie, re-add it with the same name, domain, and path, but with updated values. Playwright treats adding a cookie with the same identifying attributes as replacing the existing one, allowing you to change values like authentication tokens, expiration times, or flags.

Example of modifying a cookie’s value:

await context.addCookies([{
name: ‘user_token’,
value: ‘newtoken5678’,
domain: ‘example.com’,
path: ‘/’,
httpOnly: true,
secure: true,
expires: Math.floor(Date.now() / 1000) + 7200 // Expires in 2 hours
}]);

Deleting and Clearing Cookies

Playwright provides straightforward methods to delete specific cookies or clear all cookies in the current browser context, helping maintain test isolation and reset session states effectively.

Deleting Specific Cookies

Playwright does not have a dedicated deleteCookies() method but deleting a cookie is done by overwriting it with an expired date or by clearing the whole context.

To delete a specific cookie, you typically set the same cookie with an expired timestamp or use context.clearCookies() to remove all. Another way is to overwrite the cookie with an empty value and past expiration to invalidate it.

Example of deleting a specific cookie by expiring it:

await context.addCookies([{
name: ‘user_token’,
value: ”,
domain: ‘example.com’,
path: ‘/’,
expires: 0 // Set to expire immediately
}]);

Clearing All Cookies

Use context.clearCookies() to remove all cookies from the current browser context. This is useful to start tests with a clean slate by clearing any stored session or tracking cookies.

Example

await context.clearCookies();

Saving and Reusing Cookie State

In Playwright, saving and reusing the cookie state allows you to preserve session data (such as cookies, localStorage, and IndexedDB) across different test runs. This is particularly useful for avoiding repetitive logins and ensuring tests start from a consistent state, saving valuable time in automated testing.

Saving Cookie State

To save the cookie state, use the context.storageState() method, which captures all cookies, localStorage, and IndexedDB from the current browser context and stores them in a file. This enables you to reuse the session in future tests without needing to log in again.

Example

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

This saves the current browser context’s session data to authState.json, including cookies and localStorage data.

Reusing Cookie State

To reuse the saved cookie state in subsequent tests, you can load the storageState file into a new browser context using the storageState option. This allows you to continue from where the last test left off, preserving cookies and authentication state.

Example

const context = await browser.newContext({
storageState: ‘authState.json’ // Load saved cookie state
});

Real-World Scenarios Where storagestate() Actually Matters

Here is why storage state matters more than you think:

  • Skipping login on every spec. Log in once, save state, and reuse it across the entire suite, which is the single highest-benefit use of storageState().
  • Testing role-based access. Save an admin-state.json and a user-state.json separately, and load whichever one a given test needs without ever touching the login form for either role mid-suite.
  • Picking up mid-flow, not from the start. Preserve a session after checkout begins, or after a cart already has items in it, so a test can go straight to the step it’s actually validating.
  • Skipping cookie-consent banners. Interact with the consent pop-up once, save the resulting state, and every subsequent test starts past it. It saves you from repeatedly clicking “Accept” before the real test can begin.
  • Cross-browser and cross-device consistency checks. Reuse the same saved session across different browser projects to confirm a user stays logged in identically everywhere, which is exactly the kind of consistency that’s hardest to verify without running on real browsers and devices rather than emulators alone.

What Breaks When Cookies Aren’t Managed Properly

If you do not set cookies properly, you won’t just get an error message or “cookie not found”. Left unmanaged, cookies tend to cause the following:

  • Order-dependent failures. A test passes in isolation but fails in the full suite because an earlier test’s leftover cookie changed the starting state.
  • False positives. A test “passes” only because a stale session from a previous run masked a genuine authentication bug, the kind of failure that slips straight through to production.
  • Bloated run times. Every test that re-walks a full login UI flow instead of reusing saved state adds real value, adding more minutes to your CI pipeline.
  • Unsafe parallel runs. Shared or leaking cookie state across concurrent workers produces race conditions that have nothing to do with the feature under test and everything to do with test architecture.
  • Security exposure in CI. Saved state files with live tokens, committed to a repo or logged in plaintext, are a real and avoidable risk.
  • Silent staleness. A storagestage() file generated weeks ago quietly expires, and the failures that follow look like application bugs instead of what they actually are.

None of this is really a “cookie problem”; it’s a test-reliability problem that happens to be caused by cookies.

This is exactly why it’s worth treating cookie handling as part of your test architecture, not later when you compile the test code

Best Practices for Cookie Management in Playwright

Effective cookie management in Playwright ensures reliable, secure, and maintainable automated tests. Following these best practices helps avoid common pitfalls related to session handling, test flakiness, and environment consistency:

  • Use Separate Browser Contexts for Isolation: Create a new BrowserContext for each test or user session to isolate cookies and storage, preventing cross-test contamination and enabling parallel execution safely.
  • Set Cookies Before Navigation: When simulating authenticated states, set cookies early using context.addCookies() before navigating to the page. This avoids unnecessary login steps and speeds up tests.
  • Persist and Reuse Storage State Thoughtfully: Save cookies and localStorage to a state file with context.storageState() and reuse it to maintain session continuity across tests. Regularly refresh saved states to avoid stale or expired cookies.
  • Clear Cookies Between Tests: Use context.clearCookies() to reset session cookies, ensuring a clean slate when test isolation or repeatability is critical.
  • Handle Cookie Attributes Correctly: Accurately set flags like httpOnly, secure, sameSite, and expiration times to mimic real-world cookie behavior and avoid unexpected test results.
  • Validate Cookies Explicitly: Retrieve and inspect cookies using context.cookies() to verify test preconditions or assert post-conditions, improving test robustness.
  • Manage Cookies for Multiple Domains: When working with sites spanning multiple domains, carefully scope cookies by domain and path to reflect realistic scenarios and avoid conflicts.
  • Securely Manage Cookie Data: Treat saved cookie state files as sensitive data, especially when they contain authentication tokens.
  • Use Error Handling for Cookie Operations: Wrap cookie manipulations in try-catch blocks to handle unexpected browser behaviors or restrictions gracefully.
  • Test in Both Headed and Headless Modes: Validate cookie behavior consistently in different Playwright run modes to catch environment-specific issues.

Scale Your Playwright Testing with BrowserStack Automate

BrowserStack Automate offers a powerful cloud-based platform to scale Playwright test automation effortlessly across thousands of real browsers and mobile devices. It removes the complexities of managing infrastructure, enabling teams to accelerate test execution, increase coverage, and improve reliability at scale.

Key Benefits of Using BrowserStack Automate with Playwright:

  • Extensive Device and Browser Coverage: Run Playwright tests on 3,500+ real desktop and mobile browsers, including the industry-first support for real iOS devices, Android phones, and tablets to eliminate emulator gaps.
  • High-Scale Parallel Testing: Execute hundreds to thousands of tests concurrently, reducing test suite runtime by 10x or more without local resource constraints or custom scaling logic.
  • Seamless CI/CD Integration: Integrate effortlessly with popular CI/CD tools like Jenkins, GitHub Actions, GitLab, and CircleCI, enabling automated test runs as part of your deployment pipelines.
  • Comprehensive Debugging and Analytics: Access rich logs, video recordings, console outputs, network traces, and Playwright Trace Viewer data from a single dashboard for faster root cause analysis and debugging.
  • AI-Powered Self-Healing: BrowserStack’s smart AI agent automatically detects and heals broken locators during test runs, dramatically reducing flaky tests and maintenance overhead.

Conclusion

Cookie management in Playwright isn’t really about learning four API methods; it’s about deciding how much of your suite’s runtime and reliability you’re willing to spend re-authenticating instead of testing.

Context-level isolation, StorageState() reuse, and an auto-clearing of state turn long, flaky tests into fast and scalable tests. And a habit of clearing state deliberately is what turns a login-heavy, flaky suite into one that runs fast.

Integrating BrowserStack Automate with Playwright further enhances your testing capabilities by enabling cross-browser testing and scaling tests across real devices, ensuring comprehensive test coverage.

Useful Resources for Playwright

Tool Comparisons:

Version History

  1. Jul 29, 2026 Current Version

    Updated 3 sections, added more context and clarity about storage state, edited intro and conclusion

    Sourabh G
    Reviewed by Sourabh G Senior Software Engineer
Tags
Automation Testing Real Device Cloud Website Testing
Bhumika Babbar
Bhumika Babbar

Principal Engineer

Bhumika Babbar is a Principal Engineer for BrowserStack Automate with 15+ years of experience in test automation, quality engineering, and software testing. She specializes in building scalable automation frameworks and driving quality initiatives that help engineering teams deliver reliable software faster.

FAQs

Whenever the underlying auth token’s lifetime is close to expiring, or on a fixed schedule in CI, whichever comes first. A silently expired saved state is one of the more common causes of mysterious, hard-to-diagnose test failures.

Yes, a storageState.json file isn’t browser-specific, so you can load it into Chromium, Firefox, or WebKit contexts alike, which is useful for confirming a session behaves consistently across engines.

By design. Each browser context in Playwright is isolated, so cookies set in one context never appear in another unless you explicitly load a shared storageState file into both.

There’s no dedicated delete method. Overwrite the cookie with the same name, domain and path but set ‘expires’ to 0 or use context. clearCookies() if removing everything that is acceptable.

No. It captures cookies, local storage, and IndexedDB, but deliberately excludes session storage, since that’s meant to be tab-scoped and short-lived. Apps that rely on session storage for auth need to re-seed it per context separately.

Automation Tests on Real Devices & Browsers
Seamlessly Run Automation Tests on 3500+ real Devices & Browsers