CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tough-cookie

RFC6265 Cookies and Cookie Jar for node.js

Pending
Overview
Eval results
Files

cookie-operations.mddocs/

Cookie Operations

Core cookie parsing, creation, and manipulation functionality providing RFC 6265-compliant handling of individual cookies including validation, serialization, and attribute management.

Capabilities

Cookie Class

The main Cookie class represents an HTTP cookie with full RFC 6265 compliance.

/**
 * Creates a new Cookie instance with configurable properties
 * @param options - Cookie configuration options
 */
class Cookie {
  constructor(options?: CreateCookieOptions);
  
  // Core properties
  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;
  creationIndex: number;
  hostOnly: boolean | null;
  pathIsDefault: boolean | null;
  lastAccessed: Date | 'Infinity' | null;
  sameSite: string | undefined;
  
  // Methods
  setExpires(exp: string | Date): void;
  setMaxAge(age: number): void;
  cookieString(): string;
  toString(): string;
  TTL(now?: number): number;
  expiryTime(now?: Date): number | undefined;
  expiryDate(now?: Date): Date | undefined;
  isPersistent(): boolean;
  canonicalizedDomain(): string | undefined;
  cdomain(): string | undefined;
  validate(): boolean;
  clone(): Cookie | undefined;
  toJSON(): SerializedCookie;
}

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;
}

Usage Examples:

import { Cookie } from "tough-cookie";

// Create a simple cookie
const cookie = new Cookie({
  key: 'session',
  value: 'abc123',
  domain: 'example.com',
  path: '/',
  secure: true,
  httpOnly: true,
  maxAge: 3600 // 1 hour
});

// Create a cookie with SameSite
const csrfCookie = new Cookie({
  key: 'csrf_token',
  value: 'xyz789',
  domain: 'example.com',
  path: '/',
  secure: true,
  sameSite: 'strict'
});

// Set expiration
cookie.setExpires(new Date(Date.now() + 86400000)); // 24 hours

// Get string representations
const cookieHeader = cookie.cookieString(); // "session=abc123"
const setCookieHeader = cookie.toString(); // "session=abc123; Domain=example.com; Path=/; Secure; HttpOnly; Max-Age=3600"

Cookie Attribute Methods

Methods for managing cookie attributes and metadata.

/**
 * Sets the 'Expires' attribute. String values are parsed with parseDate()
 * @param exp - Expiration date as Date object or parseable string
 */
setExpires(exp: string | Date): void;

/**
 * Sets the 'Max-Age' attribute in seconds. Handles Infinity and -Infinity values
 * @param age - Age in seconds
 */
setMaxAge(age: number): void;

/**
 * Computes time-to-live in milliseconds. Returns Infinity for non-expiring cookies, 0 for expired
 * @param now - Current time in milliseconds (defaults to Date.now())
 * @returns TTL in milliseconds
 */
TTL(now?: number): number;

/**
 * Computes absolute expiry time in milliseconds since epoch
 * @param now - Current date for calculation (defaults to new Date())
 * @returns Expiry time in milliseconds
 */
expiryTime(now?: Date): number | undefined;

/**
 * Returns expiry time as a Date object
 * @param now - Current date for calculation (defaults to new Date())
 * @returns Expiry date or undefined if never expires
 */
expiryDate(now?: Date): Date | undefined;

/**
 * Indicates if cookie has been persisted to a store
 * @returns True if cookie is persistent (has expires or maxAge)
 */
isPersistent(): boolean;

/**
 * Returns canonical domain name using canonicalDomain()
 * @returns Canonicalized domain or undefined
 */
canonicalizedDomain(): string | undefined;

/**
 * Validates cookie attributes for semantic correctness
 * @returns True if cookie is valid according to RFC 6265
 */
validate(): boolean;

/**
 * Creates a deep clone of the cookie
 * @returns Cloned cookie or undefined if cloning fails
 */
clone(): Cookie | undefined;

Cookie String Methods

Methods for converting cookies to and from string representations.

/**
 * Encodes to a Cookie header value (key=value format)
 * @returns Cookie header string
 */
cookieString(): string;

/**
 * Encodes to a Set-Cookie header value with all attributes
 * @returns Set-Cookie header string
 */
toString(): string;

/**
 * Serializes cookie to JSON-compatible object
 * @returns Serialized cookie object
 */
