0
# Cookie Operations
1
2
Core cookie parsing, creation, and manipulation functionality providing RFC 6265-compliant handling of individual cookies including validation, serialization, and attribute management.
3
4
## Capabilities
5
6
### Cookie Class
7
8
The main Cookie class represents an HTTP cookie with full RFC 6265 compliance.
9
10
```typescript { .api }
11
/**
12
* Creates a new Cookie instance with configurable properties
13
* @param options - Cookie configuration options
14
*/
15
class Cookie {
16
constructor(options?: CreateCookieOptions);
17
18
// Core properties
19
key: string;
20
value: string;
21
expires: Date | 'Infinity' | null;
22
maxAge: number | 'Infinity' | '-Infinity' | null;
23
domain: string | null;
24
path: string | null;
25
secure: boolean;
26
httpOnly: boolean;
27
extensions: string[] | null;
28
creation: Date | 'Infinity' | null;
29
creationIndex: number;
30
hostOnly: boolean | null;
31
pathIsDefault: boolean | null;
32
lastAccessed: Date | 'Infinity' | null;
33
sameSite: string | undefined;
34
35
// Methods
36
setExpires(exp: string | Date): void;
37
setMaxAge(age: number): void;
38
cookieString(): string;
39
toString(): string;
40
TTL(now?: number): number;
41
expiryTime(now?: Date): number | undefined;
42
expiryDate(now?: Date): Date | undefined;
43
isPersistent(): boolean;
44
canonicalizedDomain(): string | undefined;
45
cdomain(): string | undefined;
46
validate(): boolean;
47
clone(): Cookie | undefined;
48
toJSON(): SerializedCookie;
49
}
50
51
interface CreateCookieOptions {
52
key?: string;
53
value?: string;
54
expires?: Date | 'Infinity' | null;
55
maxAge?: number | 'Infinity' | '-Infinity' | null;
56
domain?: string | null;
57
path?: string | null;
58
secure?: boolean;
59
httpOnly?: boolean;
60
extensions?: string[] | null;
61
creation?: Date | 'Infinity' | null;
62
hostOnly?: boolean | null;
63
pathIsDefault?: boolean | null;
64
lastAccessed?: Date | 'Infinity' | null;
65
sameSite?: string | undefined;
66
}
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import { Cookie } from "tough-cookie";
73
74
// Create a simple cookie
75
const cookie = new Cookie({
76
key: 'session',
77
value: 'abc123',
78
domain: 'example.com',
79
path: '/',
80
secure: true,
81
httpOnly: true,
82
maxAge: 3600 // 1 hour
83
});
84
85
// Create a cookie with SameSite
86
const csrfCookie = new Cookie({
87
key: 'csrf_token',
88
value: 'xyz789',
89
domain: 'example.com',
90
path: '/',
91
secure: true,
92
sameSite: 'strict'
93
});
94
95
// Set expiration
96
cookie.setExpires(new Date(Date.now() + 86400000)); // 24 hours
97
98
// Get string representations
99
const cookieHeader = cookie.cookieString(); // "session=abc123"
100
const setCookieHeader = cookie.toString(); // "session=abc123; Domain=example.com; Path=/; Secure; HttpOnly; Max-Age=3600"
101
```
102
103
### Cookie Attribute Methods
104
105
Methods for managing cookie attributes and metadata.
106
107
```typescript { .api }
108
/**
109
* Sets the 'Expires' attribute. String values are parsed with parseDate()
110
* @param exp - Expiration date as Date object or parseable string
111
*/
112
setExpires(exp: string | Date): void;
113
114
/**
115
* Sets the 'Max-Age' attribute in seconds. Handles Infinity and -Infinity values
116
* @param age - Age in seconds
117
*/
118
setMaxAge(age: number): void;
119
120
/**
121
* Computes time-to-live in milliseconds. Returns Infinity for non-expiring cookies, 0 for expired
122
* @param now - Current time in milliseconds (defaults to Date.now())
123
* @returns TTL in milliseconds
124
*/
125
TTL(now?: number): number;
126
127
/**
128
* Computes absolute expiry time in milliseconds since epoch
129
* @param now - Current date for calculation (defaults to new Date())
130
* @returns Expiry time in milliseconds
131
*/
132
expiryTime(now?: Date): number | undefined;
133
134
/**
135
* Returns expiry time as a Date object
136
* @param now - Current date for calculation (defaults to new Date())
137
* @returns Expiry date or undefined if never expires
138
*/
139
expiryDate(now?: Date): Date | undefined;
140
141
/**
142
* Indicates if cookie has been persisted to a store
143
* @returns True if cookie is persistent (has expires or maxAge)
144
*/
145
isPersistent(): boolean;
146
147
/**
148
* Returns canonical domain name using canonicalDomain()
149
* @returns Canonicalized domain or undefined
150
*/
151
canonicalizedDomain(): string | undefined;
152
153
/**
154
* Validates cookie attributes for semantic correctness
155
* @returns True if cookie is valid according to RFC 6265
156
*/
157
validate(): boolean;
158
159
/**
160
* Creates a deep clone of the cookie
161
* @returns Cloned cookie or undefined if cloning fails
162
*/
163
clone(): Cookie | undefined;
164
```
165
166
### Cookie String Methods
167
168
Methods for converting cookies to and from string representations.
169
170
```typescript { .api }
171
/**
172
* Encodes to a Cookie header value (key=value format)
173
* @returns Cookie header string
174
*/
175
cookieString(): string;
176
177
/**
178
* Encodes to a Set-Cookie header value with all attributes
179
* @returns Set-Cookie header string
180
*/
181
toString(): string;
182
183
/**
184
* Serializes cookie to JSON-compatible object
185
* @returns Serialized cookie object
186
*/
187
toJSON(): SerializedCookie;
188
```
189
190
**Usage Examples:**
191
192
```typescript
193
import { Cookie } from "tough-cookie";
194
195
const cookie = new Cookie({
196
key: 'user_pref',
197
value: 'theme=dark',
198
domain: 'example.com',
199
path: '/',
200
secure: true,
201
httpOnly: false,
202
maxAge: 86400
203
});
204
205
// Check expiration
206
const ttl = cookie.TTL(); // Time to live in milliseconds
207
const isExpired = ttl === 0;
208
const expiryDate = cookie.expiryDate(); // Date object
209
210
// Validate cookie
211
const isValid = cookie.validate();
212
213
// Get string formats
214
const forCookieHeader = cookie.cookieString(); // "user_pref=theme=dark"
215
const forSetCookieHeader = cookie.toString(); // Full Set-Cookie string
216
217
// Clone and modify
218
const cloned = cookie.clone();
219
if (cloned) {
220
cloned.setMaxAge(7200); // Extend expiration
221
}
222
```
223
224
### Cookie Parsing
225
226
Static methods for parsing cookies from strings and JSON.
227
228
```typescript { .api }
229
/**
230
* Parses a cookie string into a Cookie object
231
* @param str - Cookie string to parse
232
* @param options - Parsing options
233
* @returns Parsed Cookie or undefined if parsing fails
234
*/
235
static parse(str: string, options?: ParseCookieOptions): Cookie | undefined;
236
237
/**
238
* Deserializes a JSON representation into a Cookie object
239
* @param str - JSON string or object to deserialize
240
* @returns Cookie instance or undefined if deserialization fails
241
*/
242
static fromJSON(str: unknown): Cookie | undefined;
243
244
interface ParseCookieOptions {
245
loose?: boolean; // Allow keyless cookies like =abc
246
}
247
248
/**
249
* Array of property names that are serialized in toJSON()
250
*/
251
static readonly serializableProperties: readonly string[];
252
253
/**
254
* @internal SameSite level mapping for context validation
255
*/
256
static readonly sameSiteLevel: {
257
strict: 3;
258
lax: 2;
259
none: 1;
260
};
261
262
/**
263
* @internal Canonical SameSite attribute values
264
*/
265
static readonly sameSiteCanonical: {
266
strict: 'Strict';
267
lax: 'Lax';
268
};
269
```
270
271
**Usage Examples:**
272
273
```typescript
274
import { Cookie } from "tough-cookie";
275
276
// Parse Set-Cookie header
277
const setCookieHeader = 'session=abc123; Domain=example.com; Path=/; Secure; HttpOnly; Max-Age=3600';
278
const cookie = Cookie.parse(setCookieHeader);
279
280
// Parse with loose mode (allows keyless cookies)
281
const looseCookie = Cookie.parse('=value_only', { loose: true });
282
283
// Parse from JSON
284
const serialized = cookie?.toJSON();
285
const restored = Cookie.fromJSON(serialized);
286
287
// Check serializable properties
288
console.log(Cookie.serializableProperties); // Array of property names
289
```
290
291
### Standalone Functions
292
293
Convenience functions for cookie operations.
294
295
```typescript { .api }
296
/**
297
* Convenience function that calls Cookie.parse()
298
* @param str - Cookie string to parse
299
* @param options - Parsing options
300
* @returns Parsed Cookie or undefined
301
*/
302
function parse(str: string, options?: ParseCookieOptions): Cookie | undefined;
303
304
/**
305
* Convenience function that calls Cookie.fromJSON()
306
* @param str - JSON string or object to deserialize
307
* @returns Cookie instance or undefined
308
*/
309
function fromJSON(str: unknown): Cookie | undefined;
310
311
/**
312
* Comparison function for sorting cookies per RFC 6265 Section 5.4
313
* - Longest path first
314
* - Oldest creation time first
315
* - Lowest creation index first
316
* @param a - First cookie to compare
317
* @param b - Second cookie to compare
318
* @returns Comparison result (-1, 0, 1)
319
*/
320
function cookieCompare(a: Cookie, b: Cookie): number;
321
```
322
323
**Usage Examples:**
324
325
```typescript
326
import { parse, fromJSON, cookieCompare } from "tough-cookie";
327
328
// Use standalone parsing functions
329
const cookie1 = parse('name=value; Path=/app');
330
const cookie2 = parse('name=value; Path=/');
331
332
// Sort cookies according to RFC 6265
333
const cookies = [cookie1, cookie2].filter(Boolean);
334
cookies.sort(cookieCompare); // Longest path first
335
336
// Restore from JSON using standalone function
337
const jsonData = '{"key":"session","value":"abc123"}';
338
const restoredCookie = fromJSON(jsonData);
339
```
340
341
## Types
342
343
```typescript { .api }
344
type SerializedCookie = {
345
key?: string;
346
value?: string;
347
[key: string]: unknown; // Other serializable properties
348
}
349
```