Cookie-based session middleware for Express applications that stores session data in client-side cookies
npx @tessl/cli install tessl/npm-cookie-session@2.1.0Cookie Session is a lightweight Express/Connect middleware that provides cookie-based session management. It stores session data directly in client-side cookies rather than server-side storage, enabling simplified deployment in load-balanced environments without external dependencies.
npm install cookie-sessionconst cookieSession = require('cookie-session');For ES modules:
import cookieSession from 'cookie-session';const express = require('express');
const cookieSession = require('cookie-session');
const app = express();
app.use(cookieSession({
name: 'session',
keys: ['secret-key-1', 'secret-key-2'],
// Cookie Options
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}));
app.get('/', function (req, res) {
// Access session data
const views = req.session.views || 0;
req.session.views = views + 1;
res.send(`Number of views: ${req.session.views}`);
});
// Destroy session
app.post('/logout', function (req, res) {
req.session = null;
res.redirect('/');
});
app.listen(3000);Cookie Session operates through several key components:
cookieSession() function creates middleware instances with specified configurationreq.session property that acts as a regular JavaScript object for storing datacookies library internally for secure cookie handling with signing supportCreates cookie session middleware with configuration options.
/**
* Create a new cookie session middleware
* @param {Object} [options] - Configuration options
* @param {string} [options.name='session'] - Name of the cookie to use
* @param {string[]} [options.keys] - Array of keys to sign & verify cookie values
* @param {string} [options.secret] - Single key if keys is not provided
* @param {boolean} [options.signed=true] - Whether the cookie is to be signed
* @param {boolean} [options.httpOnly=true] - Whether cookie is HTTP-only
* @param {boolean} [options.overwrite=true] - Whether to overwrite previously set cookies
* @param {number} [options.maxAge] - Cookie expiration in milliseconds
* @param {Date} [options.expires] - Cookie expiration date
* @param {string} [options.path='/'] - Cookie path
* @param {string} [options.domain] - Cookie domain
* @param {boolean} [options.partitioned=false] - Whether to partition cookie for CHIPS
* @param {string} [options.priority] - Cookie priority ('low', 'medium', 'high')
* @param {boolean|string} [options.sameSite=false] - SameSite policy
* @param {boolean} [options.secure] - Whether cookie is HTTPS-only
* @returns {Function} Express/Connect middleware function
*/
function cookieSession(options)Access and manipulate session data through the req.session property.
/**
* Session object attached to request
* @property {boolean} isChanged - True if session has been modified during request
* @property {boolean} isNew - True if this is a new session
* @property {boolean} isPopulated - True if session contains any data
*/
interface Session {
isChanged: boolean;
isNew: boolean;
isPopulated: boolean;
// Any additional properties can be set dynamically
[key: string]: any;
}Usage Examples:
// Set session data
req.session.userId = 123;
req.session.username = 'alice';
// Read session data
const userId = req.session.userId;
const isLoggedIn = !!req.session.userId;
// Check session state
if (req.session.isNew) {
console.log('New session created');
}
if (req.session.isChanged) {
console.log('Session data has been modified');
}
// Destroy session
req.session = null;Override session options on a per-request basis.
/**
* Session options for the current request
* Shallow clone of middleware options that can be modified per-request
*/
interface SessionOptions {
name: string;
keys: string[];
signed: boolean;
httpOnly: boolean;
overwrite: boolean;
maxAge?: number;
expires?: Date;
path?: string;
domain?: string;
partitioned?: boolean;
priority?: string;
sameSite?: boolean | string;
secure?: boolean;
}Usage Example:
// Set different maxAge for specific users
app.use(function (req, res, next) {
if (req.session.isPremium) {
req.sessionOptions.maxAge = 30 * 24 * 60 * 60 * 1000; // 30 days
} else {
req.sessionOptions.maxAge = 24 * 60 * 60 * 1000; // 1 day
}
next();
});Standard cookie options passed through to the underlying cookies library:
The middleware throws errors in these situations:
// Missing keys when signing is enabled (default)
cookieSession({ signed: true }); // Throws: '.keys required.'
// Invalid session assignment
req.session = "invalid"; // Throws: 'req.session can only be set as null or an object.'Common error handling patterns:
// Graceful session loading (corrupted cookies are ignored)
app.use(function (req, res, next) {
if (req.session.isNew && req.headers.cookie) {
console.log('Previous session cookie was invalid or corrupted');
}
next();
});
// Validate session data
app.use(function (req, res, next) {
if (req.session.userId && typeof req.session.userId !== 'number') {
req.session = null; // Reset corrupted session
}
next();
});// Example: Add expiration validation
app.use(function (req, res, next) {
if (req.session.expiresAt && Date.now() > req.session.expiresAt) {
req.session = null; // Expired session
} else if (req.session.userId) {
// Extend session on activity
req.session.expiresAt = Date.now() + (30 * 60 * 1000); // 30 minutes
}
next();
});