Why does Chrome lose cookies when I restart the browser in my Puppeteer script?

I’m having trouble with my Puppeteer script. I want the browser to keep cookies when I close and open it again. But it’s not working. The cookies disappear every time.

Here’s what my code looks like:

const puppeteer = require('puppeteer');

async function runBrowser() {
  const dataFolder = '/tmp/browser_data';

  const options = [
    '--max-window',
    '--no-sync',
    '--skip-security-check',
    '--ignore-ssl-errors'
  ];

  const browser = await puppeteer.launch({
    headless: false,
    args: options,
    userDataDir: dataFolder,
    ignoreHTTPSErrors: true
  });

  const tab = await browser.newPage();
  // More code here...
}

runBrowser();

I thought using userDataDir would fix this. But it didn’t help. What am I doing wrong? How can I make the cookies stick around?

hey mate, i had this same problem. try using a persistent context instead. it’s way more reliable for keeping cookies and stuff. here’s how:

const browser = await puppeteer.launch();
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();

this way chrome won’t dump your cookies every time. hope it helps!

I’ve dealt with this issue before, and it can be frustrating. From my experience, the problem might be related to how you’re closing the browser. If you’re forcibly terminating the process, Chrome might not have a chance to save the session data properly.

Try adding a controlled shutdown at the end of your script:

await browser.close();

Also, make sure your dataFolder path is writable and persists between script runs. On some systems, ‘/tmp’ might be cleared periodically.

Another thing to check is if you’re running multiple instances of your script simultaneously. This can cause conflicts with the user data directory.

If these don’t work, you might want to consider using a session storage solution like puppeteer-extra-plugin-stealth for more reliable cookie persistence. It’s saved me a lot of headaches in similar situations.

I’ve encountered this issue in my Puppeteer projects as well. One thing that often gets overlooked is the importance of waiting for network idle before closing the browser. This ensures all data is properly saved.

Try adding this line before closing the browser:

await page.waitForNavigation({ waitUntil: ‘networkidle0’ });

Also, double-check your Chrome version. In some older versions, there were known issues with cookie persistence. Updating to the latest stable version might resolve the problem.

If you’re still having trouble, consider implementing a custom cookie handling solution. You can manually save cookies to a file and restore them at the start of each session. It’s a bit more work, but it gives you full control over the process.