Ora

How Do I Delete Cookies From My Puppeteer?

Published in Puppeteer Cookie Management 6 mins read

To delete cookies in Puppeteer, you primarily use the page.deleteCookie() method for specific cookies or leverage incognito browser contexts for a complete fresh start. Managing cookies is essential for various automation tasks, including maintaining privacy, ensuring clean test environments, or simulating user states.

Understanding Cookie Management in Puppeteer

Cookies are small pieces of data stored by websites in your browser. Puppeteer, being a headless browser control library, allows you to interact with these cookies programmatically. Deleting cookies helps in:

  • Ensuring a Clean Slate: For testing scenarios, you might need to start each test run without lingering data from previous sessions.
  • Privacy: Clearing sensitive data.
  • Simulating User Behavior: Testing how a site behaves for a first-time visitor versus a returning one.

Deleting Specific Cookies

Puppeteer provides a straightforward method to remove one or more specific cookies from the current page's browser context: page.deleteCookie(). This method requires you to specify the details of the cookies you wish to remove.

The page.deleteCookie(...cookies) method expects an array of cookie objects. Each cookie object must at least specify the name and domain of the cookie to be deleted. Other properties like path can also be included for more precise targeting, especially when multiple cookies share the same name but differ by path.

Example: Deleting a Single Specific Cookie

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    // Navigate to a page to set some cookies (e.g., a login page or any site)
    await page.goto('https://example.com');

    // Set a dummy cookie for demonstration
    await page.setCookie({
        name: 'mySpecificCookie',
        value: 'someValue',
        domain: 'example.com',
        path: '/',
        expires: Date.now() / 1000 + 60 * 60, // 1 hour from now
    });

    console.log('Cookies before deletion:');
    let allCookies = await page.cookies();
    console.log(allCookies.filter(c => c.name === 'mySpecificCookie'));

    // Delete the specific cookie
    await page.deleteCookie({
        name: 'mySpecificCookie',
        domain: 'example.com',
    });

    console.log('\nCookies after deletion:');
    allCookies = await page.cookies();
    console.log(allCookies.filter(c => c.name === 'mySpecificCookie')); // Should be empty

    await browser.close();
})();

Example: Deleting Multiple Specific Cookies

You can pass multiple cookie objects to page.deleteCookie() to remove them simultaneously.

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://example.com');

    // Set multiple dummy cookies
    await page.setCookie(
        {
            name: 'cookieOne',
            value: 'valueOne',
            domain: 'example.com',
        },
        {
            name: 'cookieTwo',
            value: 'valueTwo',
            domain: 'example.com',
            path: '/subpath',
        },
        {
            name: 'anotherCookie',
            value: 'anotherValue',
            domain: 'example.com',
        }
    );

    console.log('Cookies before deletion:');
    let allCookies = await page.cookies();
    console.log(allCookies.filter(c => ['cookieOne', 'cookieTwo', 'anotherCookie'].includes(c.name)));

    // Delete specific cookies
    await page.deleteCookie(
        {
            name: 'cookieOne',
            domain: 'example.com',
        },
        {
            name: 'cookieTwo',
            domain: 'example.com',
            path: '/subpath', // Important to match path if the cookie has one
        }
    );

    console.log('\nCookies after deletion:');
    allCookies = await page.cookies();
    console.log(allCookies.filter(c => ['cookieOne', 'cookieTwo', 'anotherCookie'].includes(c.name))); // 'anotherCookie' should remain

    await browser.close();
})();

For more details, refer to the official Puppeteer page.deleteCookie() documentation.

Effectively Clearing All Cookies for a Fresh Session

While page.deleteCookie() is excellent for specific removals, there isn't a single deleteAllCookies() method for a page. However, you can achieve a "fresh slate" effectively using a few common strategies:

1. Using an Incognito Browser Context

The most robust way to ensure a completely clean and isolated session is to use an incognito browser context. An incognito context does not share cookies, local storage, or other data with the default browser context or other incognito contexts.

When to use: Ideal when you need to start a task from scratch, simulating a brand-new user session without any prior history.

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();

    // Create a new incognito browser context
    const context = await browser.createIncognitoBrowserContext();
    const page = await context.newPage();

    // Now 'page' operates in an isolated environment with no pre-existing cookies
    await page.goto('https://example.com');
    const cookies = await page.cookies();
    console.log('Cookies in incognito context:', cookies); // Should be minimal or none initially

    // Perform actions...

    // Close the context when done to discard all its data (including cookies)
    await context.close();
    await browser.close();
})();

Learn more about isolated contexts in the Puppeteer browser.createIncognitoBrowserContext() documentation.

2. Programmatically Deleting All Existing Cookies for the Current Page

If you need to clear all cookies within an existing page's context during a session (and not just start fresh with an incognito context), you can first retrieve all cookies for the current page and then pass them to page.deleteCookie().

When to use: When you are already in a standard browser context and need to clear all current cookies for the page's loaded domains without creating a new context.

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://example.com');

    // Set some dummy cookies
    await page.setCookie(
        { name: 'session_id', value: '12345', domain: 'example.com' },
        { name: 'user_pref', value: 'dark_mode', domain: 'example.com' }
    );

    console.log('Cookies before clearing all:');
    let initialCookies = await page.cookies();
    console.log(initialCookies);

    // Get all cookies visible to the current page
    const allCurrentCookies = await page.cookies();

    // Delete all retrieved cookies
    await page.deleteCookie(...allCurrentCookies);

    console.log('\nCookies after clearing all:');
    let finalCookies = await page.cookies();
    console.log(finalCookies); // Should be empty

    await browser.close();
})();

You can inspect current cookies using Puppeteer page.cookies() documentation.

Important Considerations for Cookie Deletion

  • Domain and Path Specificity: Cookies are often tied to a specific domain and path. When deleting a cookie, you must provide the correct name and domain. If a cookie was set with a specific path, including that path in the deletion object will ensure it's accurately targeted.
  • Browser Context vs. Page Context: Cookies are typically scoped to a browser context. A single browser can have multiple contexts (e.g., default, incognito tabs). Cookies set within one context are usually isolated from others.
  • Persistence: Cookies in a non-incognito browser context persist until deleted or expired. Closing a page does not delete its cookies; closing the browser or browser context typically does for ephemeral sessions or if they are session cookies.

By understanding these methods and considerations, you can effectively manage and delete cookies within your Puppeteer automation scripts.