C
ClearView News

How to set Cookies enabled in puppeteer

Author

Michael Henderson

Published Jan 02, 2026

Publish date: 2024-01-03

I am currently having the problem (puppeteer) in a project that I think cookies are not activated. But I also don't know how to activate them if they are not already activated from the beginning.

2

1 Answer

Since every website nowaday has Captcha, so we can skip the auto-login part. I'm new too, I got an idea from here for this.

Firstly check if there is saved cookies.json file, if not, do the manually login, you click the submit button yourself and solve the captcha puzzle (in non-headless mode), the page should be redirected to destination page.

Once the destination page is loaded, save the cookies in to a Json file for next time.

Example:

const puppeteer = require('puppeteer'); const fs = require('fs'); (async () => { const browser = await puppeteer.launch({ headless: false, //launch in non-headless mode so you can see graphics defaultViewport: null }); let [page] = await browser.pages(); await page.setRequestInterception(true); const getCookies = async (page) => { // Get page cookies const cookies = await page.cookies() // Save cookies to file fs.writeFile('./cookies.json', JSON.stringify(cookies, null, 4), (err) => { if (err) console.log(err); return }); } const setCookies = async (page) => { // Get cookies from file as a string let cookiesString = fs.readFileSync('./cookies.json', 'utf8'); // Parse string let cookies = JSON.parse(cookiesString) // Set page cookies await page.setCookie.apply(page, cookies); return } page.on('request', async (req) => { // If URL is already loaded in to system if (req.url() === ') { console.log('logged in, get the cookies'); await getCookies(page); // if it's being in login page, try to set existed cookie } else if (req.url() === ') { await setCookies(page); console.log('set the saved cookies'); } // otherwise go to login page and login yourself req.continue(); }); await page.goto('); })();

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobXJsaWuAdYCOoaawZaSkerSx02aaqKebnrK0ecSnmJuklZl6qrqMqaypqJWpsqa%2B