Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshxyzhimself/7e5c312c75eb6ff9dd923b6013ca640f to your computer and use it in GitHub Desktop.
Save joshxyzhimself/7e5c312c75eb6ff9dd923b6013ca640f to your computer and use it in GitHub Desktop.
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