RFC6265 Cookies and Cookie Jar for node.js
—
Comprehensive cookie storage and retrieval system with RFC 6265-compliant domain and path matching, expiration handling, security validation, and support for RFC 6265bis features like SameSite attributes and cookie prefixes.
The main class for cookie storage and retrieval with RFC 6265 compliance and extensive configuration options.
/**
* Creates a new CookieJar with optional store and configuration
* @param store - Storage backend (defaults to MemoryCookieStore if null/undefined)
* @param options - Configuration options or boolean for legacy rejectPublicSuffixes
*/
class CookieJar {
constructor(store?: Store | null, options?: CreateCookieJarOptions | boolean);
// Properties
store: Store;
prefixSecurity: string;
// Cookie management methods (async)
setCookie(cookie: string | Cookie, url: string | URL, options?: SetCookieOptions): Promise<Cookie | undefined>;
setCookie(cookie: string | Cookie, url: string | URL, callback: Callback<Cookie | undefined>): void;
setCookie(cookie: string | Cookie, url: string | URL, options: SetCookieOptions, callback: Callback<Cookie | undefined>): void;
getCookies(url: string | URL, options?: GetCookiesOptions): Promise<Cookie[]>;
getCookies(url: string, callback: Callback<Cookie[]>): void;
getCookies(url: string | URL, options: GetCookiesOptions, callback: Callback<Cookie[]>): void;
getCookieString(url: string | URL, options?: GetCookiesOptions): Promise<string>;
getCookieString(url: string, callback: Callback<string | undefined>): void;
getCookieString(url: string, options: GetCookiesOptions, callback: Callback<string | undefined>): void;
getSetCookieStrings(url: string | URL, options?: GetCookiesOptions): Promise<string[] | undefined>;
getSetCookieStrings(url: string, callback: Callback<string[] | undefined>): void;
getSetCookieStrings(url: string, options: GetCookiesOptions, callback: Callback<string[] | undefined>): void;
// Synchronous versions (only work with synchronous stores)
setCookieSync(cookie: string | Cookie, url: string, options?: SetCookieOptions): Cookie | undefined;
getCookiesSync(url: string, options?: GetCookiesOptions): Cookie[];
getCookieStringSync(url: string, options?: GetCookiesOptions): string;
getSetCookieStringsSync(url: string, options?: GetCookiesOptions): string[];
}
interface CreateCookieJarOptions {
rejectPublicSuffixes?: boolean; // Default: true
looseMode?: boolean; // Default: false
prefixSecurity?: 'strict' | 'silent' | 'unsafe-disabled'; // Default: 'silent'
allowSpecialUseDomain?: boolean; // Default: true
allowSecureOnLocal?: boolean; // Default: true
}Usage Examples:
import { CookieJar, MemoryCookieStore } from "tough-cookie";
// Create jar with default memory store
const jar = new CookieJar();
// Create jar with custom configuration
const strictJar = new CookieJar(new MemoryCookieStore(), {
rejectPublicSuffixes: true,
prefixSecurity: 'strict',
allowSecureOnLocal: false
});
// Create jar with loose mode for parsing
const looseJar = new CookieJar(null, {
looseMode: true,
prefixSecurity: 'silent'
});Methods for storing cookies in the jar with comprehensive validation.
/**
* Attempts to set a cookie in the jar with RFC 6265 validation
* @param cookie - Cookie string or Cookie object
* @param url - URL where cookie is being set
* @param options - Configuration options for setting
* @returns Promise resolving to stored Cookie or undefined if rejected
*/
setCookie(
cookie: string | Cookie,
url: string | URL,
options?: SetCookieOptions
): Promise<Cookie | undefined>;
/**
* Synchronous version of setCookie. Only works with synchronous stores
* @param cookie - Cookie string or Cookie object
* @param url - URL where cookie is being set
* @param options - Configuration options for setting
* @returns Stored Cookie or undefined if rejected
*/
setCookieSync(
cookie: string | Cookie,
url: string,
options?: SetCookieOptions
): Cookie | undefined;
interface SetCookieOptions {
loose?: boolean;
sameSiteContext?: 'strict' | 'lax' | 'none';
ignoreError?: boolean;
http?: boolean; // Default: true
now?: Date;
}Usage Examples:
import { CookieJar } from "tough-cookie";
const jar = new CookieJar();
// Set a basic cookie
await jar.setCookie('session=abc123', 'https://example.com/');
// Set cookie with options
await jar.setCookie(
'csrf=token123; SameSite=Strict; Secure',
'https://example.com/',
{
loose: false,
sameSiteContext: 'strict',
ignoreError: false
}
);
// Set cookie synchronously (if store supports it)
const cookie = jar.setCookieSync('user=john', 'https://example.com/');
// Set cookie with error handling
try {
await jar.setCookie('__Secure-id=123', 'http://example.com/'); // Will fail due to __Secure- prefix
} catch (error) {
console.log('Cookie rejected:', error.message);
}Methods for retrieving cookies that match specific URLs and contexts.
/**
* Retrieves cookies that can be sent for the given URL
* @param url - URL to get cookies for
* @param options - Options controlling which cookies are returned
* @returns Promise resolving to array of matching cookies
*/
getCookies(url: string | URL, options?: GetCookiesOptions): Promise<Cookie[]>;
/**
* Returns cookies as a Cookie header string
* @param url - URL to get cookies for
* @param options - Options controlling which cookies are returned
* @returns Promise resolving to cookie header string
*/
getCookieString(url: string | URL, options?: GetCookiesOptions): Promise<string>;
/**
* Returns array of Set-Cookie header strings
* @param url - URL to get cookies for
* @param options - Options controlling which cookies are returned
* @returns Promise resolving to array of Set-Cookie strings
*/
getSetCookieStrings(url: string | URL, options?: GetCookiesOptions): Promise<string[] | undefined>;
interface GetCookiesOptions {
http?: boolean; // Default: true
expire?: boolean; // Default: true (automatically expire old cookies)
allPaths?: boolean; // Default: false (include cookies from all paths)
sameSiteContext?: 'none' | 'lax' | 'strict';
sort?: boolean; // Sort cookies according to RFC 6265
}Usage Examples:
import { CookieJar } from "tough-cookie";
const jar = new CookieJar();
// Set some cookies first
await jar.setCookie('session=abc123; Path=/', 'https://example.com/');
await jar.setCookie('theme=dark; Path=/app', 'https://example.com/app/');
await jar.setCookie('csrf=token; SameSite=Strict', 'https://example.com/');
// Get all matching cookies
const cookies = await jar.getCookies('https://example.com/app/');
// Get cookie header string for HTTP request
const cookieHeader = await jar.getCookieString('https://example.com/app/');
console.log(cookieHeader); // "session=abc123; theme=dark; csrf=token"
// Get cookies with specific SameSite context
const strictCookies = await jar.getCookies('https://example.com/', {
sameSiteContext: 'strict'
});
// Get cookies including all paths
const allPathCookies = await jar.getCookies('https://example.com/', {
allPaths: true
});
// Get Set-Cookie strings
const setCookieStrings = await jar.getSetCookieStrings('https://example.com/');Methods for serializing, deserializing, and cloning cookie jars.
/**
* Serializes the CookieJar if the store supports getAllCookies
* @returns Promise resolving to serialized jar data
*/
serialize(): Promise<SerializedCookieJar>;
serialize(callback: Callback<SerializedCookieJar>): void;
/**
* Synchronous version of serialize
* @returns Serialized jar data or undefined if not supported
*/
serializeSync(): SerializedCookieJar | undefined;
/**
* Alias for serializeSync()
* @returns Serialized jar data or undefined
*/
toJSON(): SerializedCookieJar | undefined;
/**
* Creates a deep clone of the CookieJar
* @param newStore - Optional new store for the clone
* @returns Promise resolving to cloned CookieJar
*/
clone(newStore?: Store): Promise<CookieJar>;
clone(callback: Callback<CookieJar>): void;
clone(newStore: Store, callback: Callback<CookieJar>): void;
/**
* Synchronous version of clone
* @param newStore - Optional new store for the clone
* @returns Cloned CookieJar or undefined if not supported
*/
cloneSync(newStore?: Store): CookieJar | undefined;
interface SerializedCookieJar {
version: string; // tough-cookie version
storeType: string | null; // Store constructor name
rejectPublicSuffixes: boolean;
[key: string]: unknown; // Other configuration
cookies: SerializedCookie[]; // Serialized cookies
}Usage Examples:
import { CookieJar } from "tough-cookie";
const jar = new CookieJar();
// Add some cookies
await jar.setCookie('session=abc123', 'https://example.com/');
await jar.setCookie('user=john', 'https://example.com/');
// Serialize the jar
const serialized = await jar.serialize();
const jsonString = JSON.stringify(serialized);
// Clone the jar
const clonedJar = await jar.clone();
// Clone with a different store
const customStore = new MemoryCookieStore();
const jarWithNewStore = await jar.clone(customStore);
// Synchronous operations (if store supports it)
const syncSerialized = jar.serializeSync();
const syncClone = jar.cloneSync();Static methods for creating CookieJars from serialized data.
/**
* Creates a new CookieJar from serialized data
* @param strOrObj - Serialized jar string or object
* @param store - Optional store for the new jar
* @returns Promise resolving to deserialized CookieJar
*/
static deserialize(strOrObj: string | object, store?: Store): Promise<CookieJar>;
static deserialize(strOrObj: string | object, callback: Callback<CookieJar>): void;
static deserialize(strOrObj: string | object, store: Store, callback: Callback<CookieJar>): void;
/**
* Synchronous version of deserialize
* @param strOrObj - Serialized jar string or object
* @param store - Optional store for the new jar
* @returns Deserialized CookieJar
*/
static deserializeSync(strOrObj: string | SerializedCookieJar, store?: Store): CookieJar;
/**
* Alias for deserializeSync
* @param jsonString - JSON string or serialized object
* @param store - Optional store for the new jar
* @returns Deserialized CookieJar
*/
static fromJSON(jsonString: string | SerializedCookieJar, store?: Store): CookieJar;Usage Examples:
import { CookieJar } from "tough-cookie";
// Deserialize from JSON string
const jsonString = '{"version":"6.0.0","cookies":[...]}';
const jar1 = await CookieJar.deserialize(jsonString);
// Deserialize with custom store
const customStore = new MemoryCookieStore();
const jar2 = await CookieJar.deserialize(jsonString, customStore);
// Synchronous deserialization
const jar3 = CookieJar.deserializeSync(jsonString);
// Using fromJSON alias
const jar4 = CookieJar.fromJSON(jsonString);Methods for removing cookies from the jar.
/**
* Removes all cookies from the jar
* @returns Promise that resolves when cleanup is complete
*/
removeAllCookies(): Promise<void>;
removeAllCookies(callback: ErrorCallback): void;
/**
* Synchronous version of removeAllCookies
*/
removeAllCookiesSync(): void;Usage Examples:
import { CookieJar } from "tough-cookie";
const jar = new CookieJar();
// Add some cookies
await jar.setCookie('session=abc123', 'https://example.com/');
await jar.setCookie('user=john', 'https://example.com/');
// Remove all cookies
await jar.removeAllCookies();
// Synchronous cleanup
jar.removeAllCookiesSync();
// Verify cleanup
const cookies = await jar.getCookies('https://example.com/');
console.log(cookies.length); // 0import { CookieJar } from "tough-cookie";
const jar = new CookieJar();
// Set cookies with different SameSite attributes
await jar.setCookie('strict=value; SameSite=Strict', 'https://example.com/');
await jar.setCookie('lax=value; SameSite=Lax', 'https://example.com/');
await jar.setCookie('none=value; SameSite=None; Secure', 'https://example.com/');
// Get cookies with specific SameSite context
const strictContext = await jar.getCookies('https://example.com/', {
sameSiteContext: 'strict' // Only gets cookies appropriate for strict context
});
const laxContext = await jar.getCookies('https://example.com/', {
sameSiteContext: 'lax' // Gets cookies appropriate for lax context
});import { CookieJar, MemoryCookieStore } from "tough-cookie";
// Strict prefix validation
const strictJar = new CookieJar(new MemoryCookieStore(), {
prefixSecurity: 'strict'
});
try {
// This will throw an error because __Secure- prefix requires HTTPS
await strictJar.setCookie('__Secure-id=123; Secure', 'http://example.com/');
} catch (error) {
console.log('Prefix violation:', error.message);
}
// Silent prefix validation (default)
const silentJar = new CookieJar(null, {
prefixSecurity: 'silent'
});
// This will silently ignore the invalid cookie
const result = await silentJar.setCookie('__Host-id=123', 'http://example.com/');
console.log(result); // undefined (cookie was rejected)interface Callback<T> {
(error: Error, result?: never): void;
(error: null, result: T): void;
}
interface ErrorCallback {
(error: Error | null): void;
}
type SerializedCookie = {
key?: string;
value?: string;
[key: string]: unknown;
}Install with Tessl CLI
npx tessl i tessl/npm-tough-cookie