Registry / auth-security / cookie-session

cookie-session

JSON →
library2.1.1jsnpmunverified

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.

npm install cookie-session
INSTALL
IMPORT
SIG · COOKIE-SESSION
C
cookie-session
auth-securityjavascriptv2.1.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

cookieSession
✓ import cookieSession from 'cookie-session'
✗ const cookieSession = require('cookie-session')
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.
cookieSession
✓ const cookieSession = require('cookie-session')
✗ import { cookieSession } from 'cookie-session'
For CommonJS environments, `require` is the correct way to import the default exported function. There are no named exports to destructure.

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.

import express from 'express'; import cookieSession from 'cookie-session'; const app = express(); // Ensure you provide at least one strong secret key. // In production, these should be loaded from environment variables. const SESSION_SECRET_KEYS = process.env.SESSION_SECRET_KEYS ? process.env.SESSION_SECRET_KEYS.split(',') : ['supersecretkey1', 'anothersupersecretkey2']; app.use(cookieSession({ name: 'session', keys: SESSION_SECRET_KEYS, maxAge: 24 * 60 * 60 * 1000, // 24 hours httpOnly: true, // Recommended for security secure: process.env.NODE_ENV === 'production', // Use secure cookies in production sameSite: 'lax' // Recommended for security })); app.get('/', (req, res) => { // Access and modify session data via req.session req.session.views = (req.session.views || 0) + 1; res.send(`Hello! You've viewed this page ${req.session.views} times. Session ID: ${req.session.id || 'N/A'}`); }); app.get('/login', (req, res) => { req.session.user = { id: 1, name: 'John Doe' }; req.session.loggedInAt = Date.now(); res.redirect('/'); }); app.get('/logout', (req, res) => { req.session = null; // Clears the session cookie res.redirect('/'); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Try visiting / and then /login and /logout'); });
Debug
Known issues
breakingIn 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.
fix
Update your middleware configuration to use `name: 'your_cookie_name'` instead of `key: 'your_cookie_name'`.
affects: >=2.0.0
breakingVersion 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.
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.
affects: >=2.0.0
gotchaThis 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`.
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.
affects: all
gotchaThe 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.
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.
affects: all
Errors
Common errors & fixes
TypeError: req.session.save is not a function
The `req.session.save()` method was removed in `cookie-session` v2.0.0 as session changes are now automatically saved upon response end.
fix
Remove all explicit calls to `req.session.save()`. The middleware automatically handles saving changes to `req.session`.
Error: 'keys' must be provided to sign the cookie.
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.
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.
No 'Set-Cookie' header is sent, and no session cookie is created.
The `cookie-session` middleware only sets a session cookie if `req.session` contains any data (i.e., it's not an empty object).
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.
ReferenceError: require is not defined (in an ES Module context)
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).
fix
Use the ES Module import syntax: `import cookieSession from 'cookie-session';`. Ensure your environment supports ES Modules.
Upgrade
Version history
2.1.1latest on npm
Audit
Dependencies
expressrequiredThis package is designed as middleware for the Express.js framework.
Agent activity
15 hits · last 30 days
node
14
OpenAI (training)
1
Resources
cookie-session — npm install cookie-session · libregistry