Managing Cookies using Playwright

On This Page Understanding Cookies and their ImportanceMarch 04, 2026 · 11 min read · Tool Comparison

Managing Cookies apply Playwright

Cookies play a all-important role in web coating by storing session data, user preferences, and certification info. In, cope cookies efficaciously is all-important for check accurate and efficient test execution.

Overview

Playwright provides a powerful API to manage cookies, allowing you to set, find, modify, and delete cookies during automated quiz. This ensures you can assume real user behavior and test hallmark, sessions, and user preferences efficaciously.

Key Methods for Cookie Management in Playwright

  • context.cookies ():Retrieves cookies for the current page or domain.
  • context.addCookies ():Adds one or more cookies to the browser context.
  • context.clearCookies ():Clears all cookies in the current context.
  • context.storageState ():Saves cookies along with localStorage and IndexedDB to a file.

Best Practices for Cookie Management in Playwright

  • Isolate Tests:Always use a new browser circumstance for each test to prevent biscuit leakage.
  • Clear Cookies Between Tests:Use clearCookies () to ensure clean state between examination.
  • Use Secure Cookies:Set httpOnly and fix flags for sensible cookies.
  • Persist Cookie State:Save and reuse cooky state to speed up tests by bypass login steps.
  • Handle Expiry:Regularly refresh cookie states to ensure sessions are up-to-date and valid.

This article research how to handle cookies in Playwright, from retrieving and setting them to saving and reusing cooky states, with better practices and real-world use cases to optimise your testing workflows.

Understanding Cookies and their Importance

Cookies are minor part of data store by a web browser that are employ to recall information about a user & # 8217; s interactions with a site. They are indispensable for maintaining user session, storing preferences, and enabling features like personalized message, authentication, and tracking.

Types of Cookies:

  • Session Cookies: Temporary cooky that are erase when the browser is close. They are typically used for maintaining session information while a user navigates a website.
  • Persistent Cookies: These cooky remain on the user & # 8217; s device after the browser is closed and are used for storing user preferences or assay-mark info for subsequent visits.
  • Third-Party Cookies: Set by domains other than the one the user is presently visiting. These are often used for tracking and targeted advertising.

Why Cookies Matter in Testing:

  • Authentication: Cookies often store certification tokens or session IDs, allowing users to stick lumber in between visit.
  • User State: Cookies are used to store user preferences, settings, or the contents of a shopping cart, ensuring a personalized experience.
  • Consistency in Testing: Managing cooky in automated trial ensures that sessions and user preferences are maintain across multiple test stairs, reducing test flakiness and improving reliability.

Understanding and managing cookies effectively in is crucial for authenticated workflows, user sessions, and personalized features, create it a key component of any automated.

Cookie APIs in Playwright

Playwright provides a robust set of cookie management APIs through the BrowserContext object, allowing you to programmatically get, set, delete, and clear biscuit within a browser setting. These APIs facilitate session management, authentication handling, and province tenacity in automated tests.

Key cookie-related methods in Playwright include:

  • context.cookies (urls?):Retrieves an array of cookies for the current browser circumstance. If URLs are specified, it returns alone cookies relevant to those URLs. This is useful for inspecting exist cookies for debugging or conditional logic.
  • context.addCookies (cookies):Adds one or more cookies to the browser setting. Each cookie object typically requires properties such as gens, value, and either url or domain/path. This method is essential for lay session item or simulating logged-in states before navigation.
  • context.clearCookies ():Clears all cooky in the current browser context, helping to readjust session state between tests or scenarios.
  • context.deleteCookies (cooky):Deletes specific cookies base on their attributes like gens, demesne, or path.
  • context.storageState ():Exports the storage state, including biscuit and local entrepot, allowing session persistence by salvage the state to platter and afterward loading it in a new browser circumstance.

Playwright & # 8217; s cookie APIs operate at the browser context level, which isolates cookie entrepot per context, significant for running parallel tests without session collision.

Example usages:

