{"id":17428,"library":"cookie-session","title":"Cookie Session Middleware","description":"cookie-session is a lightweight middleware for Node.js, primarily used with Express, that implements client-side session management. Unlike server-side session stores (like `express-session`), this module stores the entire session data directly within a signed, but unencrypted, cookie on the client's browser. This approach means no server-side database or resources are required for session storage, which can simplify deployments, especially in load-balanced environments. The current stable version is 2.1.1, released in April 2024, indicating active maintenance. Releases typically align with updates to its underlying `cookies` and `keygrip` dependencies, or to address compatibility with newer Node.js versions. Key differentiators include its minimal server-side footprint and the direct storage of session data in the client's cookie, making it suitable for 'light' sessions or as a complement to a secondary, database-backed store for larger data payloads.","status":"active","version":"2.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/expressjs/cookie-session","tags":["javascript","connect","express","middleware","session"],"install":[{"cmd":"npm install cookie-session","lang":"bash","label":"npm"},{"cmd":"yarn add cookie-session","lang":"bash","label":"yarn"},{"cmd":"pnpm add cookie-session","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is designed as middleware for the Express.js framework.","package":"express","optional":false}],"imports":[{"note":"While CommonJS `require` is shown in old docs/examples, modern Node.js and client-side development favors ES Modules. The package itself primarily exposes a default export.","wrong":"const cookieSession = require('cookie-session')","symbol":"cookieSession","correct":"import cookieSession from 'cookie-session'"},{"note":"For CommonJS environments, `require` is the correct way to import the default exported function. There are no named exports to destructure.","wrong":"import { cookieSession } from 'cookie-session'","symbol":"cookieSession","correct":"const cookieSession = require('cookie-session')"}],"quickstart":{"code":"import express from 'express';\nimport cookieSession from 'cookie-session';\n\nconst app = express();\n\n// Ensure you provide at least one strong secret key.\n// In production, these should be loaded from environment variables.\nconst SESSION_SECRET_KEYS = process.env.SESSION_SECRET_KEYS ?\n  process.env.SESSION_SECRET_KEYS.split(',') : ['supersecretkey1', 'anothersupersecretkey2'];\n\napp.use(cookieSession({\n  name: 'session',\n  keys: SESSION_SECRET_KEYS,\n  maxAge: 24 * 60 * 60 * 1000, // 24 hours\n  httpOnly: true, // Recommended for security\n  secure: process.env.NODE_ENV === 'production', // Use secure cookies in production\n  sameSite: 'lax' // Recommended for security\n}));\n\napp.get('/', (req, res) => {\n  // Access and modify session data via req.session\n  req.session.views = (req.session.views || 0) + 1;\n  res.send(`Hello! You've viewed this page ${req.session.views} times. Session ID: ${req.session.id || 'N/A'}`);\n});\n\napp.get('/login', (req, res) => {\n  req.session.user = { id: 1, name: 'John Doe' };\n  req.session.loggedInAt = Date.now();\n  res.redirect('/');\n});\n\napp.get('/logout', (req, res) => {\n  req.session = null; // Clears the session cookie\n  res.redirect('/');\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Try visiting / and then /login and /logout');\n});","lang":"typescript","description":"This quickstart initializes an Express app with `cookie-session`, demonstrating how to configure the middleware, access and modify session data (`req.session`), and clear a session. It highlights crucial security considerations like providing secret keys and setting `httpOnly`, `secure`, and `sameSite` cookie options."},"warnings":[{"fix":"Update your middleware configuration to use `name: 'your_cookie_name'` instead of `key: 'your_cookie_name'`.","message":"In version 2.0.0, the default cookie name was changed from an implicitly derived or internal 'key' to 'session'. The 'key' option was explicitly removed and developers must now use the 'name' option to specify the cookie name.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Remove all calls to `req.session.save()`, and update `req.session.populated` to `req.session.isPopulated`. For length, manually check `Object.keys(req.session).length`. Other removed properties have no direct replacement or were undocumented internal features.","message":"Version 2.0.0 deprecated and removed several properties and methods from `req.session`, including `req.session.save()`, `req.session.length`, `.populated` (replaced by `.isPopulated`), `req.sessionCookies`, and `req.sessionKey`. Attempting to use these will result in errors.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Encrypt sensitive data before storing it in `req.session`, or use a server-side session store (`express-session`) for truly private data. Alternatively, only store non-sensitive identifiers in `cookie-session` and retrieve sensitive data from a server-side database.","message":"This module *only signs* the session cookie to prevent tampering; it *does not encrypt* the session data. The client can read the entire contents of `req.session` by inspecting the cookie value. Do not store sensitive, unencrypted data in `req.session`.","severity":"gotcha","affected_versions":"all"},{"fix":"To prevent replay, implement server-side validation by storing an expiration timestamp or a unique session ID in `req.session` and regularly checking its validity on the server. Always add some initial data to `req.session` (e.g., `req.session.initialized = true;`) if you want a session cookie to be set immediately.","message":"The module does not inherently prevent session replay attacks. The expiration time set on the cookie only controls when the browser discards it. A client can save and re-use an unexpired cookie. Additionally, a session cookie will only be sent if `req.session` contains *any* data. An empty `req.session` will not trigger a `Set-Cookie` header.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Remove all explicit calls to `req.session.save()`. The middleware automatically handles saving changes to `req.session`.","cause":"The `req.session.save()` method was removed in `cookie-session` v2.0.0 as session changes are now automatically saved upon response end.","error":"TypeError: req.session.save is not a function"},{"fix":"Provide an array of strong secret strings to the `keys` option in the middleware configuration, e.g., `app.use(cookieSession({ name: 'session', keys: ['secret1', 'secret2'] }))`. In production, these should be loaded from environment variables.","cause":"The `keys` option (or `secret` for a single key) is mandatory for `cookie-session` to sign the session cookie, which prevents tampering. Without it, the middleware cannot function securely.","error":"Error: 'keys' must be provided to sign the cookie."},{"fix":"Ensure you add at least one property to `req.session` (e.g., `req.session.initialized = true;`) at some point during the request if you want a session cookie to be created for the user.","cause":"The `cookie-session` middleware only sets a session cookie if `req.session` contains any data (i.e., it's not an empty object).","error":"No 'Set-Cookie' header is sent, and no session cookie is created."},{"fix":"Use the ES Module import syntax: `import cookieSession from 'cookie-session';`. Ensure your environment supports ES Modules.","cause":"Attempting to use CommonJS `require()` syntax in a JavaScript file that is treated as an ES Module (e.g., `\"type\": \"module\"` in `package.json` or `.mjs` file extension).","error":"ReferenceError: require is not defined (in an ES Module context)"}],"ecosystem":"npm","meta_description":null}