Puppeteer saves cookies and load/read cookies. #How to save a login of a page with puppeteer.

Walter-Tscharf-Development
2 min readJan 18, 2022
Photo by Micah Williams on Unsplash

This article is covering the topic of saving and loading a session. Or better saving the cookies after login and reloading the cookies after a puppeteer session was closed. This means the article contains the following steps.

Script Alpha:

1. Open page and login to a website

2. Save cookies to a json file and close.

Script Beta:

3. Open a new page

4. Load the cookies from the previous session.

5. Redirect to the desired page after the login.

To accomplish this step follow the following script:

Code for the Script Alpha:

const puppeteer = require(‘puppeteer’);let browser = await puppeteer.launch({
headless: this.head,
args: [
‘ — no-sandbox’,
‘ — disable-setuid-sandbox’,
‘ — use-fake-ui-for-media-stream’,
‘ — disable-audio-output’,
‘ — disable-features=IsolateOrigins’,
‘ — disable-site-isolation-trials’,
],
});
let page = await browser.newPage();
await page.goto("https://www.ebay.com", {timeout: 500000});
// login procedure
await page.type("input#username", 'test@gmail.com');
await page.type("input#password", 'thisIsThePass0Wrd');
await page.click("div#loginButton");
await this.page.waitForTimeout(2000)
// save cookise:
const cookies = await page.cookies()
console.log("The cookies: ", cookies);
fs.writeFile(
'cookies.json',
JSON.stringify(cookies, null, 2),
function(err) {
if (err) throw err;
console.log('Write cookies complet');
}
);
browser.close();

After executing this script you should find a file cookies.json containing the saved cookies of the page after the login was triggered of the page.

If you want to reload the page with the login session then you can just use the following:

const puppeteer = require(‘puppeteer’);let browser = await puppeteer.launch({
headless: this.head,
args: [
‘ — no-sandbox’,
‘ — disable-setuid-sandbox’,
‘ — use-fake-ui-for-media-stream’,
‘ — disable-audio-output’,
‘ — disable-features=IsolateOrigins’,
‘ — disable-site-isolation-trials’,
],
});
let page = await browser.newPage();
// load the cookies from the file
const cookiesString = fs.readFileSync('./cookies.json', 'utf8');
const cookies = JSON.parse(cookiesString);
console.info("Google - Setting cookies")
await page.setCookie.apply(page, cookies);
// load the page you want to go to after the login
await page.goto("https://ebay.com/dashboard",{waitUntil: ['networkidle2']});
// here you can do what ever you want with the session the page will use the login sesseion
...
// When you are done just close the browser again.
await browser.close();

That is it. I hope it helped. Happy coding.

--

--