or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdrequest-cookies.mdresponse-cookies.mdserialization.md
tile.json

serialization.mddocs/

Cookie Serialization

The serialization module provides utility functions for parsing and stringifying HTTP cookies. These functions handle the low-level details of cookie header parsing, URL encoding/decoding, and proper attribute formatting according to HTTP standards.

Capabilities

Stringify Cookie

Serializes a cookie object to a string format suitable for HTTP headers.

/**
 * Serializes a cookie object to a string format for HTTP headers
 * @param c - Cookie object (RequestCookie or ResponseCookie)
 * @returns Formatted cookie string with attributes
 */
function stringifyCookie(c: ResponseCookie | RequestCookie): string;

Usage Examples:

import { stringifyCookie } from "@edge-runtime/cookies";

// Simple request cookie
const requestCookie = { name: "session", value: "abc123" };
const cookieString = stringifyCookie(requestCookie);
console.log(cookieString); // "session=abc123"

// Response cookie with attributes
const responseCookie = {
  name: "user",
  value: "john doe",
  path: "/",
  httpOnly: true,
  secure: true,
  maxAge: 3600,
  sameSite: "strict" as const
};
const setCookieString = stringifyCookie(responseCookie);
console.log(setCookieString);
// "user=john%20doe; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=strict"

// Cookie with expiration date
const expiringCookie = {
  name: "temp",
  value: "data",
  expires: new Date("2024-12-31T23:59:59Z")
};
const expiringString = stringifyCookie(expiringCookie);
console.log(expiringString);
// "temp=data; Expires=Tue, 31 Dec 2024 23:59:59 GMT"

Parse Cookie Header

Parses a Cookie header value into a Map of name-value pairs.

/**
 * Parse a Cookie header value into key-value pairs
 * @param cookie - Cookie header string (e.g., "name1=value1; name2=value2")
 * @returns Map of cookie names to values
 */
function parseCookie(cookie: string): Map<string, string>;

Usage Examples:

import { parseCookie } from "@edge-runtime/cookies";

// Parse simple cookie header
const cookieHeader = "session=abc123; theme=dark; lang=en";
const parsed = parseCookie(cookieHeader);

console.log(parsed.get("session")); // "abc123"
console.log(parsed.get("theme"));   // "dark"
console.log(parsed.get("lang"));    // "en"

// Iterate over all cookies
for (const [name, value] of parsed) {
  console.log(`${name}: ${value}`);
}

// Handle URL-encoded values
const encodedHeader = "user=john%20doe; city=new%20york";
const encodedParsed = parseCookie(encodedHeader);
console.log(encodedParsed.get("user")); // "john doe" (automatically decoded)
console.log(encodedParsed.get("city")); // "new york"

// Handle cookies without values (treated as "true")
const flagHeader = "debug; secure; user=john";
const flagParsed = parseCookie(flagHeader);
console.log(flagParsed.get("debug"));  // "true"
console.log(flagParsed.get("secure")); // "true"
console.log(flagParsed.get("user"));   // "john"

Parse Set-Cookie Header

Parses a Set-Cookie header value into a ResponseCookie object with all attributes.

/**
 * Parse a Set-Cookie header value into a ResponseCookie object
 * @param setCookie - Set-Cookie header string with attributes
 * @returns ResponseCookie object or undefined if invalid
 */
function parseSetCookie(setCookie: string): undefined | ResponseCookie;

Split Cookies String

Splits a comma-separated Set-Cookie header string into individual cookie strings. This utility handles the edge case where Set-Cookie headers are comma-joined, taking care not to split on commas within cookie attributes.

/**
 * Split comma-separated Set-Cookie header string into individual cookie strings
 * @param cookiesString - Comma-separated Set-Cookie header value
 * @returns Array of individual cookie strings
 */
function splitCookiesString(cookiesString: string): string[];

Usage Examples:

import { splitCookiesString } from "@edge-runtime/cookies";

// Handle comma-separated Set-Cookie headers (rare but valid)
const combinedHeader = "session=abc123; Path=/; HttpOnly, user=john; Secure, theme=dark";
const splitCookies = splitCookiesString(combinedHeader);
console.log(splitCookies);
// [
//   "session=abc123; Path=/; HttpOnly",
//   " user=john; Secure", 
//   " theme=dark"
// ]

