or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Cookies

Cookies is a Node.js module for getting and setting HTTP(S) cookies with optional cryptographic signing to prevent tampering. It can be used with the built-in Node.js HTTP library or as Connect/Express middleware.

Package Information

  • Package Name: cookies
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install cookies

Core Imports

const Cookies = require("cookies");

Basic Usage

const http = require("http");
const Cookies = require("cookies");

// Optionally define keys to sign cookie values
const keys = ["keyboard cat"];

const server = http.createServer(function (req, res) {
  // Create a cookies object
  const cookies = new Cookies(req, res, { keys: keys });

  // Get a cookie
  const lastVisit = cookies.get("LastVisit", { signed: true });

  // Set the cookie to a value
  cookies.set("LastVisit", new Date().toISOString(), { signed: true });

  if (!lastVisit) {
    res.setHeader("Content-Type", "text/plain");
    res.end("Welcome, first time visitor!");
  } else {
    res.setHeader("Content-Type", "text/plain");
    res.end("Welcome back! Nothing much changed since your last visit at " + lastVisit + ".");
  }
});

Capabilities

Cookies Constructor

Creates a new cookie jar for handling cookies in HTTP requests and responses.

/**
 * Create a new cookie jar for a given request and response pair
 * @param {http.IncomingMessage} request - Node.js HTTP incoming request object
 * @param {http.ServerResponse} response - Node.js HTTP server response object
 * @param {CookieOptions} options - Optional configuration object
 * @returns {Cookies} - Cookies instance
 */
function Cookies(request, response, options);

/**
 * Alternative constructor call (can be called without new)
 * @param {http.IncomingMessage} request - Node.js HTTP incoming request object
 * @param {http.ServerResponse} response - Node.js HTTP server response object
 * @param {CookieOptions} options - Optional configuration object
 * @returns {Cookies} - Cookies instance
 */
const cookies = Cookies(request, response, options);

Getting Cookies

Extracts cookie values from the request headers.

/**
 * Extract cookie value from request headers
 * @param {string} name - Cookie name to retrieve
 * @param {GetOptions} opts - Optional configuration for cookie retrieval
 * @returns {string|undefined} - Cookie value or undefined if not found
 */
cookies.get(name, opts);

Usage Examples:

// Get unsigned cookie
const sessionId = cookies.get("sessionId");

// Get signed cookie
const userId = cookies.get("userId", { signed: true });

Setting Cookies

Sets cookie values in the response headers.

/**
 * Set cookie value in response headers
 * @param {string} name - Cookie name to set
 * @param {string} value - Cookie value (omit or set to undefined to delete)
 * @param {SetOptions} opts - Optional cookie attributes
 * @returns {Cookies} - Cookies instance for chaining
 */
cookies.set(name, value, opts);

Usage Examples:

// Set simple cookie
cookies.set("theme", "dark");

// Set cookie with options
cookies.set("sessionId", "abc123", {
  maxAge: 24 * 60 * 60 * 1000, // 24 hours
  httpOnly: true,
  secure: true,
  signed: true
});

// Delete cookie
cookies.set("oldCookie", null);

Express/Connect Middleware

Creates middleware for Express or Connect applications.

/**
 * Create Connect/Express middleware for cookie handling
 * @param {string[]|Keygrip} keys - Array of signing keys or Keygrip instance
 * @returns {Function} - Middleware function
 */
Cookies.express(keys);

/**
 * Alias for Cookies.express
 * @param {string[]|Keygrip} keys - Array of signing keys or Keygrip instance
 * @returns {Function} - Middleware function
 */
Cookies.connect(keys);

Usage Example:

const express = require("express");
const Cookies = require("cookies");

const app = express();
const keys = ["keyboard cat"];

// Add cookies middleware
app.use(Cookies.express(keys));

app.get("/", (req, res) => {
  // Access cookies via req.cookies and res.cookies
  const visits = req.cookies.get("visits") || 0;
  res.cookies.set("visits", parseInt(visits) + 1);
  res.send(`Visit count: ${visits}`);
});

Cookie Class

Individual cookie representation with attributes and serialization methods.

