RFC6265 Cookies and Cookie Jar for node.js
npx @tessl/cli install tessl/npm-tough-cookie@6.0.00
# Tough Cookie
1
2
Tough 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.
3
4
## Package Information
5
6
- **Package Name**: tough-cookie
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install tough-cookie`
10
11
## Core Imports
12
13
```typescript
14
import { Cookie, CookieJar, MemoryCookieStore, Store } from "tough-cookie";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { Cookie, CookieJar, MemoryCookieStore, Store } = require("tough-cookie");
21
```
22
23
Utility functions:
24
25
```typescript
26
import {
27
parse,
28
fromJSON,
29
canonicalDomain,
30
domainMatch,
31
pathMatch,
32
parseDate,
33
formatDate
34
} from "tough-cookie";
35
```
36
37
## Basic Usage
38
39
```typescript
40
import { Cookie, CookieJar } from "tough-cookie";
41
42
// Parse a cookie string
43
const cookie = Cookie.parse('name=value; Domain=example.com; Path=/; Secure');
44
45
// Create a cookie jar with default memory store
46
const jar = new CookieJar();
47
48
// Set a cookie from a Set-Cookie header
49
await jar.setCookie('session=abc123; HttpOnly; Secure', 'https://example.com/');
50
51
// Get cookies for a URL as Cookie objects
52
const cookies = await jar.getCookies('https://example.com/');
53
54
// Get cookies as a Cookie header string
55
const cookieHeader = await jar.getCookieString('https://example.com/');
56
57
// Create a cookie programmatically
58
const newCookie = new Cookie({
59
key: 'user_pref',
60
value: 'dark_mode',
61
domain: 'example.com',
62
path: '/',
63
secure: true,
64
httpOnly: false,
65
maxAge: 86400 // 1 day in seconds
66
});
67
```
68
69
## Architecture
70
71
Tough Cookie is built around several key components:
72
73
- **Cookie Class**: Individual cookie representation with RFC 6265 compliance, attribute validation, and serialization
74
- **CookieJar Class**: Main cookie management with RFC-compliant storage, retrieval, and domain/path matching
75
- **Store Interface**: Pluggable storage backend system with async/sync operation support
76
- **MemoryCookieStore**: Default in-memory store implementation with efficient indexing
77
- **Utility Functions**: Domain validation, path matching, date parsing, and cookie comparison functions
78
- **RFC 6265bis Support**: SameSite attributes, cookie prefixes (__Secure-, __Host-), and secure context handling
79
80
## Capabilities
81
82
### Cookie Operations
83
84
Core cookie parsing, creation, and manipulation functionality. Handle individual cookies with full RFC 6265 compliance including validation, serialization, and attribute management.
85
86
```typescript { .api }
87
// Parse cookie from string
88
function parse(str: string, options?: ParseCookieOptions): Cookie | undefined;
89
90
// Create cookie from JSON
91
function fromJSON(str: unknown): Cookie | undefined;
92
93
// Cookie comparison for sorting
94
function cookieCompare(a: Cookie, b: Cookie): number;
95
```
96
97
[Cookie Operations](./cookie-operations.md)
98
99
### Cookie Jar Management
100
101
Comprehensive cookie storage and retrieval with RFC-compliant domain and path matching, expiration handling, and security validation.
102
103
```typescript { .api }
104
// Set cookies with validation
105
setCookie(
106
cookie: string | Cookie,
107
url: string | URL,
108
options?: SetCookieOptions
109
): Promise<Cookie | undefined>;
110
111
// Get cookies for URL
112
getCookies(
113
url: string | URL,
114
options?: GetCookiesOptions
115
): Promise<Cookie[]>;
116
117
// Get cookie header string
118
getCookieString(
119
url: string | URL,
120
options?: GetCookiesOptions
121
): Promise<string>;
122
```
123
124
[Cookie Jar Management](./cookie-jar.md)
125
126
### Store Implementations
127
128
Pluggable storage system supporting both synchronous and asynchronous operations with complete CRUD functionality for cookie persistence.
129
130
```typescript { .api }
131
// Store base class
132
abstract class Store {
133
abstract findCookie(
134
domain: string | null,
135
path: string | null,
136
key: string | null
137
): Promise<Cookie | undefined>;
138
139
abstract putCookie(cookie: Cookie): Promise<void>;
140
abstract getAllCookies(): Promise<Cookie[]>;
141
}
142
143
// Memory store implementation
144
class MemoryCookieStore extends Store {
145
synchronous: boolean; // Always true
146
}
147
```
148
149
[Store Implementations](./stores.md)
150
151
### Utility Functions
152
153
Domain validation, path matching, date parsing, and other RFC-compliant utility functions for cookie processing.
154
155
```typescript { .api }
156
// Domain utilities
157
function canonicalDomain(domainName: string | null): string | undefined;
158
function domainMatch(domain?: string | null, cookieDomain?: string | null): boolean | undefined;
159
function getPublicSuffix(domain: string, options?: GetPublicSuffixOptions): string | undefined;
160
161
// Path utilities
162
function pathMatch(reqPath: string, cookiePath: string): boolean;
163
function defaultPath(path?: string | null): string;
164
165
// Date utilities
166
function parseDate(cookieDate: string | null): Date | undefined;
167
function formatDate(date: Date): string;
168
```
169
170
[Utility Functions](./utilities.md)
171
172
## Core Types
173
174
```typescript { .api }
175
// Cookie constructor options
176
interface CreateCookieOptions {
177
key?: string;
178
value?: string;
179
expires?: Date | 'Infinity' | null;
180
maxAge?: number | 'Infinity' | '-Infinity' | null;
181
domain?: string | null;
182
path?: string | null;
183
secure?: boolean;
184
httpOnly?: boolean;
185
extensions?: string[] | null;
186
creation?: Date | 'Infinity' | null;
187
hostOnly?: boolean | null;
188
pathIsDefault?: boolean | null;
189
lastAccessed?: Date | 'Infinity' | null;
190
sameSite?: string | undefined;
191
}
192
193
// Cookie parsing options
194
interface ParseCookieOptions {
195
loose?: boolean; // Allow keyless cookies like =abc
196
}
197
198
// CookieJar configuration
199
interface CreateCookieJarOptions {
200
rejectPublicSuffixes?: boolean; // Default: true
201
looseMode?: boolean; // Default: false
202
prefixSecurity?: 'strict' | 'silent' | 'unsafe-disabled'; // Default: 'silent'
203
allowSpecialUseDomain?: boolean; // Default: true
204
allowSecureOnLocal?: boolean; // Default: true
205
}
206
207
// Cookie setting options
208
interface SetCookieOptions {
209
loose?: boolean;
210
sameSiteContext?: 'strict' | 'lax' | 'none';
211
ignoreError?: boolean;
212
http?: boolean; // Default: true
213
now?: Date;
214
}
215
216
// Cookie retrieval options
217
interface GetCookiesOptions {
218
http?: boolean; // Default: true
219
expire?: boolean; // Default: true
220
allPaths?: boolean; // Default: false
221
sameSiteContext?: 'none' | 'lax' | 'strict';
222
sort?: boolean;
223
}
224
225
// Public suffix options
226
interface GetPublicSuffixOptions {
227
allowSpecialUseDomain?: boolean; // Default: false
228
ignoreError?: boolean; // Default: false
229
}
230
231
// Callback types
232
interface Callback<T> {
233
(error: Error, result?: never): void;
234
(error: null, result: T): void;
235
}
236
237
interface ErrorCallback {
238
(error: Error | null): void;
239
}
240
241
// Serialization types
242
type SerializedCookie = {
243
key?: string;
244
value?: string;
245
[key: string]: unknown;
246
}
247
248
interface SerializedCookieJar {
249
version: string;
250
storeType: string | null;
251
rejectPublicSuffixes: boolean;
252
[key: string]: unknown;
253
cookies: SerializedCookie[];
254
}
255
```