0
# Cookie Management
1
2
Complete cookie handling utilities for both client and server-side cookie operations with full RFC compliance.
3
4
## Capabilities
5
6
### getCookies
7
8
Extract cookies from HTTP request headers into a structured object.
9
10
```javascript { .api }
11
/**
12
* Extract cookies from HTTP headers
13
* @param headers - HTTP headers containing Cookie header
14
* @returns Object mapping cookie names to values
15
*/
16
function getCookies(headers: IncomingHttpHeaders): Record<string, string>;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
import { getCookies } from 'undici';
23
24
// Extract cookies from request headers
25
const requestHeaders = {
26
'cookie': 'session=abc123; theme=dark; lang=en'
27
};
28
29
const cookies = getCookies(requestHeaders);
30
console.log(cookies);
31
// {
32
// session: 'abc123',
33
// theme: 'dark',
34
// lang: 'en'
35
// }
36
37
// Handle encoded cookie values
38
const encodedHeaders = {
39
'cookie': 'data=%7B%22user%22%3A%22alice%22%7D; simple=value'
40
};
41
42
const encodedCookies = getCookies(encodedHeaders);
43
console.log(encodedCookies);
44
// {
45
// data: '{"user":"alice"}', // automatically decoded
46
// simple: 'value'
47
// }
48
49
// Handle empty or missing cookies
50
const emptyCookies = getCookies({});
51
console.log(emptyCookies); // {}
52
53
const noCookies = getCookies({ 'authorization': 'Bearer token' });
54
console.log(noCookies); // {}
55
```
56
57
### getSetCookies
58
59
Extract Set-Cookie headers from HTTP response headers as an array of cookie strings.
60
61
```javascript { .api }
62
/**
63
* Extract Set-Cookie headers from HTTP response headers
64
* @param headers - HTTP headers containing Set-Cookie headers
65
* @returns Array of Set-Cookie header values
66
*/
67
function getSetCookies(headers: IncomingHttpHeaders): string[];
68
```
69
70
**Usage Examples:**
71
72
```javascript
73
import { getSetCookies } from 'undici';
74
75
// Extract Set-Cookie headers from response
76
const responseHeaders = {
77
'set-cookie': [
78
'session=abc123; Path=/; HttpOnly; Secure',
79
'theme=dark; Path=/; Max-Age=86400',
80
'lang=en; Path=/; SameSite=Strict'
81
]
82
};
83
84
const setCookies = getSetCookies(responseHeaders);
85
console.log(setCookies);
86
// [
87
// 'session=abc123; Path=/; HttpOnly; Secure',
88
// 'theme=dark; Path=/; Max-Age=86400',
89
// 'lang=en; Path=/; SameSite=Strict'
90
// ]
91
92
// Handle single Set-Cookie header
93
const singleCookieHeaders = {
94
'set-cookie': 'token=xyz789; Path=/api; HttpOnly'
95
};
96
97
const singleSetCookie = getSetCookies(singleCookieHeaders);
98
console.log(singleSetCookie); // ['token=xyz789; Path=/api; HttpOnly']
99
100
// Handle missing Set-Cookie headers
101
const noSetCookies = getSetCookies({ 'content-type': 'application/json' });
102
console.log(noSetCookies); // []
103
```
104
105
### setCookie
106
107
Set a cookie in HTTP response headers with full attribute support.
108
109
```javascript { .api }
110
/**
111
* Set cookie in HTTP response headers
112
* @param headers - HTTP headers object to modify
113
* @param cookie - Cookie object with name, value, and attributes
114
*/
115
function setCookie(headers: OutgoingHttpHeaders, cookie: Cookie): void;
116
117
interface Cookie {
118
name: string;
119
value: string;
120
expires?: Date;
121
maxAge?: number;
122
domain?: string;
123
path?: string;
124
secure?: boolean;
125
httpOnly?: boolean;
126
sameSite?: 'Strict' | 'Lax' | 'None';
127
partitioned?: boolean;
128
priority?: 'Low' | 'Medium' | 'High';
129
}
130
```
131
132
**Usage Examples:**
133
134
```javascript
135
import { setCookie } from 'undici';
136
137
// Set basic cookie
138
const headers = {};
139
setCookie(headers, {
140
name: 'session',
141
value: 'abc123'
142
});
143
console.log(headers);
144
// { 'set-cookie': ['session=abc123'] }
145
146
// Set cookie with full attributes
147
setCookie(headers, {
148
name: 'auth_token',
149
value: 'xyz789',
150
expires: new Date(Date.now() + 86400000), // 24 hours
151
maxAge: 86400,
152
domain: '.example.com',
153
path: '/api',
154
secure: true,
155
httpOnly: true,
156
sameSite: 'Strict',
157
partitioned: true,
158
priority: 'High'
159
});
160
161
// Set multiple cookies
162
setCookie(headers, {
163
name: 'theme',
164
value: 'dark',
165
path: '/',
166
maxAge: 604800 // 7 days
167
});
168
169
setCookie(headers, {
170
name: 'lang',
171
value: 'en',
172
path: '/',
173
sameSite: 'Lax'
174
});
175
176
console.log(headers['set-cookie']);
177
// [
178
// 'session=abc123',
179
// 'auth_token=xyz789; Expires=...; Max-Age=86400; Domain=.example.com; Path=/api; Secure; HttpOnly; SameSite=Strict; Partitioned; Priority=High',
180
// 'theme=dark; Path=/; Max-Age=604800',
181
// 'lang=en; Path=/; SameSite=Lax'
182
// ]
183
```
184
185
### deleteCookie
186
187
Delete a cookie by setting it with an expired date and empty value.
188
189
```javascript { .api }
190
/**
191
* Delete cookie by setting expired cookie
192
* @param headers - HTTP headers object to modify
193
* @param name - Name of cookie to delete
194
* @param attributes - Optional cookie attributes (domain, path, etc.)
195
*/
196
function deleteCookie(
197
headers: OutgoingHttpHeaders,
198
name: string,
199
attributes?: CookieAttributes
200
): void;
201
202
interface CookieAttributes {
203
domain?: string;
204
path?: string;
205
secure?: boolean;
206
httpOnly?: boolean;
207
sameSite?: 'Strict' | 'Lax' | 'None';
208
partitioned?: boolean;
209
}
210
```
211
212
**Usage Examples:**
213
214
```javascript
215
import { deleteCookie } from 'undici';
216
217
// Delete basic cookie
218
const headers = {};
219
deleteCookie(headers, 'session');
220
console.log(headers);
221
// { 'set-cookie': ['session=; Expires=Thu, 01 Jan 1970 00:00:00 GMT'] }
222
223
// Delete cookie with specific attributes
224
deleteCookie(headers, 'auth_token', {
225
domain: '.example.com',
226
path: '/api',
227
secure: true,
228
httpOnly: true
229
});
230
231
console.log(headers['set-cookie']);
232
// [
233
// 'session=; Expires=Thu, 01 Jan 1970 00:00:00 GMT',
234
// 'auth_token=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Domain=.example.com; Path=/api; Secure; HttpOnly'
235
// ]
236
237
// Delete cookie matching original attributes
238
deleteCookie(headers, 'user_pref', {
239
path: '/dashboard',
240
sameSite: 'Strict'
241
});
242
```
243
244
### parseCookie
245
246
Parse a cookie string into a structured cookie object.
247
248
```javascript { .api }
249
/**
250
* Parse cookie string into structured object
251
* @param cookie - Cookie string to parse
252
* @returns Parsed cookie object
253
*/
254
function parseCookie(cookie: string): Cookie;
255
256
interface Cookie {
257
name: string;
258
value: string;
259
expires?: Date;
260
maxAge?: number;
261
domain?: string;
262
path?: string;
263
secure?: boolean;
264
httpOnly?: boolean;
265
sameSite?: 'Strict' | 'Lax' | 'None';
266
partitioned?: boolean;
267
priority?: 'Low' | 'Medium' | 'High';
268
}
269
```
270
271
**Usage Examples:**
272
273
```javascript
274
import { parseCookie } from 'undici';
275
276
// Parse simple cookie
277
const simpleCookie = parseCookie('session=abc123');
278
console.log(simpleCookie);
279
// {
280
// name: 'session',
281
// value: 'abc123'
282
// }
283
284
// Parse complex cookie with attributes
285
const complexCookie = parseCookie(
286
'auth_token=xyz789; Expires=Wed, 09 Jun 2024 10:18:14 GMT; Max-Age=86400; Domain=.example.com; Path=/api; Secure; HttpOnly; SameSite=Strict'
287
);
288
289
console.log(complexCookie);
290
// {
291
// name: 'auth_token',
292
// value: 'xyz789',
293
// expires: Date object,
294
// maxAge: 86400,
295
// domain: '.example.com',
296
// path: '/api',
297
// secure: true,
298
// httpOnly: true,
299
// sameSite: 'Strict'
300
// }
301
302
// Parse cookie with encoded value
303
const encodedCookie = parseCookie('data=%7B%22user%22%3A%22alice%22%7D; Path=/');
304
console.log(encodedCookie);
305
// {
306
// name: 'data',
307
// value: '{"user":"alice"}', // automatically decoded
308
// path: '/'
309
// }
310
311
// Parse cookie with priority and partitioned attributes
312
const modernCookie = parseCookie('tracking=disabled; SameSite=None; Secure; Partitioned; Priority=Low');
313
console.log(modernCookie);
314
// {
315
// name: 'tracking',
316
// value: 'disabled',
317
// sameSite: 'None',
318
// secure: true,
319
// partitioned: true,
320
// priority: 'Low'
321
// }
322
```
323
324
## Complete Cookie Workflow Examples
325
326
### Server-Side Cookie Management
327
328
```javascript
329
import { getCookies, setCookie, deleteCookie } from 'undici';
330
import { createServer } from 'http';
331
332
const server = createServer((req, res) => {
333
// Extract cookies from request
334
const cookies = getCookies(req.headers);
335
console.log('Request cookies:', cookies);
336
337
// Check for session cookie
338
if (!cookies.session) {
339
// Set new session cookie
340
setCookie(res.headers, {
341
name: 'session',
342
value: 'new_session_' + Date.now(),
343
maxAge: 86400, // 24 hours
344
httpOnly: true,
345
secure: true,
346
sameSite: 'Strict'
347
});
348
}
349
350
// Handle logout
351
if (req.url === '/logout') {
352
deleteCookie(res.headers, 'session', {
353
httpOnly: true,
354
secure: true
355
});
356
deleteCookie(res.headers, 'user_prefs');
357
}
358
359
// Set user preferences
360
if (req.url === '/set-theme') {
361
setCookie(res.headers, {
362
name: 'theme',
363
value: 'dark',
364
maxAge: 604800, // 7 days
365
path: '/'
366
});
367
}
368
369
res.end('Cookie management complete');
370
});
371
```
372
373
### Client-Side Cookie Processing
374
375
```javascript
376
import { fetch, getSetCookies } from 'undici';
377
378
// Make request and process cookies
379
const response = await fetch('https://api.example.com/login', {
380
method: 'POST',
381
headers: {
382
'Content-Type': 'application/json'
383
},
384
body: JSON.stringify({ username: 'alice', password: 'secret' })
385
});
386
387
// Extract Set-Cookie headers
388
const setCookieHeaders = getSetCookies(response.headers);
389
console.log('Server set cookies:', setCookieHeaders);
390
391
// Store cookies for subsequent requests
392
const cookieStore = new Map();
393
setCookieHeaders.forEach(cookieHeader => {
394
const cookie = parseCookie(cookieHeader);
395
cookieStore.set(cookie.name, cookie.value);
396
});
397
398
// Use cookies in next request
399
const cookieHeader = Array.from(cookieStore.entries())
400
.map(([name, value]) => `${name}=${value}`)
401
.join('; ');
402
403
const authenticatedResponse = await fetch('https://api.example.com/profile', {
404
headers: {
405
'Cookie': cookieHeader
406
}
407
});
408
```
409
410
## Types
411
412
```javascript { .api }
413
type IncomingHttpHeaders = Record<string, string | string[]>;
414
type OutgoingHttpHeaders = Record<string, string | string[] | number>;
415
```