node.jscookieselectronnode-request

How to store cookies client-side from request module response


I'm creating a desktop app with electron using a private API. When I make request I got the set-cookie in res.headers but I don't know how to store it locally. First I was storing every cookies in one variable so the last set-cookie is overwritting the old one but with further research I found that cookies are not working like that and I need to merge the old and the new cookies response but I don't know how to do that.

Everything I find is only to set a new cookie serverside but never like the browser do.

let cookies

request({
  uri: myUrl,
  method: 'GET'
}, function (err, res, body) {
  if (err) {}
  if (res.headers['set-cookie']) {
    cookies = res.headers['set-cookie']
  }
})

Solution

  • Managed to do it using request and tough-cookie-filestore to persist data

    var request = require('request')
    const FileCookieStore = require('tough-cookie-filestore');
    // NOTE - currently the 'cookies.json' file must already exist!
    const j = request.jar(new FileCookieStore('./cookie.json'));
    request = request.defaults({ jar : j })