user1584421
user1584421

Reputation: 3863

Pass signed cookie to puppeteer

I am using node.js and i have access to my signed cookies obviously.

They are in this form:

{ 'connect.sid': 's:qX4ZrttrjydtrjkgsdghsdghrewynZj4Ew2OUh.tTSILkcvgsegsegsegsr99gmW5
0XLcJefM' }

Puppeteer supports cookies and has this function in order to pass the parameters of the cookie:

page.setCookie(...cookies)
...cookies <...Object>
name <string> required
value <string> required
url <string>
domain <string>
path <string>
expires <number> Unix time in seconds.
httpOnly <boolean>
secure <boolean>
sameSite <string> "Strict" or "Lax".
returns: <Promise>

As you can see, you provide the parameters of each field directly. Is there a way to pass my signed cookie directly to puppeteer?

Upvotes: 3

Views: 8838

Answers (1)

Md. Abu Taher
Md. Abu Taher

Reputation: 18846

You have to extract and use the proper cookie format.

  1. First install this extension called EditThisCookie.
  2. Then export your cookie. You will get an array of cookies. enter image description here

  3. Use ... spread to pass all cookies as argument to setCookie.

    await page.setCookie(...cookies)
    

Done!

If you want to write the cookies, then here is a format for that.

const cookies = [
 {
    "domain": "localhost", // google.com, yahoo.com etc. Without the host
    "hostOnly": true,
    "httpOnly": true,
    "name": "connect.sid", // here is the actual cookie name
    "path": "/",
    "sameSite": "no_restriction",
    "secure": false,
    "session": true,
    "storeId": "0",
    "value": "s%3AliYZ-M8urEQLfgn2_kSG_FIPwVTr5VQs.5rrJW7hzuXebekzTRgPYFTYri5nljhGCp8Dz%2FgLoSN4", // and the value
    "id": 1
 }
]

Working example

const cookie = {
    name: 'login_email',
    value: '[email protected]',
    domain: '.paypal.com',
    url: 'https://www.paypal.com/',
    path: '/',
    httpOnly: true,
    secure: true
}

const puppeteer = require('puppeteer');


const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setCookie(cookie)
await page.goto('https://www.paypal.com/signin')
await page.screenshot({
    path: 'paypal_login.png'
})
await browser.close()

If you notice original docs, it shows page.setCookie(...cookies) cookies with three dots. Which basically means you can pass an array of objects as arguments that way.

How you put the data into cookie variable is upto you, you can hard code it, you can use some database etc. That's not related to how you pass the cookie.

If it's only one cookie like in paypal example, you pass them with page.setCookie(cookie), but if it's multiple cookie like you got from exporting using EditThisCookie or the localhost example above, then you have to use the spread operator with three dots like I've explained above.

You can read more about spread and rest on this question.

Upvotes: 7

Related Questions