JamesTheHacker JamesTheHacker - 3 months ago 19
Node.js Question

Requests setting cookies in cookieJar including subdomains

I have a bunch of cookies in JSON format. They're the result of exporting cookies from a plugin called EditThisCookie.

I'm attempting to parse the JSON cookie array and add them to a cookiejar. I do this like so:

JSONCookies.forEach(cookie => {
let extensions = [
'session=true',
'sameSite=no_restriction'
];

cookies.push(new ToughCookie.Cookie({
key: cookie.name,
value: cookie.value,
secure: cookie.secure || false,
path: cookie.path,
httpOnly: cookie.httpOnly || false,
extensions: extensions
}));

// Set the uid property of object with users ID
if(cookie.name === 'c_user') {
this.uid = cookie.value;
}
})


I add them to request's cookiejar:

cookies.forEach(function(cookie) {
cookieJar.setCookie(cookie, 'https://facebook.com', (err, cookie) => {
if(err) {
reject(new Error(err));
return;
}
})
})


... And this works fine. I can make requests to Facebook and pull data from our business groups.

But, many requests on Facebook use a subdomain. Such as
upload.facebook.com
. This doesn't work. Obviously because I'm missing the
domain
from the cookie.

So, I create the tough-cookie and add
domain: '.facebook.com'
. Except now when I make a request it fails with an error:

Error: Cookie not in this host's domain. Cookie:facebook.com Request:null


How am I able to set the cookies in the cookiejar to work across sub domains? Is it possible?

The documentation isn't very good, and I've been unable to find out how to do this. I think it has something to do with the URL passed into
setCookie
. I've attempted to change that to different variations to no avail.

Answer

I had the same problem recently. The solution is to do this:

cookies.push(new ToughCookie.Cookie({
    domain: 'facebook.com'
    key: cookie.name,
    value: cookie.value,
    secure: cookie.secure || false,
    path: cookie.path,
    httpOnly: cookie.httpOnly || false,
    extensions: extensions
}));

The leading . in .facebook.com isn't required. This was discussed on the tough-cookie github issue too.