CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-undici-types

A stand-alone types package for Undici HTTP client library

Pending
Overview
Eval results
Files

cookies.mddocs/

Cookie Management

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.

Capabilities

Cookie Interface

Core cookie data structure representing all standard cookie attributes.

/**
 * Represents an HTTP cookie with all standard attributes
 */
interface Cookie {
  /** Cookie name */
  name: string;
  
  /** Cookie value */
  value: string;
  
  /** Expiration date or timestamp */
  expires?: Date | number;
  
  /** Maximum age in seconds */
  maxAge?: number;
  
  /** Domain scope for the cookie */
  domain?: string;
  
  /** Path scope for the cookie */
  path?: string;
  
  /** Secure flag - only send over HTTPS */
  secure?: boolean;
  
  /** HttpOnly flag - not accessible via JavaScript */
  httpOnly?: boolean;
  
  /** SameSite attribute for CSRF protection */
  sameSite?: 'Strict' | 'Lax' | 'None';
  
  /** Unparsed attributes for extensions */
  unparsed?: string[];
}

Get Cookies

Extract cookies from request headers into a simple key-value object.

/**
 * Parse cookies from Cookie header into key-value pairs
 * @param headers - Headers object containing Cookie header
 * @returns Object with cookie names as keys and values
 */
function getCookies(headers: Headers): Record<string, string>;

Usage Examples:

import { getCookies } from "undici-types";

// From request headers
const headers = new Headers({
  "cookie": "sessionId=abc123; theme=dark; lang=en"
});

const cookies = getCookies(headers);
console.log(cookies);
// { sessionId: "abc123", theme: "dark", lang: "en" }

// Access specific cookies
if (cookies.sessionId) {
  console.log("User session:", cookies.sessionId);
}

// Check for presence
if ("theme" in cookies) {
  console.log("User theme:", cookies.theme);
}

Get Set-Cookie Headers

Parse Set-Cookie headers into structured cookie objects with all attributes.

/**
 * Parse Set-Cookie headers into array of Cookie objects
 * @param headers - Headers object containing Set-Cookie headers
 * @returns Array of parsed Cookie objects with all attributes
 */
function getSetCookies(headers: Headers): Cookie[];

Usage Examples:

import { getSetCookies } from "undici-types";

// From response headers with multiple Set-Cookie headers
const headers = new Headers();
headers.append("set-cookie", "sessionId=abc123; Path=/; HttpOnly; Secure");
headers.append("set-cookie", "theme=dark; Max-Age=86400; SameSite=Lax");
headers.append("set-cookie", "lang=en; Domain=.example.com; Expires=Wed, 09 Jun 2025 10:18:14 GMT");

const setCookies = getSetCookies(headers);
console.log(setCookies);
// [
//   {
//     name: "sessionId",
//     value: "abc123",
//     path: "/",
//     httpOnly: true,
//     secure: true
//   },
//   {
//     name: "theme", 
//     value: "dark",
//     maxAge: 86400,
//     sameSite: "Lax"
//   },
//   {
//     name: "lang",
//     value: "en", 
//     domain: ".example.com",
//     expires: new Date("Wed, 09 Jun 2025 10:18:14 GMT")
//   }
// ]

// Process each cookie
setCookies.forEach(cookie => {
  console.log(`Cookie: ${cookie.name} = ${cookie.value}`);
  if (cookie.secure) {
    console.log("  ⚠️  Secure cookie - HTTPS only");
  }
  if (cookie.httpOnly) {
    console.log("  🔒 HttpOnly - not accessible to JavaScript");
  }
});

Set Cookie

Add a cookie to response headers with proper formatting.

/**
 * Add a cookie to headers using Set-Cookie format
 * @param headers - Headers object to add Set-Cookie header to
 * @param cookie - Cookie object to serialize and add
 */
function setCookie(headers: Headers, cookie: Cookie): void;

Usage Examples:

import { setCookie } from "undici-types";

const headers = new Headers();

// Set simple cookie
setCookie(headers, {
  name: "userId",
  value: "12345"
});

// Set cookie with security attributes
setCookie(headers, {
  name: "authToken",
  value: "jwt-token-here",
  httpOnly: true,
  secure: true,
  sameSite: "Strict",
  path: "/api",
  maxAge: 3600 // 1 hour
});

// Set cookie with domain and expiration
setCookie(headers, {
  name: "preferences",
  value: JSON.stringify({ theme: "dark", lang: "en" }),
  domain: ".example.com",
  expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
  sameSite: "Lax"
});

// View generated headers
console.log(headers.get("set-cookie"));
// Multiple Set-Cookie headers will be properly formatted

