API Reference

RezoCookieJar

RezoCookieJar extends tough-cookie’s CookieJar with enhanced features including multiple input/output formats, file persistence, and browser-accurate domain matching. Also exported as CookieJar.

Constructors

RezoCookieJar has four constructor overloads:

new RezoCookieJar()
new RezoCookieJar(cookies: Cookie[])
new RezoCookieJar(cookies: Cookie[], url: string)
new RezoCookieJar(store: Store | null, options?: CreateCookieJarOptions | boolean)
OverloadDescription
No argsCreates an empty cookie jar.
cookies: Cookie[]Creates a jar pre-loaded with the given cookies.
cookies: Cookie[], url: stringCreates a jar with cookies associated to the given URL.
store, optionsCreates a jar with a custom tough-cookie store and options.

Example

import { RezoCookieJar, Cookie } from 'rezo';

// Empty jar
const jar = new RezoCookieJar();

// Pre-loaded jar
const cookies = [
  new Cookie({ key: 'session', value: 'abc123', domain: 'example.com' })
];
const jar2 = new RezoCookieJar(cookies, 'https://example.com');

cookies(url?)

Returns all cookies (or cookies for a specific URL) in multiple formats.

cookies(url?: string): Cookies

Returns a Cookies object:

PropertyTypeDescription
arrayCookie[]Array of Cookie instances.
serializedSerializedCookie[]Plain objects for JSON serialization.
netscapestringNetscape cookie file format string.
stringstringCookie header format (key=value; key2=value2).
setCookiesStringstring[]Array of Set-Cookie header strings.

Example

const all = jar.cookies();
console.log(all.string);    // "session=abc123; theme=dark"
console.log(all.array);     // [Cookie, Cookie, ...]

// Filter by URL
const google = jar.cookies('https://google.com');

parseResponseCookies(cookies)

Converts an array of Cookie instances into the Cookies multi-format object.

parseResponseCookies(cookies: Cookie[]): Cookies

Serialization Methods

toNetscapeCookie() (instance)

Returns all cookies in Netscape cookie file format.

toNetscapeCookie(): string

toCookieString() (instance)

Returns all cookies as a Cookie header string.

toCookieString(): string

toArray()

Returns all cookies as an array of Cookie instances.

toArray(): Cookie[]

toSetCookies()

Returns all cookies as an array of Set-Cookie header strings.

toSetCookies(): string[]

toSerializedCookies()

Returns all cookies as an array of serialized plain objects.

toSerializedCookies(): SerializedCookie[]

Static Serialization

static toNetscapeCookie(cookies: Cookie[] | SerializedCookie[]): string
static toCookieString(cookies: Cookie[] | SerializedCookie[]): string

Request Filtering

getCookiesForRequest(requestUrl)

Returns cookies that should be sent with a request to the given URL. Properly handles domain matching, path matching, Secure flag, and expiry.

getCookiesForRequest(requestUrl: string | URL): Cookie[]

getCookieHeader(requestUrl)

Returns the Cookie header value for a request. Properly filters by domain, path, secure flag, and expiry.

getCookieHeader(requestUrl: string | URL): string

debugCookiesForRequest(requestUrl)

Returns detailed debug information about cookie matching for a URL.

debugCookiesForRequest(requestUrl: string | URL): {
  url: string;
  matchingCookies: Array<{ key: string; value: string; domain: string; path: string }>;
  cookieHeader: string;
  allCookies: Array<{ key: string; domain: string; path: string }>;
}

Example

const jar = new RezoCookieJar();
// ... add cookies ...

// Get cookies for a request
const cookies = jar.getCookiesForRequest('https://api.example.com/v1/users');

// Get the Cookie header string
const header = jar.getCookieHeader('https://api.example.com/v1/users');
// "session=abc123; csrf_token=xyz789"

// Debug matching
const debug = jar.debugCookiesForRequest('https://api.example.com/v1/users');
console.log(debug.matchingCookies); // Which cookies match and why
console.log(debug.allCookies);      // All cookies in the jar for comparison

Setting Cookies

setCookiesSync (overloaded)

Sets cookies from multiple input formats. All overloads return a Cookies object.

setCookiesSync(setCookieArray: string[]): Cookies
setCookiesSync(setCookieArray: string[], url: string): Cookies
setCookiesSync(cookiesString: string): Cookies
setCookiesSync(cookiesString: string, url: string): Cookies
setCookiesSync(serializedCookies: SerializedCookie[]): Cookies
setCookiesSync(serializedCookies: SerializedCookie[], url: string): Cookies
setCookiesSync(cookieArray: Cookie[]): Cookies
setCookiesSync(cookieArray: Cookie[], url: string): Cookies

Supported Input Formats

FormatDescription
string[]Array of Set-Cookie header strings.
stringNetscape cookie file content, comma-separated Set-Cookie headers, or key=value;key=value format.
SerializedCookie[]Array of plain cookie objects.
Cookie[]Array of Cookie instances.

Example

// From Set-Cookie headers
jar.setCookiesSync([
  'session=abc123; Domain=example.com; Path=/; HttpOnly',
  'theme=dark; Domain=example.com; Max-Age=86400'
], 'https://example.com');

// From cookie string
jar.setCookiesSync('session=abc123;theme=dark', 'https://example.com');

// From Netscape format
jar.setCookiesSync('.example.com	TRUE	/	FALSE	0	session	abc123');

// From serialized objects
jar.setCookiesSync([
  { key: 'token', value: 'xyz', domain: 'api.example.com', path: '/' }
]);

File Persistence

