Skip to content

Instantly share code, notes, and snippets.

@ilyazub ilyazub/README.md
Created Aug 9, 2019

Embed
What would you like to do?
Reuse `puppeteer` cookies in `tough-cookie` and `got`

Reuse puppeteer cookies in tough-cookie and got

This way we can send HTTP requests from the Node.js instead of UI interactions.

Set puppeteer cookies to tough-cookie's CookieJar

const cookies = await page.cookies()
cookies.forEach(
  async cookie => {
    await setCookie(
      `${cookie.name}=${cookie.value}`,
      'https://www.example.com'
    )
  }
)

Use CookieJar in got request

const { request } = await got('https://www.example.com', { cookieJar })
const { promisify } = require('util')
const puppeteer = require('puppeteer')
const got = require('got')
const { CookieJar } = require('tough-cookie')
const cookieJar = new CookieJar()
const setCookie = promisify(cookieJar.setCookie.bind(cookieJar))
;(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://www.example.com', { waitUntil: 'networkidle2' })
// That's the takeaway: set puppeteer cookies to CookieJar
const cookies = await page.cookies()
cookies.forEach(
async cookie => {
await setCookie(
`${cookie.name}=${cookie.value}`,
'https://www.example.com'
)
}
)
await setCookie('test_cookie=1', 'https://www.example.com')
// This way we can send HTTP requests from the Node.js instead of UI interactions.
const { request } = await got('https://www.example.com', { cookieJar })
console.log(request.gotOptions.headers.cookie)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.