Mindfulness

How to Clear Cookies in Playwright

Updated · By the Relaxmid editors

Reading time
5 min
Sections
6
Topic
Mindfulness

Use the browserContext.clearCookies() method to remove all cookies from a specific browser context. For example, calling await context.clearCookies(); after a logout sequence ensures the next session starts without previous authentication data.

How Do You Clear All Cookies for a Context?

The most direct way to handle cookies in Playwright is through the BrowserContext object. Since a context acts as an isolated session, clearing its cookies removes every cookie associated with any domain visited during that session. This is essential when you need to test a clean-slate user experience or verify that a logout function actually destroys the session on the client side.

To implement this, you first need a reference to your context. If you are using the default browser setup, you create a context using browser.newContext(). Once you have this object, the clearCookies() method wipes the storage. This action is asynchronous, so you must use the await keyword to ensure the cookies are fully removed before the browser attempts to load the next page. If you skip the await, the browser might send old cookies with the subsequent request, leading to intermittent test failures where a user appears logged in when they should be logged out.

This method is a global wipe for that specific context. It does not matter which domain the cookies belong to; they are all deleted. This is useful for general cleanup between test cases. If your test suite runs multiple scenarios in one context, calling this method at the end of each test prevents state leakage. State leakage occurs when a cookie from Test A influences the behavior of Test B, making it difficult to determine why a test is failing.

What Is the Difference Between Clearing Cookies and Clearing Storage?

Many developers confuse clearing cookies with clearing all browser storage. Cookies are small pieces of data sent with every HTTP request to a server. However, modern web applications also use Local Storage and Session Storage, which are stored locally in the browser and not sent to the server. The clearCookies() method only removes cookies; it does not touch Local Storage or Session Storage.

If an application uses a JWT (JSON Web Token) stored in Local Storage for authentication, calling clearCookies() will not log the user out. You will see the user remain authenticated because the application checks the Local Storage instead of a cookie. To fully reset a browser’s state, you must clear both. While Playwright does not have a single clearAllStorage() command, you can execute JavaScript within the page to clear these areas.

To clear Local Storage and Session Storage, use the page.evaluate() method. You can run window.localStorage.clear() and window.sessionStorage.clear(). This ensures that no remnants of the previous session remain. A common pattern is to create a helper function that calls clearCookies() and then evaluates the storage clear commands. This combination provides a truly clean environment, similar to opening a browser in Incognito mode for the first time.

How Do You Remove Specific Cookies Only?

Sometimes you do not want to wipe everything. You might want to keep a preference cookie while removing an authentication token. Playwright allows you to manage specific cookies using browserContext.clearCookies({name: 'session_id'}) or by filtering by domain.

When you pass an object to clearCookies(), you can specify the name of the cookie you wish to target. If you only provide the name, Playwright removes all cookies with that name across all domains. If you provide both a name and a domain, it only removes the cookie for that specific site. This is helpful for testing third-party integrations where you want to clear the cookies for a payment provider but keep the cookies for your own main application.

Another way to handle specific cookies is to retrieve the full list using browserContext.cookies(). This returns an array of cookie objects. You can then filter this array to find the specific cookies you want to remove and call clearCookies() for each one. This programmatic approach gives you total control over the browser state. For instance, if you need to test how a site behaves when a specific tracking cookie is missing but the user is still logged in, this is the only way to achieve that state.

Why Are Cookies Still Present After Clearing?

If you find that cookies reappear immediately after you clear them, it is usually because the page is still open and the application is automatically regenerating them. Many modern web apps have scripts that check for the existence of a session cookie every few seconds. If the cookie is missing, the script may automatically request a new one from the server or regenerate a guest session cookie.

To prevent this, clear the cookies while the browser is on a blank page or before you navigate to the target URL. If you clear cookies while the page is active, the active JavaScript on that page may trigger a refresh or a background API call that sets a new cookie. The safest sequence is to navigate to about:blank, clear the cookies, and then navigate to your application URL.

Another common misconception is that clearing cookies removes the cache. Cookies and the browser cache are different. The cache stores images, scripts, and HTML files to make pages load faster. Clearing cookies does not remove these cached files. If you are seeing old versions of a page, you may need to use a fresh browser context entirely rather than just clearing cookies. Creating a new context with browser.newContext() is the most reliable way to ensure no cache, cookies, or storage persist from a previous session.

How to Implement a Full Reset Sequence

To ensure a completely clean state for every test, follow a structured reset sequence. This prevents flakiness and ensures that your tests are deterministic. A deterministic test is one that produces the same result every time it is run, regardless of what happened in previous tests.

Follow these steps to perform a full reset:

  1. Navigate the page to about:blank to stop any active scripts from the application from running.
  2. Call await context.clearCookies(); to remove all HTTP cookies.
  3. Use await page.evaluate(() => window.localStorage.clear()); to wipe persistent local data.
  4. Use await page.evaluate(() => window.sessionStorage.clear()); to wipe session-specific data.
  5. Navigate to the starting URL of your application.

By following this order, you eliminate the risk of the application regenerating cookies while you are trying to delete them. This sequence is particularly important for applications that use complex authentication flows involving multiple redirects and third-party identity providers. If you only clear cookies, the identity provider might still have a session in the browser’s local storage, leading to an automatic login that bypasses your test’s login screen.

If you find yourself doing this for every single test, consider using a new BrowserContext for every test instead of reusing one. Playwright is designed to make context creation very fast. A new context provides a fresh profile with no cookies, no cache, and no storage by default. This is generally preferred over manual clearing because it is faster to implement and more reliable. You only need to manually clear cookies if your specific test case requires you to simulate a user clearing their browser data mid-session.

Related

General information for everyday wellbeing, not medical advice. If something affects your health, sleep or mood for more than a short while, talk to a qualified professional. Read more

Spotted an error? Tell us and we will correct it (corrections policy).