An HTTP/1.1 client, written from scratch for Node.js
—
Complete cookie handling utilities for both client and server-side cookie operations with full RFC compliance.
Extract cookies from HTTP request headers into a structured object.
/**
* Extract cookies from HTTP headers
* @param headers - HTTP headers containing Cookie header
* @returns Object mapping cookie names to values
*/
function getCookies(headers: IncomingHttpHeaders): Record<string, string>;Usage Examples:
import { getCookies } from 'undici';
// Extract cookies from request headers
const requestHeaders = {
'cookie': 'session=abc123; theme=dark; lang=en'
};
const cookies = getCookies(requestHeaders);
console.log(cookies);
// {
// session: 'abc123',
// theme: 'dark',
// lang: 'en'
// }
// Handle encoded cookie values
const encodedHeaders = {
'cookie': 'data=%7B%22user%22%3A%22alice%22%7D; simple=value'
};
const encodedCookies = getCookies(encodedHeaders);
console.log(encodedCookies);
// {
// data: '{"user":"alice"}', // automatically decoded
// simple: 'value'
// }
// Handle empty or missing cookies
const emptyCookies = getCookies({});
console.log(emptyCookies); // {}
const noCookies = getCookies({ 'authorization': 'Bearer token' });
console.log(noCookies); // {}Extract Set-Cookie headers from HTTP response headers as an array of cookie strings.
/**
* Extract Set-Cookie headers from HTTP response headers
* @param headers - HTTP headers containing Set-Cookie headers
* @returns Array of Set-Cookie header values
*/
function getSetCookies(headers: IncomingHttpHeaders): string[];Usage Examples:
import { getSetCookies } from 'undici';
// Extract Set-Cookie headers from response
const responseHeaders = {
'set-cookie': [
'session=abc123; Path=/; HttpOnly; Secure',
'theme=dark; Path=/; Max-Age=86400',
'lang=en; Path=/; SameSite=Strict'
]
};
const setCookies = getSetCookies(responseHeaders);
console.log(setCookies);
// [
// 'session=abc123; Path=/; HttpOnly; Secure',
// 'theme=dark; Path=/; Max-Age=86400',
// 'lang=en; Path=/; SameSite=Strict'
// ]
// Handle single Set-Cookie header
const singleCookieHeaders = {
'set-cookie': 'token=xyz789; Path=/api; HttpOnly'
};
const singleSetCookie = getSetCookies(singleCookieHeaders);
console.log(singleSetCookie); // ['token=xyz789; Path=/api; HttpOnly']
// Handle missing Set-Cookie headers
const noSetCookies = getSetCookies({ 'content-type': 'application/json' });
console.log(noSetCookies); // []Set a cookie in HTTP response headers with full attribute support.
/**
* Set cookie in HTTP response headers
* @param headers - HTTP headers object to modify
* @param cookie - Cookie object with name, value, and attributes
*/
function setCookie(headers: OutgoingHttpHeaders, cookie: Cookie): void;
interface Cookie {
name: string;
value: string;
expires?: Date;
maxAge?: number;
domain?: string;
path?: string;
secure?: boolean;
httpOnly?: boolean;
sameSite?: 'Strict' | 'Lax' | 'None';
partitioned?: boolean;
priority?: 'Low' | 'Medium' | 'High';
}Usage Examples:
import { setCookie } from 'undici';
// Set basic cookie
const headers = {};
setCookie(headers, {
name: 'session',
value: 'abc123'
});
console.log(headers);
// { 'set-cookie': ['session=abc123'] }
// Set cookie with full attributes
setCookie(headers, {
name: 'auth_token',
value: 'xyz789',
expires: new Date(Date.now() + 86400000), // 24 hours
maxAge: 86400,
domain: '.example.com',
path: '/api',
secure: true,
httpOnly: true,
sameSite: 'Strict',
partitioned: true,
priority: 'High'
});
// Set multiple cookies
setCookie(headers, {
name: 'theme',
value: 'dark',
path: '/',
maxAge: 604800 // 7 days
});
setCookie(headers, {
name: 'lang',
value: 'en',
path: '/',
sameSite: 'Lax'
});
console.log(headers['set-cookie']);
// [
// 'session=abc123',
// 'auth_token=xyz789; Expires=...; Max-Age=86400; Domain=.example.com; Path=/api; Secure; HttpOnly; SameSite=Strict; Partitioned; Priority=High',
// 'theme=dark; Path=/; Max-Age=604800',
// 'lang=en; Path=/; SameSite=Lax'
// ]Delete a cookie by setting it with an expired date and empty value.
/**
* Delete cookie by setting expired cookie
* @param headers - HTTP headers object to modify
* @param name - Name of cookie to delete
* @param attributes - Optional cookie attributes (domain, path, etc.)
*/
function deleteCookie(
headers: OutgoingHttpHeaders,
name: string,
attributes?: CookieAttributes
): void;
interface CookieAttributes {
domain?: string;
path?: string;
secure?: boolean;
httpOnly?: boolean;
sameSite?: 'Strict' | 'Lax' | 'None';
partitioned?: boolean;
}Usage Examples:
import { deleteCookie } from 'undici';
// Delete basic cookie
const headers = {};
deleteCookie(headers, 'session');
console.log(headers);
// { 'set-cookie': ['session=; Expires=Thu, 01 Jan 1970 00:00:00 GMT'] }
// Delete cookie with specific attributes
deleteCookie(headers, 'auth_token', {
domain: '.example.com',
path: '/api',
secure: true,
httpOnly: true
});
console.log(headers['set-cookie']);
// [
// 'session=; Expires=Thu, 01 Jan 1970 00:00:00 GMT',
// 'auth_token=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Domain=.example.com; Path=/api; Secure; HttpOnly'
// ]
// Delete cookie matching original attributes
deleteCookie(headers, 'user_pref', {
path: '/dashboard',
sameSite: 'Strict'
});Parse a cookie string into a structured cookie object.
/**
* Parse cookie string into structured object
* @param cookie - Cookie string to parse
* @returns Parsed cookie object
*/
function parseCookie(cookie: string): Cookie;
interface Cookie {
name: string;
value: string;
expires?: Date;
maxAge?: number;
domain?: string;
path?: string;
secure?: boolean;
httpOnly?: boolean;
sameSite?: 'Strict' | 'Lax' | 'None';
partitioned?: boolean;
priority?: 'Low' | 'Medium' | 'High';
}Usage Examples:
import { parseCookie } from 'undici';
// Parse simple cookie
const simpleCookie = parseCookie('session=abc123');
console.log(simpleCookie);
// {
// name: 'session',
// value: 'abc123'
// }
// Parse complex cookie with attributes
const complexCookie = parseCookie(
'auth_token=xyz789; Expires=Wed, 09 Jun 2024 10:18:14 GMT; Max-Age=86400; Domain=.example.com; Path=/api; Secure; HttpOnly; SameSite=Strict'
);
console.log(complexCookie);
// {
// name: 'auth_token',
// value: 'xyz789',
// expires: Date object,
// maxAge: 86400,
// domain: '.example.com',
// path: '/api',
// secure: true,
// httpOnly: true,
// sameSite: 'Strict'
// }
// Parse cookie with encoded value
const encodedCookie = parseCookie('data=%7B%22user%22%3A%22alice%22%7D; Path=/');
console.log(encodedCookie);
// {
// name: 'data',
// value: '{"user":"alice"}', // automatically decoded
// path: '/'
// }
// Parse cookie with priority and partitioned attributes
const modernCookie = parseCookie('tracking=disabled; SameSite=None; Secure; Partitioned; Priority=Low');
console.log(modernCookie);
// {
// name: 'tracking',
// value: 'disabled',
// sameSite: 'None',
// secure: true,
// partitioned: true,
// priority: 'Low'
// }import { getCookies, setCookie, deleteCookie } from 'undici';
import { createServer } from 'http';
const server = createServer((req, res) => {
// Extract cookies from request
const cookies = getCookies(req.headers);
console.log('Request cookies:', cookies);
// Check for session cookie
if (!cookies.session) {
// Set new session cookie
setCookie(res.headers, {
name: 'session',
value: 'new_session_' + Date.now(),
maxAge: 86400, // 24 hours
httpOnly: true,
secure: true,
sameSite: 'Strict'
});
}
// Handle logout
if (req.url === '/logout') {
deleteCookie(res.headers, 'session', {
httpOnly: true,
secure: true
});
deleteCookie(res.headers, 'user_prefs');
}
// Set user preferences
if (req.url === '/set-theme') {
setCookie(res.headers, {
name: 'theme',
value: 'dark',
maxAge: 604800, // 7 days
path: '/'
});
}
res.end('Cookie management complete');
});import { fetch, getSetCookies } from 'undici';
// Make request and process cookies
const response = await fetch('https://api.example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'alice', password: 'secret' })
});
// Extract Set-Cookie headers
const setCookieHeaders = getSetCookies(response.headers);
console.log('Server set cookies:', setCookieHeaders);
// Store cookies for subsequent requests
const cookieStore = new Map();
setCookieHeaders.forEach(cookieHeader => {
const cookie = parseCookie(cookieHeader);
cookieStore.set(cookie.name, cookie.value);
});
// Use cookies in next request
const cookieHeader = Array.from(cookieStore.entries())
.map(([name, value]) => `${name}=${value}`)
.join('; ');
const authenticatedResponse = await fetch('https://api.example.com/profile', {
headers: {
'Cookie': cookieHeader
}
});type IncomingHttpHeaders = Record<string, string | string[]>;
type OutgoingHttpHeaders = Record<string, string | string[] | number>;Install with Tessl CLI
npx tessl i tessl/npm-undici