Skip to main content
Zimt

Home baking recipes and cinnamon favourites

Fix Puppeteer Pages That Cannot Read Cookies

You can fix Puppeteer pages that cannot read cookies by ensuring the browser context shares the correct cookie store, using the right launch arguments, and handling storage consistently across page navigations.

What You'll Need

  • Node.js (v12 or newer) installed on your machine
  • npm or yarn to install packages
  • The latest stable version of the puppeteer npm package
  • A recent Chromium or Chrome binary that matches the Puppeteer version
  • Basic knowledge of async/await in JavaScript

Step-by-Step

  1. Install Puppeteer and Verify the Browser Version. Open a terminal and run npm install puppeteer. After installation, check the bundled Chromium version with npx puppeteer --version. If you plan to use a custom Chrome executable, note its exact version because mismatched versions can cause cookie‑related errors.
  2. Launch the Browser with a Persistent User Data Directory. By default Puppeteer runs in a temporary profile that is discarded after the script ends, which means cookies are lost. Provide a userDataDir option so the same profile is reused:
    const browser = await puppeteer.launch({
      headless: false,
      userDataDir: './my‑profile',
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-web-security' // optional, see tip below
      ]
    });
    This directory stores cookies, localStorage, and other session data across runs.
  3. Disable the Default Incognito Context (If You Use One). Many developers create an incognito context with browser.createIncognitoBrowserContext() because it feels safer. Incognito contexts do not persist cookies, so any page opened there will appear unable to read previously set cookies. Either avoid incognito for pages that need cookies, or explicitly set cookies in that context using context.overridePermissions and context.addCookies.
  4. Set the Correct SameSite and Secure Flags. Modern browsers enforce SameSite=Lax or Strict by default, and they reject cookies without the Secure flag on HTTPS sites. When you manually add cookies with page.setCookie(...), include these attributes to match what the server expects:
    await page.setCookie({
      name: 'session_id',
      value: 'abc123',
      domain: 'example.com',
      path: '/',
      httpOnly: true,
      secure: true,
      sameSite: 'Lax'
    });
  5. Wait for Navigation to Complete Before Reading Cookies. Puppeteer may try to read cookies immediately after a page.goto() call, but the network request might still be in progress. Use await page.waitForNavigation({ waitUntil: 'networkidle2' }) or await page.waitForTimeout(1000) to give the page time to set its cookies.
  6. Use the Same Page or Context When Accessing Cookies. Cookies are scoped to the browser context, not the individual Page objects. If you open a new page with await browser.newPage() inside the same context, you can read the cookies. However, if you inadvertently create a new context, the cookie store is fresh. Keep a reference to the original context:
    const context = browser.defaultBrowserContext();
    const page = await context.newPage();
    // later…
    const secondPage = await context.newPage();
  7. Persist Cookies Manually Between Runs (Optional). If you cannot keep a permanent userDataDir, you can export cookies after a session and reload them next time:
    const cookies = await page.cookies();
    require('fs').writeFileSync('cookies.json', JSON.stringify(cookies, null, 2));
    // …on next run
    const saved = JSON.parse(require('fs').readFileSync('cookies.json'));
    await page.setCookie(...saved);
    
    This technique is handy for CI pipelines where a persistent folder may be undesirable.
  8. Verify the Cookie Store Using DevTools. Open the Chrome DevTools window attached to the Puppeteer instance (press F12 or right‑click → Inspect). Navigate to the Application tab and look under Cookies. If the expected cookies are missing, the issue is likely in the steps above.
  9. Close the Browser Cleanly. Always call await browser.close() after your script finishes. Abrupt termination can corrupt the userDataDir, causing the next launch to start with an empty profile.

Common Mistakes

  • Launching with headless: true and expecting the same cookie behaviour as a headed session. Some sites set cookies only when a visible window is present.
  • Creating a new incognito context for every page without re‑adding the required cookies.
  • Omitting the domain attribute when using page.setCookie, causing the cookie to be scoped to localhost instead of the target domain.
  • Reading cookies before the page finishes loading, which returns an empty array.
  • Using a mismatched Chrome version; Chromium updates can change cookie handling rules.

Tips

  • Set the --disable-web-security flag only when you control the environment; it relaxes SameSite enforcement and can simplify testing.
  • When debugging, enable dumpio: true in the launch options to see Chrome’s console output directly in your terminal.
  • Use page.evaluate(() => document.cookie) as a quick sanity check; it shows the cookie string as the page sees it.
  • If a site uses HttpOnly cookies, you cannot read them via document.cookie, but page.cookies() will still return them.
  • Consider adding await page.reload({ waitUntil: 'networkidle0' }) after setting cookies to force the browser to send them on the next request.

Troubleshooting

If the page still cannot read cookies after following the steps above, try the following systematic checks:

  1. Confirm the Cookie File Exists. Look inside your userDataDir for a file named Cookies. If it’s missing or empty, the browser never wrote the data.
  2. Check for Domain Mismatch. Open DevTools, go to the Network tab, and inspect the request headers for the Cookie field. If it’s absent, verify that the cookie’s domain matches exactly (including leading dot).
  3. Inspect SameSite Settings. Modern Chrome blocks cross‑site cookies with SameSite=None unless the Secure flag is present. Ensure both flags are set when you manually add cookies.
  4. Validate Timing. Add explicit waits after navigation (e.g., await page.waitForTimeout(2000)) and before reading cookies. This eliminates race conditions.
  5. Run in Headed Mode. Change headless: false and watch the page load. If a banner or consent dialog appears, it may be preventing cookie creation. Automate dismissal of that dialog before checking cookies.
  6. Disable Cache. Use await page.setCacheEnabled(false) to force the browser to request fresh resources, which can reveal whether stale cache is hiding cookie updates.
  7. Check for Extensions or Interceptors. If you load Chrome extensions via --load-extension, they may interfere with cookie handling. Test without extensions.
  8. Review Server‑Side Set‑Cookie Headers. Use the Network tab to see the exact Set-Cookie header the server sends. If the header contains attributes that conflict with your script (e.g., Expires=Thu, 01 Jan 1970 00:00:00 GMT), the cookie will be immediately discarded.

After each check, restart the script to see if the issue resolves. If none of the above fixes the problem, consider filing an issue on the Puppeteer GitHub repository with a minimal reproducible example.

Frequently Asked Questions

Why does a page see an empty document.cookie string but page.cookies() returns values?

Because document.cookie cannot access HttpOnly cookies, while page.cookies() reads the full cookie store directly from the browser.

Can I use a proxy with a persistent cookie store?

Yes. Add the proxy argument in args (e.g., --proxy-server=host:port) and keep the same userDataDir. The proxy does not affect the local cookie file.

Do I need to clear the userDataDir between test runs?

Only if stale cookies cause false positives. Deleting the directory forces a fresh profile, which is useful for isolated test cases.

How do I handle cookies for multiple domains in the same script?

Use the same browser context and set domain‑specific cookies with page.setCookie({domain: 'example.com', ...}) and {domain: 'other.com', ...}. The context will store each cookie under its appropriate domain.

Is there a way to export cookies in Netscape format for use with curl?

After retrieving cookies with await page.cookies(), you can map them to the Netscape format manually or use a helper library that converts the JSON array to the .txt format expected by curl.

What if the site uses JavaScript‑only cookie setting (e.g., via document.cookie)?

Make sure the script that writes the cookie runs before you attempt to read it. Use await page.waitForFunction(() => document.cookie.includes('myCookie')) to wait until the cookie appears.

Read next