// Use in HTTP response
const response = new Response("Success", {
  headers: headers
});

Delete Cookie

Remove a cookie by setting it to expire immediately.

/**
 * Delete a cookie by setting expiration to past date
 * @param headers - Headers object to add deletion Set-Cookie header to
 * @param name - Name of cookie to delete
 * @param attributes - Optional domain and path attributes to match existing cookie
 */
function deleteCookie(
  headers: Headers, 
  name: string, 
  attributes?: { 
    name?: string; 
    domain?: string; 
    path?: string; 
  }
): void;

Usage Examples:

import { deleteCookie } from "undici-types";

const headers = new Headers();

// Delete simple cookie
deleteCookie(headers, "sessionId");

// Delete cookie with specific domain/path
deleteCookie(headers, "authToken", {
  domain: ".example.com",
  path: "/api"
});

// Delete multiple cookies
const cookiesToDelete = ["sessionId", "authToken", "preferences"];
cookiesToDelete.forEach(name => {
  deleteCookie(headers, name);
});

// View deletion headers
console.log(headers.getSetCookie());
// ["sessionId=; Expires=Thu, 01 Jan 1970 00:00:00 GMT", ...]

// Use in logout response
const logoutResponse = new Response("Logged out", {
  headers: headers
});

Parse Cookie String

Parse a single cookie string into a structured Cookie object.

/**
 * Parse a single Set-Cookie header value into a Cookie object
 * @param cookie - Set-Cookie header value string to parse
 * @returns Parsed Cookie object or null if parsing fails
 */
function parseCookie(cookie: string): Cookie | null;

Usage Examples:

import { parseCookie } from "undici-types";

// Parse complex cookie string
const cookieString = "sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=3600";
const cookie = parseCookie(cookieString);

if (cookie) {
  console.log(cookie);
  // {
  //   name: "sessionId",
  //   value: "abc123", 
  //   path: "/",
  //   httpOnly: true,
  //   secure: true,
  //   sameSite: "Strict",
  //   maxAge: 3600
  // }
}

// Parse cookie with expiration date
const expiringCookie = parseCookie("theme=dark; Expires=Wed, 09 Jun 2025 10:18:14 GMT; Domain=.example.com");
if (expiringCookie) {
  console.log(`Cookie expires: ${expiringCookie.expires}`);
  console.log(`Domain: ${expiringCookie.domain}`);
}

// Handle invalid cookie strings
const invalid = parseCookie("invalid-cookie-format");
if (invalid === null) {
  console.log("Failed to parse cookie string");
}

// Batch parse multiple cookie strings
const cookieStrings = [
  "user=john; Max-Age=86400",
  "session=xyz789; HttpOnly; Secure",
  "invalid=",
];

const parsed = cookieStrings
  .map(parseCookie)
  .filter(cookie => cookie !== null);

console.log(`Successfully parsed ${parsed.length} cookies`);

Integration Examples

Server-Side Cookie Handling

import { getCookies, setCookie, deleteCookie } from "undici-types";

// Express-like middleware example
function handleCookies(request: Request): Response {
  // Read incoming cookies
  const cookies = getCookies(request.headers);
  
  const headers = new Headers();
  
  // Check authentication
  if (!cookies.sessionId) {
    // Set session cookie
    setCookie(headers, {
      name: "sessionId", 
      value: generateSessionId(),
      httpOnly: true,
      secure: true,
      sameSite: "Strict",
      maxAge: 86400 // 24 hours
    });
  }
  
  // Handle logout
  if (request.url.includes('/logout')) {
    deleteCookie(headers, "sessionId");
    deleteCookie(headers, "authToken");
  }
  
  return new Response("OK", { headers });
}

Client-Side Cookie Management

import { getSetCookies, Cookie } from "undici-types";

// Handle response cookies
async function handleApiResponse(response: Response) {
  const setCookies = getSetCookies(response.headers);
  
  setCookies.forEach(cookie => {
    // Log cookie details
    console.log(`Received cookie: ${cookie.name}`);
    
    // Handle security warnings
    if (cookie.secure && !location.protocol.startsWith('https:')) {
      console.warn('Secure cookie received over HTTP');
    }
    
    // Store cookie info for debugging
    if (cookie.sameSite === 'None' && !cookie.secure) {
      console.error('SameSite=None requires Secure attribute');
    }
  });
}

Install with Tessl CLI

npx tessl i tessl/npm-undici-types

docs

connection-management.md

cookies.md

error-handling.md

http-api.md

http-clients.md

index.md

interceptors.md

testing-mocking.md

utilities.md

web-standards.md

tile.json