Zimt

How to Save and Load Cookies in Puppeteer

· 4 min read · Cookies and Bars

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To save and load cookies in Puppeteer, you serialize the browser's cookie objects to a file (usually JSON) and then set them back on a new browser context before navigating. This lets you persist login sessions, avoid repeated authentication, and maintain state across script runs.

What You'll Need

  • Node.js (v12 or later) installed
  • A project with Puppeteer installed (npm install puppeteer)
  • Basic familiarity with async/await and file system operations

Step-by-Step

  1. Set up your Puppeteer script. Create a new file, e.g., cookies.js, and require Puppeteer and the file system module.
  2. Launch a browser and open a page. Use puppeteer.launch() and page.goto() to a site where you need a session (e.g., a login page).
  3. Perform login or any action that sets cookies. This could be filling a form and submitting, or simply visiting a page that sets cookies automatically.
  4. Get the cookies. Call const cookies = await page.cookies(); — this returns an array of cookie objects.
  5. Save cookies to a file. Use fs.writeFileSync('cookies.json', JSON.stringify(cookies)); to store them.
  6. Close the browser. Call await browser.close(); to end the session.
  7. Load cookies in a new script or session. Read the file with const cookies = JSON.parse(fs.readFileSync('cookies.json'));.
  8. Set cookies on the page. After opening a page, call await page.setCookie(...cookies); before navigating to the target URL.
  9. Navigate to the protected page. Use page.goto() to the URL that requires the session. The cookies will be sent automatically.

Common Mistakes

  • Not waiting for cookies to be set. If you save cookies immediately after navigation, they might be incomplete. Use page.waitForNavigation() or a delay after login.
  • Using the wrong cookie domain. Cookies are domain-specific. If you set them on a different domain than they were meant for, they won't be sent.
  • Forgetting to set cookies before navigation. setCookie must be called before goto() to the target page, otherwise the request won't include them.
  • Overwriting the cookie file. If you save cookies every run, you might overwrite a valid session with an invalid one. Use a separate file for each site or check if the file exists.
  • Not handling expired cookies. Cookies have expiration dates. If you load an old file, the session may be invalid. Always check the status code of the page after loading.

Tips

  • Use a dedicated cookie file per site. This prevents mixing domains and makes debugging easier.
  • Store cookies as JSON. JSON is human-readable and easy to edit if needed.
  • Consider using userDataDir. Instead of manual cookie saving, you can launch Puppeteer with a persistent user data directory: puppeteer.launch({ userDataDir: './profile' }). This saves all browser state, including cookies, automatically.
  • Test cookie validity. After loading cookies, check if the page contains expected elements (e.g., a logout button) to confirm the session is active.
  • Use environment variables for sensitive data. If your cookies contain tokens, don't hardcode them in the script.

Troubleshooting

  • Cookies are not being saved. Check that the page actually sets cookies. Use page.on('response', ...) to inspect Set-Cookie headers, or manually check document.cookie in the page.
  • Cookies are saved but not loaded. Ensure the file is readable and the JSON is valid. Also verify that the cookie domain matches the URL you're navigating to.
  • Session still not recognized. Some sites use localStorage or IndexedDB for session tokens. Save those as well using page.evaluate() to retrieve and set them.
  • Cookies expire too quickly. Some cookies are session-only and are cleared when the browser closes. If you need long-term persistence, consider using a persistent user data directory instead.
  • Getting a 403 or redirect to login. The cookies might be invalid or expired. Re-run the login step and save fresh cookies.

Frequently Asked Questions

Can I save cookies from one browser and load them in another?

Yes, as long as the cookies are not tied to a specific device or browser fingerprint. Most session cookies work across browsers if the domain and path match.

Do I need to save cookies for every page or just the main domain?

You should save all cookies returned by page.cookies() — they include subdomain and path details. Setting them all ensures the session works across the site.

How do I clear cookies before saving new ones?

Use page.deleteCookie(...cookies) to remove specific cookies, or browser.newPage() to start with a clean context. You can also call page.setCookie() with empty array to clear all.

Is it safe to store cookies in plain text?

It depends on the sensitivity. For personal scripts, it's common, but for production, encrypt the file or use a secure storage service.

Can I use cookies with Puppeteer Cluster or multiple pages?

Yes, you can set the same cookies on multiple pages by iterating over each page and calling setCookie with the same array.

What if the site uses httpOnly cookies?

Puppeteer can still access them via page.cookies() because it interacts with the browser directly. They are included in the returned array.