Managing Cookies using Playwright
On This Page Understanding Cookies and their ImportanceMarch 04, 2026 · 11 min read · Tool Comparison
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. 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 Best Practices for Cookie Management in Playwright 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. 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: Why Cookies Matter in Testing: Understanding and managing cookies effectively in is crucial for authenticated workflows, user sessions, and personalized features, create it a key component of any automated. 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: 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: // Set a cookie // Clear all cookies This set of biscuit APIs makes Playwright highly flexible for managing browser states and feign user sessions programmatically during automated testing. Read More: 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. 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. 3. Get Cookies for the Current Page If no area is specified, context.cookies () retrieves all cookies for the current page. Why Inspect Cookies? Using these methods, you can easily regain and inspect cookies, enabling better control over session data during automated testing with Playwright. Read More: 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. 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: 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: 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. 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: 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 Read More: 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. 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 This saves the current browser context & # 8217; s session datum to authState.json, include cooky and localStorage information. 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 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: Read More: 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: 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: 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. Tool Comparisons: On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Managing Cookies apply Playwright
Overview
Understanding Cookies and their Importance
Cookie APIs in Playwright
// Get all cookies
const cookies = await context.cookies ();
await context.addCookies ([{
name: & # 8216; session_id & # 8217;,
value: & # 8216; abc123 & # 8217;,
domain: & # 8216; example.com & # 8217;,
path: & # 8216; / & # 8217;,
httpOnly: true,
secure: true,
}]);
await context.clearCookies ();How to Get and Inspect Cookies
const cookies = await context.cookies (& # 8216; https: //example.com & # 8217;);
console.log (cookies); // Logs an raiment of cookieconst 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 cookieconst biscuit = await context.cookies ();
console.log (biscuit); // Logs cookies for the current pageSetting and Modifying Cookies
How to Set Cookies
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
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
Deleting Specific Cookies
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
await context.clearCookies ();
Saving and Reusing Cookie State
Saving Cookie State
await context.storageState ({path: & # 8216; authState.json & # 8217;});Reusing Cookie State
const context = await browser.newContext ({
storageState: & # 8216; authState.json & # 8217; // Load preserve cookie province
});Use Cases for Saving and Reusing Cookie State
Best Practices for Cookie Management in Playwright
Scale Your Playwright Testing with BrowserStack Automate
Conclusion
Useful Resources for Playwright
Related Guides
Automate This With SUSA
Test Your App Autonomously