How to save and reuse session cookies with Puppeteer?

When working with Puppeteer, you can save and reuse session cookies in order to maintain the state of a session between different browser instances or runs of your script. Here is a step-by-step guide on how to achieve this:

  1. Save the session cookies: Before closing the browser instance, you can access the cookies from the page and save them to a file or in memory. You can do this by using the page.cookies() method which returns an array of cookies currently set for the page. You can then save this array to a file using fs.writeFileSync().
const fs = require('fs'); const cookies = await page.cookies(); fs.writeFileSync('cookies.json', JSON.stringify(cookies));
  1. Reuse the session cookies: When launching a new browser instance, you can load the saved cookies back from the file and set them for the page using the page.setCookie() method. This will allow you to reuse the session cookies from a previous session.
const cookies = JSON.parse(fs.readFileSync('cookies.json', 'utf8')); for (let cookie of cookies) { await page.setCookie(cookie); }

By following these steps, you can save and reuse session cookies with Puppeteer, allowing you to maintain the state of a session between different browser instances or runs of your script.