node-tls-clientLatest version on npm

Cookies

The session cookie jar, sending your own cookies, and reading what was set.

Each session has a cookie jar in the native library. Cookies set by a response are stored there and sent on later requests to the same site, just like a browser. You don't have to do anything:

const session = new Session();
// httpbin sets `theme=dark` and redirects; we just want the Set-Cookie.
await session.get("https://httpbin.org/cookies/set/theme/dark");

// Sent automatically from now on:
const res = await session.get("https://httpbin.org/cookies");
console.log(await res.json()); // { cookies: { theme: 'dark' } }

Sending your own cookies

cookies in the request options sends extra cookies, as name → value:

// Your own cookies: sent with this request AND added to the jar,
// so later requests to this host send them too.
const withConsent = await session.get("https://httpbin.org/cookies", {
  cookies: { consent: "yes", visits: 3 },
});
console.log(await withConsent.json()); // { cookies: { consent: 'yes', theme: 'dark', visits: '3' } }

These cookies are added to the jar. Later requests to the same host send them too, without passing them again. Values are sent verbatim, so a value may contain ; or =.

Reading cookies

Two ways, with different scopes:

// response.cookies: what the jar holds for this host after the response.
const response = await session.get("https://httpbin.org/cookies/set/lang/en");
console.log(response.cookies); // { consent: 'yes', lang: 'en', theme: 'dark', visits: '3' }

// session.cookies(): every cookie the session has sent or received.
const all = await session.cookies();
console.log([...new Set(all.map((c) => c.key))]); // [ 'theme', 'consent', 'visits', 'lang' ]
APIReturns
response.cookies{ name: value } for every cookie the jar holds for this host, after this response.
session.cookies()Every cookie the session has sent or received, as tough-cookie objects (key, value, domain, path, creation, …).

Domain and path in session.cookies() come from the URL each cookie was seen on, so the same cookie can appear once per path (the example dedupes by key). Expiry and HttpOnly/Secure flags aren't available.

Turning the jar off

withoutCookieJar: true disables the native jar. Response cookies are no longer sent on later requests; only the cookies you pass are. session.cookies() still records what it saw.

const stateless = new Session({ withoutCookieJar: true });
await stateless.get("https://httpbin.org/cookies/set/theme/dark");
const fresh = await stateless.get("https://httpbin.org/cookies");
console.log(await fresh.json()); // { cookies: {} }

withCustomCookieJar: true swaps Go's standard cookie jar for tls-client's own implementation. Cookies still persist between requests either way.

Clearing cookies

There's no API to delete cookies from a session. Close it and start a new one.

On this page