Cookie provides HTTP server cookie parsing and serialization that is RFC 6265 compliant. It offers a simple API for parsing Cookie headers into JavaScript objects and serializing cookie name-value pairs into Set-Cookie header strings with comprehensive attribute support.
npm install cookieimport { parse, serialize } from "cookie";
import type { ParseOptions, SerializeOptions } from "cookie";For CommonJS:
const { parse, serialize } = require("cookie");import { parse, serialize } from "cookie";
// Parse Cookie header
const cookies = parse("foo=bar; equation=E%3Dmc%5E2");
console.log(cookies); // { foo: 'bar', equation: 'E=mc^2' }
// Serialize cookie for Set-Cookie header
const setCookie = serialize("sessionId", "abc123", {
httpOnly: true,
secure: true,
maxAge: 3600
});
console.log(setCookie); // "sessionId=abc123; Max-Age=3600; HttpOnly; Secure"Parses a HTTP Cookie header string into an object containing all cookie name-value pairs.
/**
* Parse a cookie header string into an object of name-value pairs
* @param str - Cookie header string to parse
* @param options - Optional parsing configuration
* @returns Object with cookie names as keys and values as strings
*/
function parse(
str: string,
options?: ParseOptions
): Record<string, string | undefined>;
interface ParseOptions {
/**
* Function to decode cookie values. Defaults to decodeURIComponent with error handling.
* If decoding fails, returns the original value.
*/
decode?: (str: string) => string | undefined;
}Usage Examples:
import { parse } from "cookie";
// Basic parsing
const cookies = parse("name=value; theme=dark");
// Result: { name: 'value', theme: 'dark' }
// Custom decode function with type safety
import type { ParseOptions } from "cookie";
const parseOptions: ParseOptions = {
decode: (value) => {
try {
return JSON.parse(decodeURIComponent(value));
} catch {
return value;
}
}
};
const cookiesWithCustomDecode = parse("data=%7B%22user%22%3A%22alice%22%7D", parseOptions);
// Handles malformed cookies gracefully
const messyCookies = parse("valid=ok; malformed; another=value");
// Result: { valid: 'ok', another: 'value' }Serializes a cookie name-value pair into a Set-Cookie header string with optional attributes.
/**
* Serialize a cookie name-value pair into a Set-Cookie header string
* @param name - Cookie name (must be valid according to RFC 6265)
* @param val - Cookie value (will be encoded)
* @param options - Optional serialization attributes
* @returns Set-Cookie header string
* @throws TypeError if name or encoded value is invalid
*/
function serialize(
name: string,
val: string,
options?: SerializeOptions
): string;
interface SerializeOptions {
/**
* Function to encode cookie values. Defaults to encodeURIComponent.
*/
encode?: (str: string) => string;
/**
* Max-Age attribute in seconds. Takes precedence over expires if both are set.
*/
maxAge?: number;
/**
* Expires attribute as Date object. Creates session cookie if omitted.
*/
expires?: Date;
/**
* Domain attribute. Cookie applies to current domain only if omitted.
*/
domain?: string;
/**
* Path attribute. Uses default path if omitted.
*/
path?: string;
/**
* HttpOnly flag. Prevents client-side JavaScript access when true.
*/
httpOnly?: boolean;
/**
* Secure flag. Only sent over HTTPS when true.
*/
secure?: boolean;
/**
* Partitioned flag. Experimental attribute for CHIPS support.
*/
partitioned?: boolean;
/**
* Priority attribute for cookie eviction priority.
*/
priority?: "low" | "medium" | "high";
/**
* SameSite attribute for CSRF protection.
* - true or "strict": Strict same-site enforcement
* - "lax": Lax same-site enforcement (default behavior)
* - "none": Explicit cross-site cookie (requires Secure)
*/
sameSite?: boolean | "lax" | "strict" | "none";
}Usage Examples:
import { serialize } from "cookie";
// Basic serialization
const basic = serialize("sessionId", "abc123");
// Result: "sessionId=abc123"
// Session cookie with security attributes using typed options
import type { SerializeOptions } from "cookie";
const sessionOptions: SerializeOptions = {
httpOnly: true,
secure: true,
sameSite: "strict"
};
const sessionCookie = serialize("session", "user123", sessionOptions);
// Result: "session=user123; HttpOnly; Secure; SameSite=Strict"
// Persistent cookie with expiration
const persistent = serialize("preferences", "theme=dark", {
expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
domain: "example.com",
path: "/",
maxAge: 604800 // 7 days in seconds
});
// Cross-site cookie configuration
const crossSite = serialize("tracking", "analytics123", {
sameSite: "none",
secure: true, // Required for SameSite=None
partitioned: true // CHIPS support
});
// Custom encoding
const customEncoded = serialize("data", '{"user":"alice"}', {
encode: (value) => Buffer.from(value).toString('base64')
});The serialize function throws TypeError for invalid inputs:
// These will throw TypeError
serialize("invalid name", "value"); // Invalid name with space
serialize("name", "value", { maxAge: 3.14 }); // Non-integer maxAge
serialize("name", "value", { priority: "urgent" }); // Invalid priority
serialize("name", "value", { domain: "invalid..domain" }); // Invalid domain format
serialize("name", "value", { path: "/path;with;semicolons" }); // Invalid path characters