RFC6265 Cookies and Cookie Jar for node.js
npx @tessl/cli install tessl/npm-tough-cookie@6.0.0Tough Cookie is a comprehensive RFC 6265-compliant HTTP cookie library for JavaScript and Node.js that provides parsing, storage, and retrieval of cookies. It offers a complete implementation of cookie handling including domain matching, path matching, secure cookies, SameSite attributes, and cookie prefixes, with both synchronous and asynchronous APIs.
npm install tough-cookieimport { Cookie, CookieJar, MemoryCookieStore, Store } from "tough-cookie";For CommonJS:
const { Cookie, CookieJar, MemoryCookieStore, Store } = require("tough-cookie");Utility functions:
import {
parse,
fromJSON,
canonicalDomain,
domainMatch,
pathMatch,
parseDate,
formatDate
} from "tough-cookie";import { Cookie, CookieJar } from "tough-cookie";
// Parse a cookie string
const cookie = Cookie.parse('name=value; Domain=example.com; Path=/; Secure');
// Create a cookie jar with default memory store
const jar = new CookieJar();
// Set a cookie from a Set-Cookie header
await jar.setCookie('session=abc123; HttpOnly; Secure', 'https://example.com/');
// Get cookies for a URL as Cookie objects
const cookies = await jar.getCookies('https://example.com/');
// Get cookies as a Cookie header string
const cookieHeader = await jar.getCookieString('https://example.com/');
// Create a cookie programmatically
const newCookie = new Cookie({
key: 'user_pref',
value: 'dark_mode',
domain: 'example.com',
path: '/',
secure: true,
httpOnly: false,
maxAge: 86400 // 1 day in seconds
});Tough Cookie is built around several key components:
Core cookie parsing, creation, and manipulation functionality. Handle individual cookies with full RFC 6265 compliance including validation, serialization, and attribute management.
// Parse cookie from string
function parse(str: string, options?: ParseCookieOptions): Cookie | undefined;
// Create cookie from JSON
function fromJSON(str: unknown): Cookie | undefined;
// Cookie comparison for sorting
function cookieCompare(a: Cookie, b: Cookie): number;Comprehensive cookie storage and retrieval with RFC-compliant domain and path matching, expiration handling, and security validation.
// Set cookies with validation
setCookie(
cookie: string | Cookie,
url: string | URL,
options?: SetCookieOptions
): Promise<Cookie | undefined>;
// Get cookies for URL
getCookies(
url: string | URL,
options?: GetCookiesOptions
): Promise<Cookie[]>;
// Get cookie header string
getCookieString(
url: string | URL,
options?: GetCookiesOptions
): Promise<string>;Pluggable storage system supporting both synchronous and asynchronous operations with complete CRUD functionality for cookie persistence.
// Store base class
abstract class Store {
abstract findCookie(
domain: string | null,
path: string | null,
key: string | null
): Promise<Cookie | undefined>;
abstract putCookie(cookie: Cookie): Promise<void>;
abstract getAllCookies(): Promise<Cookie[]>;
}
// Memory store implementation
class MemoryCookieStore extends Store {
synchronous: boolean; // Always true
}Domain validation, path matching, date parsing, and other RFC-compliant utility functions for cookie processing.
// Domain utilities
function canonicalDomain(domainName: string | null): string | undefined;
function domainMatch(domain?: string | null, cookieDomain?: string | null): boolean | undefined;
function getPublicSuffix(domain: string, options?: GetPublicSuffixOptions): string | undefined;
// Path utilities
function pathMatch(reqPath: string, cookiePath: string): boolean;
function defaultPath(path?: string | null): string;
// Date utilities
function parseDate(cookieDate: string | null): Date | undefined;
function formatDate(date: Date): string;// Cookie constructor options
interface CreateCookieOptions {
key?: string;
value?: string;
expires?: Date | 'Infinity' | null;
maxAge?: number | 'Infinity' | '-Infinity' | null;
domain?: string | null;
path?: string | null;
secure?: boolean;
httpOnly?: boolean;
extensions?: string[] | null;
creation?: Date | 'Infinity' | null;
hostOnly?: boolean | null;
pathIsDefault?: boolean | null;
lastAccessed?: Date | 'Infinity' | null;
sameSite?: string | undefined;
}
// Cookie parsing options
interface ParseCookieOptions {
loose?: boolean; // Allow keyless cookies like =abc
}
// CookieJar configuration
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
}
// Cookie setting options
interface SetCookieOptions {
loose?: boolean;
sameSiteContext?: 'strict' | 'lax' | 'none';
ignoreError?: boolean;
http?: boolean; // Default: true
now?: Date;
}
// Cookie retrieval options
interface GetCookiesOptions {
http?: boolean; // Default: true
expire?: boolean; // Default: true
allPaths?: boolean; // Default: false
sameSiteContext?: 'none' | 'lax' | 'strict';
sort?: boolean;
}
// Public suffix options
interface GetPublicSuffixOptions {
allowSpecialUseDomain?: boolean; // Default: false
ignoreError?: boolean; // Default: false
}
// Callback types
interface Callback<T> {
(error: Error, result?: never): void;
(error: null, result: T): void;
}
interface ErrorCallback {
(error: Error | null): void;
}
// Serialization types
type SerializedCookie = {
key?: string;
value?: string;
[key: string]: unknown;
}
interface SerializedCookieJar {
version: string;
storeType: string | null;
rejectPublicSuffixes: boolean;
[key: string]: unknown;
cookies: SerializedCookie[];
}