toJSON(): SerializedCookie;

Usage Examples:

import { Cookie } from "tough-cookie";

const cookie = new Cookie({
  key: 'user_pref',
  value: 'theme=dark',
  domain: 'example.com',
  path: '/',
  secure: true,
  httpOnly: false,
  maxAge: 86400
});

// Check expiration
const ttl = cookie.TTL(); // Time to live in milliseconds
const isExpired = ttl === 0;
const expiryDate = cookie.expiryDate(); // Date object

// Validate cookie
const isValid = cookie.validate();

// Get string formats
const forCookieHeader = cookie.cookieString(); // "user_pref=theme=dark"
const forSetCookieHeader = cookie.toString(); // Full Set-Cookie string

// Clone and modify
const cloned = cookie.clone();
if (cloned) {
  cloned.setMaxAge(7200); // Extend expiration
}

Cookie Parsing

Static methods for parsing cookies from strings and JSON.

/**
 * Parses a cookie string into a Cookie object
 * @param str - Cookie string to parse
 * @param options - Parsing options
 * @returns Parsed Cookie or undefined if parsing fails
 */
static parse(str: string, options?: ParseCookieOptions): Cookie | undefined;

/**
 * Deserializes a JSON representation into a Cookie object
 * @param str - JSON string or object to deserialize
 * @returns Cookie instance or undefined if deserialization fails
 */
static fromJSON(str: unknown): Cookie | undefined;

interface ParseCookieOptions {
  loose?: boolean; // Allow keyless cookies like =abc
}

/**
 * Array of property names that are serialized in toJSON()
 */
static readonly serializableProperties: readonly string[];

/**
 * @internal SameSite level mapping for context validation
 */
static readonly sameSiteLevel: {
  strict: 3;
  lax: 2;
  none: 1;
};

/**
 * @internal Canonical SameSite attribute values
 */
static readonly sameSiteCanonical: {
  strict: 'Strict';
  lax: 'Lax';
};

Usage Examples:

import { Cookie } from "tough-cookie";

// Parse Set-Cookie header
const setCookieHeader = 'session=abc123; Domain=example.com; Path=/; Secure; HttpOnly; Max-Age=3600';
const cookie = Cookie.parse(setCookieHeader);

// Parse with loose mode (allows keyless cookies)
const looseCookie = Cookie.parse('=value_only', { loose: true });

// Parse from JSON
const serialized = cookie?.toJSON();
const restored = Cookie.fromJSON(serialized);

// Check serializable properties
console.log(Cookie.serializableProperties); // Array of property names

Standalone Functions

Convenience functions for cookie operations.

/**
 * Convenience function that calls Cookie.parse()
 * @param str - Cookie string to parse
 * @param options - Parsing options
 * @returns Parsed Cookie or undefined
 */
function parse(str: string, options?: ParseCookieOptions): Cookie | undefined;

/**
 * Convenience function that calls Cookie.fromJSON()
 * @param str - JSON string or object to deserialize
 * @returns Cookie instance or undefined
 */
function fromJSON(str: unknown): Cookie | undefined;

/**
 * Comparison function for sorting cookies per RFC 6265 Section 5.4
 * - Longest path first
 * - Oldest creation time first  
 * - Lowest creation index first
 * @param a - First cookie to compare
 * @param b - Second cookie to compare
 * @returns Comparison result (-1, 0, 1)
 */
function cookieCompare(a: Cookie, b: Cookie): number;

Usage Examples:

import { parse, fromJSON, cookieCompare } from "tough-cookie";

// Use standalone parsing functions
const cookie1 = parse('name=value; Path=/app');
const cookie2 = parse('name=value; Path=/');

// Sort cookies according to RFC 6265
const cookies = [cookie1, cookie2].filter(Boolean);
cookies.sort(cookieCompare); // Longest path first

// Restore from JSON using standalone function
const jsonData = '{"key":"session","value":"abc123"}';
const restoredCookie = fromJSON(jsonData);

Types

type SerializedCookie = {
  key?: string;
  value?: string;
  [key: string]: unknown; // Other serializable properties
}

Install with Tessl CLI

npx tessl i tessl/npm-tough-cookie

docs

cookie-jar.md

cookie-operations.md

index.md

stores.md

utilities.md

tile.json