Managing Cookies using Playwright

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

Get Started free
Managing Cookies using Playwright
Home Guide Managing Cookies using Playwright

Managing Cookies using Playwright

Cookies play a crucial role in web applications by storing session data, user preferences, and authentication information. In automated testing, managing cookies effectively is essential for ensuring accurate and efficient test execution.

Overview

Playwright provides a powerful API to manage cookies, allowing you to set, retrieve, modify, and delete cookies during automated testing. This ensures you can simulate real user behavior and test authentication, sessions, and user preferences effectively.

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 context for each test to prevent cookie leakage.
  • Clear Cookies Between Tests: Use clearCookies() to ensure clean state between tests.
  • Use Secure Cookies: Set httpOnly and secure flags for sensitive cookies.
  • Persist Cookie State: Save and reuse cookie state to speed up tests by bypassing login steps.
  • Handle Expiry: Regularly refresh cookie states to ensure sessions are up-to-date and valid.

This article explores how to handle cookies in Playwright, from retrieving and setting them to saving and reusing cookie states, with best practices and real-world use cases to optimize your testing workflows.

Understanding Cookies and their Importance

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 personalized content, authentication, and tracking.

Types of Cookies:

  • 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.

Why Cookies Matter in Testing:

  • Authentication: Cookies often store authentication tokens or session IDs, allowing users to stay logged in between visits.
  • 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 cookies in automated tests ensures that sessions and user preferences are maintained across multiple test steps, reducing test flakiness and improving reliability.

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

Playwright Testing

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 cookies within a browser context. These APIs facilitate session management, authentication handling, and state persistence in automated tests.

Key cookie-related methods in Playwright include:

  • 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.
  • 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.
  • context.clearCookies(): Clears all cookies in the current browser context, helping to reset session state between tests or scenarios.
  • context.deleteCookies(cookies): Deletes specific cookies based on their attributes like name, domain, or path.
  • context.storageState(): Exports the storage state, including cookies and local storage, allowing session persistence by saving the state to disk and later loading it in a new browser context.

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

Example usages:

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

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

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

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
});

Use Cases for Saving and Reusing Cookie State

Reusing cookie state in Playwright can significantly 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 once and reuse it across multiple tests to avoid logging in repeatedly.
  • Simulating Different User Roles: Save separate cookie states for different user roles (e.g., admin, user) and load them as needed to simulate role-based access.
  • Testing Authenticated User Flows: Preserve the session after login to directly test authenticated user flows, such as accessing a personalized dashboard or settings.
  • Managing Complex User Sessions: Maintain session continuity across multiple tests, ensuring persistent states like shopping cart items or user preferences are carried over.
  • Bypassing Cookie Consent or Pop-ups: Save the state after interacting with cookie consent banners or pop-ups to skip these steps in future tests.
  • Performance Testing Across Multiple Browsers: Reuse the saved cookie state across different browsers and devices to ensure consistent user sessions during performance testing.

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.

Talk to Expert

Conclusion

Managing cookies effectively in Playwright is essential for simulating real user sessions, authenticating users, and testing various scenarios with persistent session data.

By utilizing methods like setting, modifying, saving, and reusing cookies, you can streamline your test execution, improve test consistency, and handle complex user workflows more efficiently.

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.

Try BrowserStack Now

Useful Resources for Playwright

Tool Comparisons:

Tags
Automation Testing Real Device Cloud Website Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord