Node.js HTTP Cookie Management
node-cookie is a utility library for Node.js environments, designed to simplify the parsing, signing, encryption, creation, and clearing of HTTP cookies. It directly interfaces with Node.js's built-in `http.IncomingMessage` and `http.ServerResponse` objects, making it agnostic to higher-level web frameworks. The current stable version is 2.1.2, which was last published over six years ago. Despite some recent activity on its GitHub repository (commits in 2022-2023), the package itself has not seen new releases, suggesting it is in an abandoned or very low-maintenance state. Its key differentiator is providing low-level, built-in cookie signing and encryption capabilities without requiring a full framework or complex middleware, directly leveraging Node.js crypto primitives.
Common errors
-
TypeError: The 'secret' argument must be a string or a Buffer
cause The `secret` parameter for signing or encrypting cookies was not provided or was of an incorrect type (e.g., `null`, `undefined`, or a number).fixEnsure a non-empty string secret is passed as the fourth argument to `create` or `parse`/`get` methods, or as part of the options object. -
Error: Invalid IV length
cause This cryptographic error often occurs when the secret key used for encryption/decryption is inconsistent or of an incorrect length, or if the cookie value itself has been tampered with or corrupted.fixVerify that the *exact same secret* is used for both encrypting (during `create`) and decrypting (during `parse` or `get`) a cookie. Ensure the secret meets the length requirements of the underlying cryptographic algorithm (e.g., 16, 24, or 32 characters for AES-128, AES-192, AES-256 respectively, or derived consistently). -
Cookie 'mycookie' is not visible in browser developer tools / `req.headers.cookie` does not contain 'mycookie'
cause The `Set-Cookie` header was not properly sent by the server, or the browser rejected the cookie due to incorrect attributes (e.g., `Domain`, `Path`, `Secure`, `HttpOnly`, `Expires`, `SameSite`).fixCheck the `Set-Cookie` header in the server response for errors. Ensure `secure: true` is only for HTTPS. Verify `domain` and `path` match the request URL. If `httpOnly: true` is set, the cookie won't be accessible by client-side JavaScript, but should still be sent by the browser. Explicitly set `expires` or `maxAge` to ensure persistence.
Warnings
- breaking The package is explicitly CommonJS and uses `require`. Attempting to `import` it in a pure ESM context might lead to issues or require specific Node.js interoperability configurations (e.g., `createRequire`). Node.js ESM loader will treat `require('node-cookie')` as a default export, but explicit named imports are not supported.
- gotcha Using a weak or hardcoded secret for signing and encryption (e.g., directly in source code) makes cookies vulnerable to tampering and decryption. The secret must be sufficiently long and complex, and should be managed securely (e.g., via environment variables).
- gotcha Cookies might not be set in the browser if `secure: true` is used when serving over HTTP, or if `domain` or `path` options are misconfigured. Browsers strictly enforce these attributes.
- deprecated This package has not been updated in over six years (last published version 2.1.2). It may not receive security updates or be compatible with future Node.js versions or evolving web standards (e.g., `SameSite=None; Secure;` requirements).
Install
-
npm install node-cookie -
yarn add node-cookie -
pnpm add node-cookie
Imports
- nodeCookie
const { nodeCookie } = require('node-cookie')import nodeCookie from 'node-cookie'
- create
import { create } from 'node-cookie'import nodeCookie from 'node-cookie'; nodeCookie.create(res, 'key', 'value')
- parse
import { parse } from 'node-cookie'const nodeCookie = require('node-cookie'); const cookies = nodeCookie.parse(req) - get
const { get } = require('node-cookie')const nodeCookie = require('node-cookie'); const value = nodeCookie.get(req, 'key')
Quickstart
const http = require('http');
const nodeCookie = require('node-cookie');
const SECRET = process.env.COOKIE_SECRET ?? 'supersecretkeyfornodejsapp';
http.createServer(function (req, res) {
if (req.url === '/set-cookie') {
// Create a signed and encrypted cookie
nodeCookie.create(res, 'userSession', 'user123', { expires: new Date(Date.now() + 60 * 60 * 1000) }, SECRET, true);
nodeCookie.create(res, 'lastVisit', new Date().toISOString(), SECRET, false);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Cookies set!');
} else if (req.url === '/get-cookie') {
// Parse and retrieve cookies
const parsedCookies = nodeCookie.parse(req, SECRET, true);
const userSession = nodeCookie.get(req, 'userSession', SECRET, true);
const lastVisit = nodeCookie.get(req, 'lastVisit', SECRET, false);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
parsedCookies,
userSession: userSession || 'Not found or invalid',
lastVisit: lastVisit || 'Not found or invalid'
}));
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Visit /set-cookie to set, or /get-cookie to retrieve.</h1>');
}
}).listen(3000, () => {
console.log('Server running on http://localhost:3000');
console.log('Try http://localhost:3000/set-cookie then http://localhost:3000/get-cookie');
});