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
puppeteernpm package - A recent Chromium or Chrome binary that matches the Puppeteer version
- Basic knowledge of async/await in JavaScript
Step-by-Step
-
Install Puppeteer and Verify the Browser Version. Open a terminal and run
npm install puppeteer. After installation, check the bundled Chromium version withnpx puppeteer --version. If you plan to use a custom Chrome executable, note its exact version because mismatched versions can cause cookie‑related errors. -
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
userDataDiroption so the same profile is reused:
This directory stores cookies, localStorage, and other session data across runs.const browser = await puppeteer.launch({ headless: false, userDataDir: './my‑profile', args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-web-security' // optional, see tip below ] }); -
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 usingcontext.overridePermissionsandcontext.addCookies. -
Set the Correct SameSite and Secure Flags. Modern browsers enforce
SameSite=LaxorStrictby default, and they reject cookies without theSecureflag on HTTPS sites. When you manually add cookies withpage.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' }); -
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. Useawait page.waitForNavigation({ waitUntil: 'networkidle2' })orawait page.waitForTimeout(1000)to give the page time to set its cookies. -
Use the Same Page or Context When Accessing Cookies. Cookies are scoped to the browser context, not the individual
Pageobjects. If you open a new page withawait 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(); -
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:
This technique is handy for CI pipelines where a persistent folder may be undesirable.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); - 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.
-
Close the Browser Cleanly. Always call
await browser.close()after your script finishes. Abrupt termination can corrupt theuserDataDir, causing the next launch to start with an empty profile.
Common Mistakes
- Launching with
headless: trueand 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
domainattribute when usingpage.setCookie, causing the cookie to be scoped tolocalhostinstead 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-securityflag only when you control the environment; it relaxes SameSite enforcement and can simplify testing. - When debugging, enable
dumpio: truein 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, butpage.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:
- Confirm the Cookie File Exists. Look inside your
userDataDirfor a file namedCookies. If it’s missing or empty, the browser never wrote the data. - Check for Domain Mismatch. Open DevTools, go to the Network tab, and inspect the request headers for the
Cookiefield. If it’s absent, verify that the cookie’sdomainmatches exactly (including leading dot). - Inspect SameSite Settings. Modern Chrome blocks cross‑site cookies with
SameSite=Noneunless theSecureflag is present. Ensure both flags are set when you manually add cookies. - Validate Timing. Add explicit waits after navigation (e.g.,
await page.waitForTimeout(2000)) and before reading cookies. This eliminates race conditions. - Run in Headed Mode. Change
headless: falseand 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. - 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. - Check for Extensions or Interceptors. If you load Chrome extensions via
--load-extension, they may interfere with cookie handling. Test without extensions. - Review Server‑Side Set‑Cookie Headers. Use the Network tab to see the exact
Set-Cookieheader 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.