// Get all cookies
const cookies = await context.cookies ();

// Set a cookie
await context.addCookies ([{
name: & # 8216; session_id & # 8217;,
value: & # 8216; abc123 & # 8217;,
domain: & # 8216; example.com & # 8217;,
path: & # 8216; / & # 8217;,
httpOnly: true,
secure: true,
}]);

// Clear all cookies
await context.clearCookies ();

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

Read More:

How to Get and Inspect Cookies

In Playwright, you can easily regain and inspect cooky using the context.cookies () method. This allows you to examine session data, hallmark token, and former 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 area or page.

const cookies = await context.cookies (& # 8216; https: //example.com & # 8217;);
console.log (cookies); // Logs an raiment of cookie

2. Inspect Specific Cookies

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

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

const cookies = await context.cookies (& # 8216; https: //example.com & # 8217;);
const sessionCookie = cookies.find (cookie = & gt; cookie.name === & # 8216; session_id & # 8217;);
console.log (sessionCookie); // Logs the session cookie

3. Get Cookies for the Current Page

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

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

Why Inspect Cookies?

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

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

Read More:

Setting and Modifying Cookies

Playwright let you to set and modify cookies in a browser setting expend the context.addCookies () method. This enable you to programmatically add new cooky or update live single before navigating to a page, which is useful for model authenticated sessions or check user preferences during trial.

How to Set Cookies

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

Example:

await context.addCookies ([{
gens: & # 8216; user_token & # 8217;,
value: & # 8216; abcd1234 & # 8217;,
orbit: & # 8216; example.com & # 8217;,
path: & # 8216; / & # 8217;,
httpOnly: true,
secure: true,
expires: Math.floor (Date.now () / 1000) + 3600 // Expires in 1 hr
}]);

How to Modify Cookies

To modify an existing biscuit, re-add it with the like name, area, and path, but with updated values. Playwright treats adding a cookie with the like identifying attributes as supersede the be one, allowing you to vary values like assay-mark tokens, expiration times, or flags.

Example of modifying a cookie & # 8217; s value:

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

Deleting and Clearing Cookies

Playwright furnish straightforward methods to blue-pencil specific cookies or clear all cookies in the current browser context, helping maintain exam isolation and reset session province effectively.

Deleting Specific Cookies

Playwright does not have a commit deleteCookies () method but deleting a cookie is done by overwriting it with an expired date or by brighten 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 vacuous value and past expiration to invalidate it.

Example of deleting a specific cookie by expiring it:

await context.addCookies ([{
name: & # 8216; user_token & # 8217;,
value: & # 8221;,
domain: & # 8216; example.com & # 8217;,
path: & # 8216; / & # 8217;,
expires: 0 // Set to expire immediately
}]);

Clearing All Cookies

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

Example

await context.clearCookies ();

Read More:

Saving and Reusing Cookie State

In Playwright, saving and reusing the biscuit state allows you to preserve session data (such as cookies, localStorage, and IndexedDB) across different test runs. This is peculiarly useful for avoid insistent logins and ensuring tests start from a consistent state, saving worthful clip in automated testing.

Saving Cookie State

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

Example

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

This saves the current browser context & # 8217; s session datum to authState.json, include cooky and localStorage information.

Reusing Cookie State

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

Example

const context = await browser.newContext ({
storageState: & # 8216; authState.json & # 8217; // Load preserve cookie province
});

Use Cases for Saving and Reusing Cookie State

Reusing cooky province in Playwright can importantly enhance the efficiency and reliability of your tests. Here are some practical scenarios where saving and reusing cookie state can be particularly beneficial:

  • Skipping Login Steps:Save the authenticated session after logging in erst and reuse it across multiple tests to avoid logging in repeatedly.
  • Simulating Different User Roles:Save freestanding cookie states for different user roles (e.g., admin, user) and load them as demand to simulate role-based access.
  • Testing Authenticated User Flows:Preserve the session after login to direct test authenticated user flows, such as access a individualized splasher or setting.
  • Managing Complex User Sessions:Maintain session continuity across multiple tests, ensuring persistent states like shopping cart items or user druthers are carried over.
  • Bypassing Cookie Consent or Pop-ups:Save the province after interact with cookie consent banners or pop-ups to skip these steps in future tests.
  • Performance Testing Across Multiple Browsers:Reuse the saved cooky state across different browsers and devices to ascertain logical user sessions during performance testing.

Read More:

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, trial flakiness, and environs consistency:

  • Use Separate Browser Contexts for Isolation:Create a new BrowserContext for each test or exploiter session to isolate biscuit and storage, forestall cross-test contamination and enabling parallel performance safely.
  • Set Cookies Before Navigation:When feign authenticate states, set cookies early using context.addCookies () before navigating to the page. This avoids unneeded login steps and speeds up tests.
  • Persist and Reuse Storage State Thoughtfully:Save cookies and localStorage to a province file with context.storageState () and reuse it to maintain session persistence across tests. Regularly refresh save states to avert stale or expired cookies.
  • Open Cookies Between Tests:Use context.clearCookies () to reset session cookies, ensuring a clear slate when test isolation or repeatability is critical.
  • Handle Cookie Attributes Correctly:Accurately set flag like httpOnly, secure, sameSite, and going times to mimic real-world cookie behavior and avoid unexpected tryout outcome.
  • Validate Cookies Explicitly:Retrieve and inspect cookies using context.cookies () to verify tryout preconditions or assert post-conditions, improving test robustness.
  • Manage Cookies for Multiple Domains:When working with sites spanning multiple orbit, cautiously scope cookies by domain and route to reflect realistic scenario and avoid conflicts.
  • Securely Manage Cookie Data:Treat saved cooky state file as sensible data, especially when they contain authentication tokens.
  • Use Error Handling for Cookie Operations:Wrap cookie manipulations in try-catch blocks to handle unexpected browser demeanour or confinement gracefully.
  • Test in Both Headed and Headless Modes:Validate biscuit behavior consistently in different Playwright run modes to get environment-specific issues.

Scale Your Playwright Testing with BrowserStack Automate

offers a knock-down cloud-based platform to scale Playwright test mechanization effortlessly across thousands of real browser and nomadic devices. It removes the complexities of managing substructure, enabling teams to quicken test performance, growth coverage, and improve reliability at scale.

Key Benefits of Using BrowserStack Automate with Playwright:

  • All-inclusive Device and Browser Coverage:Run Playwright examination on 3,500+ existent background and mobile browsers, include the industry-first support for real iOS device, Android phones, and tablets to obviate emulator gaps.
  • High-Scale Parallel Testing:Execute hundred to thousands of tests concurrently, reducing test cortege runtime by 10x or more without local resource constraints or custom scaling logic.
  • Seamless CI/CD Integration:Integrate effortlessly with popular tools like, GitHub Actions,, and, enabling automated test runs as portion of your deployment pipelines.
  • Comprehensive Debugging and Analytics:Access rich logs, video recordings, console outputs, web traces, and Playwright Trace Viewer data from a individual dashboard for faster stem cause analysis and debugging.
  • AI-Powered Self-Healing:BrowserStack & # 8217; s smart AI agent automatically detects and heals humbled locators during trial runs, dramatically reducing flaky tests and maintenance overhead.

Talk to Expert

Conclusion

Managing biscuit efficaciously in Playwright is essential for simulating existent user sessions, authenticating exploiter, and essay various scenarios with persistent session data.

By utilizing method like setting, modifying, saving, and reusing cookies, you can streamline your test execution, improve test consistence, and care complex user workflows more efficiently.

Integrating BrowserStack Automate with Playwright further heighten your testing capabilities by enabling cross-browser testing and scaling test across real device, guarantee comprehensive test coverage.

Useful Resources for Playwright

Tool Comparisons:

Tags
7,000+ Views

# Ask-and-Contributeabout this topic 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