Get Third‑Party Cookies with Puppeteer – Step‑by‑Step Guide
In this article
You can retrieve third‑party cookies in Puppeteer by launching Chromium with the proper flags, creating a browser context that allows cross‑site cookies, navigating to a page that loads the third‑party resources, and then reading the cookie store via the DevTools Protocol.
What You’ll Need
- Node.js (v14 or newer) installed on your machine
- Puppeteer package (npm install puppeteer)
- A target website that sets third‑party cookies (e.g., a page with an embedded analytics iframe)
- Basic familiarity with JavaScript and async/await
- Optional: Chrome/Chromium executable path if you want to use a custom build
Step‑by‑Step
- Install Puppeteer. Open a terminal and run
npm init -y && npm install puppeteer. This will download a recent Chromium binary that matches the library version. - Create a new script file. For example,
third‑party‑cookies.js. This file will contain the entire workflow. - Import the library and set up async main.
const puppeteer = require('puppeteer'); (async () => { // code will go here })(); - Launch Chromium with flags that disable SameSite enforcement. The flags
--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecuretell the browser to treat SameSite cookies as if the feature were off, allowing third‑party cookies to be set.const browser = await puppeteer.launch({ headless: false, args: [ '--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure', '--disable-blink-features=AutomationControlled', '--no-sandbox' ] }); - Create an isolated browser context. Using an incognito context prevents previous cookies from interfering.
const context = await browser.createIncognitoBrowserContext(); const page = await context.newPage(); - Set a permissive cookie policy for the page. You can enable third‑party cookies via the Chrome DevTools Protocol (CDP) command
Network.setCookieor by adjusting the default cookie behavior.
This step is optional but demonstrates that the session can set SameSite=None cookies, which third‑party services often use.const client = await page.target().createCDPSession(); await client.send('Network.setCookie', { name: 'placeholder', value: '1', domain: '.example.com', path: '/', expires: Math.floor(Date.now() / 1000) + 3600, sameSite: 'None', secure: true }); - Navigate to the target page. Use
page.gotowithwaitUntil: 'networkidle2'so all sub‑resources (including iframes) finish loading.await page.goto('https://your‑target‑site.com', { waitUntil: 'networkidle2' }); - Wait for the third‑party iframe to load. If you know the iframe selector, wait for it; otherwise a short timeout works.
await page.waitForSelector('iframe[src*="third‑party.com"]', { timeout: 10000 }); - Extract cookies from the entire browser context. The simple
page.cookies()call only returns cookies for the current page’s URL. To get third‑party cookies, request them for the third‑party domain explicitly.// Retrieve cookies for the third‑party domain const thirdPartyCookies = await page.cookies('https://third‑party.com'); console.log('Third‑party cookies:', thirdPartyCookies); - Alternatively, use CDP to fetch all cookies. This method returns every cookie stored in the Chromium profile, regardless of domain.
Filter the result for the domain you care about.const allCookies = await client.send('Network.getAllCookies'); console.log('All cookies in context:', allCookies.cookies); - Validate the result. Look for the
domainfield matching the third‑party host and ensuresameSiteis set toNone(orLaxif the site uses that). If the array is empty, the third‑party script likely blocked cookie creation. - Close the browser. Always clean up resources.
await browser.close();
Common Mistakes
- Forgetting to pass the
--disable-featuresflags. Modern Chromium enforces SameSite, so third‑party cookies are silently dropped without the flags. - Calling
page.cookies()without specifying the third‑party URL. The method defaults to the page’s main URL, which never includes cross‑origin cookies. - Using a persistent browser context that already contains a
SameSitepolicy override from a previous run. Always start with a fresh incognito context. - Running headless mode without the flags. Some headless builds have stricter defaults; disabling the features explicitly avoids surprises.
- Neglecting to wait for the iframe or network idle state, causing the script to read cookies before they are set.
Tips
- Combine
Network.setCookiewithNetwork.enableto ensure the CDP session is ready before navigation. - Use
await page.waitForResponse(response => response.url().includes('third‑party.com') && response.status() === 200)to guarantee the third‑party request succeeded. - If the third‑party domain uses HTTP‑Only cookies, they will appear in
Network.getAllCookiesbut not be accessible via JavaScript. CDP is the only way to read them. - Store the extracted cookies in JSON for later reuse with
page.setCookie(...)to simulate a logged‑in or tracked session. - When debugging, open the DevTools window (set
headless: false) and inspect the Application → Cookies panel to see what the browser actually stored.
Troubleshooting
If you end up with an empty cookie array, follow these steps:
- Confirm the flags are correctly passed. Print
browser.process().spawnargsto verify the argument list. - Check the network tab in the opened Chrome window for any
Set‑Cookieheaders coming from the third‑party domain. If the header is missing, the server isn’t sending cookies. - Make sure the request is not blocked by CSP or by the site’s own anti‑tracking measures. Some sites only set cookies after a user interaction.
- Verify that the cookie’s
Secureattribute is satisfied (the page must be loaded over HTTPS). Loading the page viahttp://will cause Secure cookies to be ignored. - Inspect the
sameSiteattribute in the response. If it is set toLaxorStrict, the browser may refuse to store it for a cross‑origin request unless the flags are active. - Try using the CDP command
Network.clearBrowserCookiesbefore navigation to ensure no stale cookies interfere. - If you still see no cookies, add a manual
await page.evaluate(() => document.cookie)after navigation; this will reveal any first‑party cookies that might be masking the issue.
Frequently Asked Questions
Do third‑party cookies work in headless mode?
Yes, but only when the SameSite‑related features are disabled via the command‑line flags. Without those flags, Chromium’s headless mode follows the same privacy defaults as the regular UI.
Can I read HTTP‑Only cookies with page.cookies()?
No. page.cookies() respects the JavaScript visibility rules. To access HTTP‑Only cookies you must use the DevTools Protocol method Network.getAllCookies.
Is it safe to disable SameSite globally?
Disabling the feature is safe for a controlled scraping environment, but you should never ship a browser with those flags to end users because it reduces privacy protections.
What if the third‑party site sets the cookie with SameSite=None but without Secure?
Modern browsers reject SameSite=None without the Secure flag. The cookie will be ignored unless you also launch Chromium with the --allow-insecure-localhost flag for testing on localhost.
Do I need to clear cookies between runs?
When using an incognito context, Chromium automatically discards cookies when the context is closed, so manual clearing isn’t required.
Can I use this approach with Firefox?
Puppeteer’s primary support is for Chromium. Firefox support exists but does not expose the same CDP commands, making third‑party cookie handling more limited.