// Handle single cookie (returns array with one item)
const singleHeader = "token=xyz789; Expires=Wed, 21 Oct 2025 07:28:00 GMT";
const singleCookie = splitCookiesString(singleHeader);
console.log(singleCookie); // ["token=xyz789; Expires=Wed, 21 Oct 2025 07:28:00 GMT"]

// Handle empty string
const emptyHeader = "";
const emptySplit = splitCookiesString(emptyHeader);
console.log(emptySplit); // []

// Process each cookie individually
const multiHeader = "a=1; Path=/, b=2; Domain=.example.com";
const cookies = splitCookiesString(multiHeader);
cookies.forEach(cookieStr => {
  const parsed = parseSetCookie(cookieStr.trim());
  console.log(parsed);
});
import { parseSetCookie } from "@edge-runtime/cookies";

// Parse basic Set-Cookie header
const basicHeader = "session=abc123; Path=/; HttpOnly";
const basicCookie = parseSetCookie(basicHeader);
console.log(basicCookie);
// {
//   name: "session",
//   value: "abc123",
//   path: "/",
//   httpOnly: true
// }

// Parse complex Set-Cookie header
const complexHeader = "user=john%2520doe; Domain=.example.com; Path=/admin; Max-Age=3600; Secure; HttpOnly; SameSite=Strict; Priority=High";
const complexCookie = parseSetCookie(complexHeader);
console.log(complexCookie);
// {
//   name: "user",
//   value: "john%20doe", // URL decoded
//   domain: ".example.com",
//   path: "/admin",
//   maxAge: 3600,
//   secure: true,
//   httpOnly: true,
//   sameSite: "strict",
//   priority: "high"
// }

// Parse cookie with expiration date
const expiresHeader = "temp=data; Expires=Wed, 21 Oct 2025 07:28:00 GMT";
const expiresCookie = parseSetCookie(expiresHeader);
console.log(expiresCookie?.expires); // Date object: Wed Oct 21 2025 07:28:00 GMT

// Handle invalid cookie (returns undefined)
const invalidHeader = "";
const invalidCookie = parseSetCookie(invalidHeader);
console.log(invalidCookie); // undefined

// Handle malformed attributes (gracefully ignored)
const malformedHeader = "name=value; InvalidAttribute=bad; Path=/; Valid=true";
const malformedCookie = parseSetCookie(malformedHeader);
console.log(malformedCookie);
// {
//   name: "name",
//   value: "value",
//   path: "/"
// }
// Note: InvalidAttribute is ignored, Valid is not a standard cookie attribute

Supported Cookie Attributes

The parseSetCookie function recognizes and parses the following cookie attributes:

Standard Attributes

  • Domain: Cookie domain scope
  • Path: Cookie path scope
  • Expires: Absolute expiration date
  • Max-Age: Relative expiration in seconds
  • Secure: HTTPS-only flag
  • HttpOnly: No JavaScript access flag
  • SameSite: Cross-site request policy (Strict, Lax, None)

Modern Attributes

  • Partitioned: CHIPS (Cookies Having Independent Partitioned State)
  • Priority: Browser eviction hint (Low, Medium, High)

Implementation Notes

URL Encoding

  • Cookie values are automatically URL-encoded during stringification
  • Cookie values are automatically URL-decoded during parsing
  • Invalid URL-encoded sequences are gracefully handled

Case Insensitivity

  • Attribute names are parsed case-insensitively
  • Attribute values preserve original case except for standardized enums

Error Handling

  • Invalid cookie strings return empty Maps or undefined
  • Malformed attributes are ignored rather than throwing errors
  • URL decoding errors are silently ignored

Standards Compliance

  • Follows RFC 6265 cookie specification
  • Compatible with modern browser cookie implementations
  • Handles edge cases like comma-separated Set-Cookie headers

Advanced Usage Example:

import { parseCookie, parseSetCookie, stringifyCookie } from "@edge-runtime/cookies";

// Round-trip cookie processing
const originalHeader = "session=user123; Path=/; HttpOnly; SameSite=Lax";
const parsed = parseSetCookie(originalHeader);
const reconstructed = stringifyCookie(parsed!);

console.log(originalHeader);
console.log(reconstructed);
// Both should represent the same cookie, though formatting may differ slightly