0
# Cookie Management
1
2
HTTP cookie parsing, manipulation, and header integration utilities. These functions provide comprehensive cookie management capabilities for both client and server-side applications with full RFC compliance.
3
4
## Capabilities
5
6
### Cookie Interface
7
8
Core cookie data structure representing all standard cookie attributes.
9
10
```typescript { .api }
11
/**
12
* Represents an HTTP cookie with all standard attributes
13
*/
14
interface Cookie {
15
/** Cookie name */
16
name: string;
17
18
/** Cookie value */
19
value: string;
20
21
/** Expiration date or timestamp */
22
expires?: Date | number;
23
24
/** Maximum age in seconds */
25
maxAge?: number;
26
27
/** Domain scope for the cookie */
28
domain?: string;
29
30
/** Path scope for the cookie */
31
path?: string;
32
33
/** Secure flag - only send over HTTPS */
34
secure?: boolean;
35
36
/** HttpOnly flag - not accessible via JavaScript */
37
httpOnly?: boolean;
38
39
/** SameSite attribute for CSRF protection */
40
sameSite?: 'Strict' | 'Lax' | 'None';
41
42
/** Unparsed attributes for extensions */
43
unparsed?: string[];
44
}
45
```
46
47
### Get Cookies
48
49
Extract cookies from request headers into a simple key-value object.
50
51
```typescript { .api }
52
/**
53
* Parse cookies from Cookie header into key-value pairs
54
* @param headers - Headers object containing Cookie header
55
* @returns Object with cookie names as keys and values
56
*/
57
function getCookies(headers: Headers): Record<string, string>;
58
```
59
60
**Usage Examples:**
61
62
```typescript
63
import { getCookies } from "undici-types";
64
65
// From request headers
66
const headers = new Headers({
67
"cookie": "sessionId=abc123; theme=dark; lang=en"
68
});
69
70
const cookies = getCookies(headers);
71
console.log(cookies);
72
// { sessionId: "abc123", theme: "dark", lang: "en" }
73
74
// Access specific cookies
75
if (cookies.sessionId) {
76
console.log("User session:", cookies.sessionId);
77
}
78
79
// Check for presence
80
if ("theme" in cookies) {
81
console.log("User theme:", cookies.theme);
82
}
83
```
84
85
### Get Set-Cookie Headers
86
87
Parse Set-Cookie headers into structured cookie objects with all attributes.
88
89
```typescript { .api }
90
/**
91
* Parse Set-Cookie headers into array of Cookie objects
92
* @param headers - Headers object containing Set-Cookie headers
93
* @returns Array of parsed Cookie objects with all attributes
94
*/
95
function getSetCookies(headers: Headers): Cookie[];
96
```
97
98
**Usage Examples:**
99
100
```typescript
101
import { getSetCookies } from "undici-types";
102
103
// From response headers with multiple Set-Cookie headers
104
const headers = new Headers();
105
headers.append("set-cookie", "sessionId=abc123; Path=/; HttpOnly; Secure");
106
headers.append("set-cookie", "theme=dark; Max-Age=86400; SameSite=Lax");
107
headers.append("set-cookie", "lang=en; Domain=.example.com; Expires=Wed, 09 Jun 2025 10:18:14 GMT");
108
109
const setCookies = getSetCookies(headers);
110
console.log(setCookies);
111
// [
112
// {
113
// name: "sessionId",
114
// value: "abc123",
115
// path: "/",
116
// httpOnly: true,
117
// secure: true
118
// },
119
// {
120
// name: "theme",
121
// value: "dark",
122
// maxAge: 86400,
123
// sameSite: "Lax"
124
// },
125
// {
126
// name: "lang",
127
// value: "en",
128
// domain: ".example.com",
129
// expires: new Date("Wed, 09 Jun 2025 10:18:14 GMT")
130
// }
131
// ]
132
133
// Process each cookie
134
setCookies.forEach(cookie => {
135
console.log(`Cookie: ${cookie.name} = ${cookie.value}`);
136
if (cookie.secure) {
137
console.log(" ⚠️ Secure cookie - HTTPS only");
138
}
139
if (cookie.httpOnly) {
140
console.log(" 🔒 HttpOnly - not accessible to JavaScript");
141
}
142
});
143
```
144
145
### Set Cookie
146
147
Add a cookie to response headers with proper formatting.
148
149
```typescript { .api }
150
/**
151
* Add a cookie to headers using Set-Cookie format
152
* @param headers - Headers object to add Set-Cookie header to
153
* @param cookie - Cookie object to serialize and add
154
*/
155
function setCookie(headers: Headers, cookie: Cookie): void;
156
```
157
158
**Usage Examples:**
159
160
```typescript
161
import { setCookie } from "undici-types";
162
163
const headers = new Headers();
164
165
// Set simple cookie
166
setCookie(headers, {
167
name: "userId",
168
value: "12345"
169
});
170
171
// Set cookie with security attributes
172
setCookie(headers, {
173
name: "authToken",
174
value: "jwt-token-here",
175
httpOnly: true,
176
secure: true,
177
sameSite: "Strict",
178
path: "/api",
179
maxAge: 3600 // 1 hour
180
});
181
182
// Set cookie with domain and expiration
183
setCookie(headers, {
184
name: "preferences",
185
value: JSON.stringify({ theme: "dark", lang: "en" }),
186
domain: ".example.com",
187
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
188
sameSite: "Lax"
189
});
190
191
// View generated headers
192
console.log(headers.get("set-cookie"));
193
// Multiple Set-Cookie headers will be properly formatted
194
195
// Use in HTTP response
196
const response = new Response("Success", {
197
headers: headers
198
});
199
```
200
201
### Delete Cookie
202
203
Remove a cookie by setting it to expire immediately.
204
205
```typescript { .api }
206
/**
207
* Delete a cookie by setting expiration to past date
208
* @param headers - Headers object to add deletion Set-Cookie header to
209
* @param name - Name of cookie to delete
210
* @param attributes - Optional domain and path attributes to match existing cookie
211
*/
212
function deleteCookie(
213
headers: Headers,
214
name: string,
215
attributes?: {
216
name?: string;
217
domain?: string;
218
path?: string;
219
}
220
): void;
221
```
222
223
**Usage Examples:**
224
225
```typescript
226
import { deleteCookie } from "undici-types";
227
228
const headers = new Headers();
229
230
// Delete simple cookie
231
deleteCookie(headers, "sessionId");
232
233
// Delete cookie with specific domain/path
234
deleteCookie(headers, "authToken", {
235
domain: ".example.com",
236
path: "/api"
237
});
238
239
// Delete multiple cookies
240
const cookiesToDelete = ["sessionId", "authToken", "preferences"];
241
cookiesToDelete.forEach(name => {
242
deleteCookie(headers, name);
243
});
244
245
// View deletion headers
246
console.log(headers.getSetCookie());
247
// ["sessionId=; Expires=Thu, 01 Jan 1970 00:00:00 GMT", ...]
248
249
// Use in logout response
250
const logoutResponse = new Response("Logged out", {
251
headers: headers
252
});
253
```
254
255
### Parse Cookie String
256
257
Parse a single cookie string into a structured Cookie object.
258
259
```typescript { .api }
260
/**
261
* Parse a single Set-Cookie header value into a Cookie object
262
* @param cookie - Set-Cookie header value string to parse
263
* @returns Parsed Cookie object or null if parsing fails
264
*/
265
function parseCookie(cookie: string): Cookie | null;
266
```
267
268
**Usage Examples:**
269
270
```typescript
271
import { parseCookie } from "undici-types";
272
273
// Parse complex cookie string
274
const cookieString = "sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=3600";
275
const cookie = parseCookie(cookieString);
276
277
if (cookie) {
278
console.log(cookie);
279
// {
280
// name: "sessionId",
281
// value: "abc123",
282
// path: "/",
283
// httpOnly: true,
284
// secure: true,
285
// sameSite: "Strict",
286
// maxAge: 3600
287
// }
288
}
289
290
// Parse cookie with expiration date
291
const expiringCookie = parseCookie("theme=dark; Expires=Wed, 09 Jun 2025 10:18:14 GMT; Domain=.example.com");
292
if (expiringCookie) {
293
console.log(`Cookie expires: ${expiringCookie.expires}`);
294
console.log(`Domain: ${expiringCookie.domain}`);
295
}
296
297
// Handle invalid cookie strings
298
const invalid = parseCookie("invalid-cookie-format");
299
if (invalid === null) {
300
console.log("Failed to parse cookie string");
301
}
302
303
// Batch parse multiple cookie strings
304
const cookieStrings = [
305
"user=john; Max-Age=86400",
306
"session=xyz789; HttpOnly; Secure",
307
"invalid=",
308
];
309
310
const parsed = cookieStrings
311
.map(parseCookie)
312
.filter(cookie => cookie !== null);
313
314
console.log(`Successfully parsed ${parsed.length} cookies`);
315
```
316
317
## Integration Examples
318
319
### Server-Side Cookie Handling
320
321
```typescript
322
import { getCookies, setCookie, deleteCookie } from "undici-types";
323
324
// Express-like middleware example
325
function handleCookies(request: Request): Response {
326
// Read incoming cookies
327
const cookies = getCookies(request.headers);
328
329
const headers = new Headers();
330
331
// Check authentication
332
if (!cookies.sessionId) {
333
// Set session cookie
334
setCookie(headers, {
335
name: "sessionId",
336
value: generateSessionId(),
337
httpOnly: true,
338
secure: true,
339
sameSite: "Strict",
340
maxAge: 86400 // 24 hours
341
});
342
}
343
344
// Handle logout
345
if (request.url.includes('/logout')) {
346
deleteCookie(headers, "sessionId");
347
deleteCookie(headers, "authToken");
348
}
349
350
return new Response("OK", { headers });
351
}
352
```
353
354
### Client-Side Cookie Management
355
356
```typescript
357
import { getSetCookies, Cookie } from "undici-types";
358
359
// Handle response cookies
360
async function handleApiResponse(response: Response) {
361
const setCookies = getSetCookies(response.headers);
362
363
setCookies.forEach(cookie => {
364
// Log cookie details
365
console.log(`Received cookie: ${cookie.name}`);
366
367
// Handle security warnings
368
if (cookie.secure && !location.protocol.startsWith('https:')) {
369
console.warn('Secure cookie received over HTTP');
370
}
371
372
// Store cookie info for debugging
373
if (cookie.sameSite === 'None' && !cookie.secure) {
374
console.error('SameSite=None requires Secure attribute');
375
}
376
});
377
}
378
```