HTTP Cookie Parser and Serializer
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
-
TypeError: cookie is not a function
cause Attempting to use `import cookie from 'cookie'` and then calling `cookie.parse()` or `cookie.serialize()` after v1.0.0, which removed the default export.fixChange your import statement to `import * as cookie from 'cookie';` or `import { parseCookie, stringifySetCookie } from 'cookie';`. -
ReferenceError: require is not defined
cause Using CommonJS `require()` syntax in an ESM module context (e.g., in a Node.js project with `"type": "module"` in `package.json` or in a browser environment via bundler without proper CJS translation).fixUse ESM `import` statements: `import { parseCookie, stringifySetCookie } from 'cookie';`. -
TypeError: options.maxAge must be an integer
cause Providing a non-integer value for the `maxAge` option when calling `stringifySetCookie` (or the deprecated `serialize`).fixEnsure the `maxAge` value is a whole number (e.g., `Math.floor(value)` or `parseInt(value, 10)`). -
Error: Invalid character in cookie name/value
cause Attempting to parse or serialize cookie strings with characters that violate RFC6265 specifications, though the package is generally lenient.fixEnsure cookie names and values adhere to valid character sets (e.g., for values, `encodeURIComponent` by default handles most cases). Looser validation was added in v1.0.2, but extreme cases may still fail.
Warnings
- breaking Version 1.0.0 introduced significant breaking changes, including minimum Node.js v18, mandatory named or namespace ESM imports, and a null prototype object for `parse` return values. The `strict` and `priority` options now require lowercase strings.
- breaking The `parse` and `serialize` methods were renamed to `parseCookie` and `stringifySetCookie` respectively in v1.1.0 to improve clarity and introduce `parseSetCookie` and `stringifyCookie`. While old names are aliased for backward compatibility, relying on them is discouraged.
- gotcha When using `maxAge` and `expires` options together in `stringifySetCookie`, RFC6265 states `maxAge` takes precedence. However, some clients might not obey this. It's best practice to ensure both point to the same date and time if used.
- breaking The `maxAge` option in `stringifySetCookie` now strictly requires an integer value, using `Number.isInteger` for validation. Non-integer values will cause issues.
- gotcha The `cookie.parseSetCookie` method strictly follows the specification and will ignore invalid or unrecognized attributes in a `Set-Cookie` string, rather than attempting to normalize or guess their intent.
Install
-
npm install cookie -
yarn add cookie -
pnpm add cookie
Imports
- parseCookie
const { parseCookie } = require('cookie');import { parseCookie } from 'cookie'; - stringifySetCookie
import cookie from 'cookie'; const header = cookie.serialize(...); // Deprecated name
import { stringifySetCookie } from 'cookie'; - parseSetCookie
import { parseSetCookie } from 'cookie'; - * as cookie
import cookie from 'cookie'; // Default import no longer works
import * as cookie from 'cookie';
Quickstart
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 }