Node.js HTTP Cookie Management

2.1.2 · abandoned · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting and retrieving signed and encrypted HTTP cookies using `node-cookie` with a basic Node.js HTTP server. It shows `create` for writing cookies with options for expiration, signing, and encryption, and `parse` and `get` for reading them, also handling decryption and unsigning.

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');
});

view raw JSON →