HTTP Cookie Parser and Serializer

1.1.1 · active · verified Sun Apr 19

The `cookie` package provides fundamental utilities for parsing and serializing HTTP `Cookie` and `Set-Cookie` headers, commonly used in Node.js HTTP servers. It is currently at stable version 1.1.1, with relatively frequent patch and minor releases addressing fixes and new HTTP cookie attributes like `partitioned` and `priority`. Key differentiators include its focus on adherence to RFC6265, minimal API surface, and robust handling of common cookie patterns. It is maintained by the `jshttp` organization, known for foundational Express.js ecosystem middleware, ensuring reliability and specification compliance.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing HTTP `Cookie` headers and both parsing and stringifying `Set-Cookie` headers with common options.

import { parseCookie, stringifySetCookie, parseSetCookie } from 'cookie';

// Example 1: Parsing a 'Cookie' header from an incoming request
const cookieHeader = 'foo=bar; equation=E%3Dmc%5E2; Path=/; Secure';
const parsedCookies = parseCookie(cookieHeader);
console.log('Parsed Cookies:', parsedCookies);
// Expected: { foo: 'bar', equation: 'E=mc^2' }

// Example 2: Stringifying a 'Set-Cookie' header for an outgoing response
const setCookieObject = {
  name: 'sessionid',
  value: 'abc123def456',
  maxAge: 3600, // 1 hour
  httpOnly: true,
  secure: true,
  path: '/',
  sameSite: 'Lax'
};
const setCookieString = stringifySetCookie(setCookieObject);
console.log('Set-Cookie String:', setCookieString);
// Expected: sessionid=abc123def456; Max-Age=3600; Path=/; HttpOnly; Secure; SameSite=Lax

// Example 3: Parsing a 'Set-Cookie' header (e.g., from a client-side response)
const rawSetCookie = 'mytoken=somevalue; Max-Age=7200; Path=/api; Expires=Wed, 21 Oct 2026 07:28:00 GMT; HttpOnly';
const parsedSetCookie = parseSetCookie(rawSetCookie);
console.log('Parsed Set-Cookie Object:', parsedSetCookie);
// Expected: { name: 'mytoken', value: 'somevalue', maxAge: 7200, path: '/api', expires: <Date object>, httpOnly: true }

view raw JSON →