Connect/Express Cookie Middleware

raw JSON →
0.0.0 verified Thu Apr 23 auth: no javascript abandoned

connect-cookies is an unmaintained Node.js middleware for the `connect` and `express` frameworks, designed to simplify reading and setting HTTP(S) cookies. It wraps the `cookies` and `keygrip` packages to provide cookie management capabilities, including support for signed cookies to prevent tampering. Despite its purpose, the package is stuck at version `0.0.0` and has not seen updates in nearly a decade. Its underlying dependencies (`cookies` and `keygrip`) are also quite old. Modern Node.js applications, especially those using recent versions of Express, should avoid this package due to its abandoned status, potential security vulnerabilities, and lack of support for contemporary cookie standards (e.g., `SameSite` attribute defaults and `__Host` prefixes). Current stable alternatives like `cookie-parser` for basic cookie handling and `express-session` or `cookie-session` for session management are recommended for active development.

error TypeError: req.cookies.get is not a function
cause The `connect-cookies` middleware was not correctly applied or initialized, or another middleware overwrote `req.cookies`.
fix
Ensure app.use(cookies(keys)) is called before any route handlers attempt to access req.cookies. Verify that connect-cookies is the intended cookie middleware.
error Error: Can't set headers after they are sent.
cause A common Express/Connect error indicating that `res.end()`, `res.send()`, or `res.json()` was called more than once, or headers were sent before attempting to set a cookie.
fix
Review middleware and route handler logic to ensure res.end() (or similar) is called only once. Ensure next() is called if the middleware is not terminating the request.
error Error: Not a signed cookie.
cause Attempting to retrieve a signed cookie using `req.cookies.get('cookieName', { signed: true })` when the cookie was not originally set with `signed: true` or with valid keys, or the keys provided to `connect-cookies` do not match the keys used to sign the cookie.
fix
Ensure that cookies intended to be signed are set with req.cookies.set('cookieName', value, { signed: true }) and that the cookies() middleware is initialized with the correct keys array that was used for signing.
breaking This package is unmaintained and stuck at version 0.0.0. It will not receive any further updates, bug fixes, or security patches. Using it in production is strongly discouraged.
fix Migrate to `cookie-parser` for basic cookie handling and `express-session` or `cookie-session` for session management.
security The package and its dependencies are old, lacking modern security features for cookie handling (e.g., robust `SameSite` attribute defaults, `__Host` prefixes). This makes applications vulnerable to common attacks like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) if not carefully configured manually.
fix Replace with maintained alternatives like `cookie-parser` and `express-session` which provide secure defaults and are actively patched. Implement strong Content Security Policies (CSPs).
gotcha Designed for older `connect`/`express` versions (likely 2.x/3.x era). Compatibility with newer Node.js versions or Express 4.x/5.x is not guaranteed and may lead to unexpected behavior or breaking changes.
fix Avoid using this package in new projects. For existing projects, consider a full migration to modern middleware to ensure compatibility and stability.
gotcha The package is CommonJS-only, meaning it cannot be directly imported using ESM `import` syntax. This can cause issues in modern Node.js environments that primarily use ESM.
fix If used in an ESM project, you would need to use `createRequire` or transpile your code, which adds unnecessary complexity. It's best to use modern, ESM-compatible alternatives.
npm install connect-cookies
yarn add connect-cookies
pnpm add connect-cookies

Demonstrates basic usage of `connect-cookies` middleware to implement a simple view counter, storing the count in a signed cookie. It showcases cookie retrieval and setting.

const connect = require('connect');
const cookies = require('connect-cookies');

const app = connect();

// Pass an array of keys for secure cookies. In production, these should be strong and rotated.
// process.env.COOKIE_KEYS should be a comma-separated string of keys.
const cookieKeys = process.env.COOKIE_KEYS ? process.env.COOKIE_KEYS.split(',') : ['your_secret_key_here', 'another_secret_key'];

app.use(cookies(cookieKeys));

app.use(function(req, res) {
  // Access cookies via req.cookies, which is an instance of the 'cookies' module.
  // .get() method retrieves a cookie.
  let views = req.cookies.get('views') || 0;
  views = parseInt(views, 10) + 1;

  // .set() method sets a cookie. Include 'signed: true' for secure cookies.
  // Ensure appropriate secure, httpOnly, and SameSite options for production.
  req.cookies.set('views', views.toString(), { signed: true, httpOnly: true, secure: process.env.NODE_ENV === 'production' });

  res.end(`${views} views`);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log('Visit http://localhost:3000/ to see the view counter.');
});