Node-only. loadFromFile, saveToFile, and fromFile use node:fs and throw in browsers and React Native ("requires Node.js, Bun, or Deno"). On those runtimes, persist via JSON.stringify(jar.toJSON()) to whatever storage you have (localStorage, AsyncStorage, IndexedDB) and rehydrate with new RezoCookieJar() + setCookiesSync(parsed).

loadFromFile(filePath)

Loads cookies from a file. Supports .json and .txt (Netscape) formats.

loadFromFile(filePath: string): void

saveToFile(filePath?)

Saves cookies to a file. Uses the configured cookieFile path if no argument is provided. The HTTP adapter calls this automatically after every request when the jar was constructed with a cookieFile — you do not need to call it yourself in the normal flow.

saveToFile(filePath?: string): void

fromFile (static factory)

Creates a new RezoCookieJar pre-loaded from a file.

static fromFile(filePath: string): RezoCookieJar

netscapeCookiesToSetCookieArray(text) (static)

Parses a Netscape cookie file’s contents into an array of Set-Cookie header strings. Useful when you’ve fetched a Netscape file from another tool (curl / wget) and want to feed it into the jar without writing it to disk first.

import { readFileSync } from 'node:fs';
import { RezoCookieJar } from 'rezo';

const text = readFileSync('./from-curl.txt', 'utf-8');
const setCookies = RezoCookieJar.netscapeCookiesToSetCookieArray(text);

const jar = new RezoCookieJar();
jar.setCookiesSync(setCookies, 'https://example.com');

Example

// Load from file
const jar = RezoCookieJar.fromFile('./cookies.json');

// Use the jar
jar.setCookiesSync(['new=cookie'], 'https://example.com');

// Save back
jar.saveToFile('./cookies.json');

// Or save to a different format
jar.saveToFile('./cookies.txt'); // Netscape format

RezoCookieStore (advanced)

RezoCookieJar is built on top of tough-cookie’s memory store. For workloads that need size limits, automatic purging of expired cookies, or change-event notifications, use RezoCookieStore and pass it as the underlying store. Change notifications are delivered via the onChange callback set on the constructor options — there is no .on() event-emitter API on the store.

import { RezoCookieJar, RezoCookieStore, type CookieStoreEvent, type CookieStoreStats } from 'rezo';

const store = new RezoCookieStore({
  maxCookiesPerDomain: 50,
  maxTotalCookies: 5_000,
  autoPurge: true,
  // Subscribe to mutations: 'put' | 'update' | 'remove' | 'remove-all' | 'purge'
  onChange: (event: CookieStoreEvent) => {
    // event.cookie is the affected cookie (when applicable)
    // event.count is the number of cookies affected for bulk events ('remove-all', 'purge')
    metrics.increment('cookie.' + event.type);
  },
});

const jar = new RezoCookieJar(store);

// Inspect the store directly
const stats: CookieStoreStats = store.getStats();
// {
//   totalCookies, totalDomains,
//   domainsBreakdown: Record<string, number>,
//   expiredCookies, secureCookies, httpOnlyCookies, sessionCookies
// }

RezoCookieStoreOptions

interface RezoCookieStoreOptions {
  maxCookiesPerDomain?: number;   // LRU evict when a single domain hits the cap
  maxTotalCookies?: number;       // LRU evict when the entire store hits the cap
  autoPurge?: boolean;            // Drop expired cookies on every put / get
  onChange?: (event: CookieStoreEvent) => void;  // Mutation hook
}

The onChange callback fires for every mutation. If you need cross-process persistence on top of this, forward the event payload to your own backing store.

CookieStoreEvent

interface CookieStoreEvent {
  type: 'put' | 'update' | 'remove' | 'remove-all' | 'purge';
  domain?: string;
  path?: string;
  key?: string;
  cookie?: Cookie;         // The affected cookie (put/update/remove)
  count?: number;          // Number of cookies affected for bulk events
  timestamp: number;
}

Cookie

The Cookie class extends tough-cookie’s Cookie with additional methods for format conversion and URL extraction.

Instance Methods

toNetscapeFormat()

Returns the cookie in Netscape file format (tab-separated).

toNetscapeFormat(): string
const cookie = new Cookie({ key: 'session', value: 'abc', domain: '.example.com', path: '/', secure: true });
console.log(cookie.toNetscapeFormat());
// ".example.com	TRUE	/	TRUE	0	session	abc"

toSetCookieString()

Returns the cookie as a Set-Cookie header string with all attributes.

toSetCookieString(): string
console.log(cookie.toSetCookieString());
// "session=abc; Domain=.example.com; Path=/; Secure"

getURL()

Reconstructs the URL from the cookie’s domain, path, and secure flag.

getURL(): string | undefined
console.log(cookie.getURL()); // "https://example.com/"

Cookie.isCookie(obj) (static)

Type guard to check if an object is a Cookie instance.

static isCookie(cookie: unknown): cookie is Cookie

SerializedCookie

Plain object representation of a cookie for JSON serialization.

interface SerializedCookie {
  key: string;
  value: string;
  domain?: string;
  path?: string;
  expires?: string | Date;
  maxAge?: number | string;
  secure?: boolean;
  httpOnly?: boolean;
  sameSite?: string;
  hostOnly?: boolean;
  creation?: string | Date;
  lastAccessed?: string | Date;
  extensions?: string[];
}

RezoCookieStore

The underlying cookie store used by RezoCookieJar. Provides low-level cookie storage operations.

Methods

putCookie(cookie)

Stores a cookie in the store.

getDomains()

Returns all domains that have stored cookies.

getCookiesForDomain(domain)

Returns all cookies for a specific domain.

purgeExpiredSync()

Synchronously removes all expired cookies from the store.

getStats()

Returns statistics about the cookie store (total cookies, domains, etc.).