/**
 * Create a new Cookie instance
 * @param {string} name - Cookie name
 * @param {string} value - Cookie value
 * @param {CookieAttributes} attrs - Cookie attributes
 * @returns {Cookie} - Cookie instance
 */
function Cookie(name, value, attrs);

/**
 * Access Cookie class via Cookies.Cookie
 */
const Cookie = Cookies.Cookie;

Cookie Methods

Methods available on Cookie instances.

/**
 * Convert cookie to name=value string
 * @returns {string} - Cookie as name=value string
 */
cookie.toString();

/**
 * Convert cookie to complete Set-Cookie header value
 * @returns {string} - Complete Set-Cookie header with all attributes
 */
cookie.toHeader();

Cookie Properties

/**
 * Deprecated alias for maxAge property
 * @deprecated Use maxAge instead
 * @type {number}
 */
cookie.maxage; // getter/setter for cookie.maxAge

Types

Constructor Options

/**
 * Options for Cookies constructor
 * @typedef {Object} CookieOptions
 * @property {string[]|Keygrip} keys - Array of signing keys or Keygrip instance
 * @property {boolean} secure - Explicitly specify if connection is secure
 */

Get Options

/**
 * Options for cookies.get() method
 * @typedef {Object} GetOptions
 * @property {boolean} signed - Whether to verify cookie signature (default: determined by presence of keys)
 */

Set Options

/**
 * Options for cookies.set() method
 * @typedef {Object} SetOptions
 * @property {number} maxAge - Milliseconds from Date.now() for expiry
 * @property {Date} expires - Date object indicating expiration (end of session by default)
 * @property {string} path - Cookie path (default: "/")
 * @property {string} domain - Cookie domain (no default)
 * @property {boolean} secure - HTTPS only flag (auto-detected by default)
 * @property {boolean} httpOnly - HTTP(S) only flag (default: true)
 * @property {boolean} partitioned - Chrome CHIPS partitioning flag (default: false)
 * @property {string} priority - Cookie priority: "low", "medium", or "high"
 * @property {boolean|string} sameSite - Same site policy: false, "strict", "lax", "none", or true (maps to "strict")
 * @property {boolean} signed - Cryptographic signing flag (default: determined by presence of keys)
 * @property {boolean} overwrite - Overwrite existing cookies flag (default: false)
 */

Cookie Attributes

/**
 * Default cookie attribute values
 * @typedef {Object} CookieAttributes
 * @property {string} name - Cookie name
 * @property {string} value - Cookie value (empty string by default)
 * @property {string} path - Cookie path (default: "/")
 * @property {Date} expires - Expiration date (undefined by default)
 * @property {string} domain - Cookie domain (undefined by default)
 * @property {boolean} httpOnly - HTTP(S) only flag (default: true)
 * @property {boolean} partitioned - CHIPS partitioning flag (default: false)
 * @property {string} priority - Cookie priority (undefined by default)
 * @property {boolean} sameSite - Same site policy (default: false)
 * @property {boolean} secure - HTTPS only flag (default: false)
 * @property {boolean} overwrite - Overwrite existing cookies flag (default: false)
 */

Error Handling

The cookies module throws specific errors in these cases:

  • TypeError: Invalid cookie name, value, path, domain, maxAge, priority, or sameSite values
  • Error: Missing keys when attempting signed cookie operations
  • Error: Attempting to set secure cookies over unencrypted connections

Security Features

Signed Cookies

Cookies can be cryptographically signed to detect tampering:

const cookies = new Cookies(req, res, { keys: ["secret-key-1", "secret-key-2"] });

// Set signed cookie
cookies.set("userId", "12345", { signed: true });

// Get signed cookie (automatically verifies signature)
const userId = cookies.get("userId", { signed: true });

Secure Defaults

  • All cookies are httpOnly by default to prevent client-side access
  • Cookies sent over HTTPS are automatically marked secure
  • Signed cookies store signatures in separate .sig cookies using standard naming

Key Rotation

Multiple keys can be provided for signature verification, enabling key rotation:

  • First key is used for signing new cookies
  • All keys are tried when verifying existing cookies
  • Stale signatures are automatically refreshed with the current key