or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-cookie-session

Cookie-based session middleware for Express applications that stores session data in client-side cookies

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/cookie-session@2.1.x

To install, run

npx @tessl/cli install tessl/npm-cookie-session@2.1.0

index.mddocs/

Cookie Session

Cookie 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.

Package Information

  • Package Name: cookie-session
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install cookie-session

Core Imports

const cookieSession = require('cookie-session');

For ES modules:

import cookieSession from 'cookie-session';

Basic Usage

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

Architecture

Cookie Session operates through several key components:

  • Middleware Factory: The main cookieSession() function creates middleware instances with specified configuration
  • Session Property: Adds req.session property that acts as a regular JavaScript object for storing data
  • Cookie Management: Uses the cookies library internally for secure cookie handling with signing support
  • Automatic Persistence: Monitors session changes and automatically writes cookies on response
  • Lazy Loading: Session data is loaded from cookies only when first accessed

Capabilities

Middleware Creation

Creates 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)

Session Management

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;

Session Options Override

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

Configuration Options

Core Options

  • name (string): Cookie name, defaults to 'session'
  • keys (string[]): Array of keys for signing cookies, enables key rotation
  • secret (string): Single key alternative to keys array
  • signed (boolean): Whether to sign cookies, defaults to true

Cookie Options

Standard cookie options passed through to the underlying cookies library:

  • maxAge (number): Expiration time in milliseconds from Date.now()
  • expires (Date): Absolute expiration date
  • path (string): Cookie path, defaults to '/'
  • domain (string): Cookie domain
  • partitioned (boolean): Enable Chrome CHIPS partitioning
  • priority (string): Cookie priority ('low', 'medium', 'high')
  • sameSite (boolean|string): SameSite policy ('strict', 'lax', 'none', true)
  • secure (boolean): HTTPS-only flag
  • httpOnly (boolean): HTTP-only flag, defaults to true
  • overwrite (boolean): Overwrite existing cookies, defaults to true

Error Handling

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

Security Considerations

  • No Encryption: Session data is only signed, not encrypted - avoid storing sensitive data
  • Key Rotation: Use multiple keys in the keys array to enable secure key rotation
  • Cookie Size Limits: Browser cookie size limits apply (~4KB total per domain)
  • Session Replay: No built-in expiration validation - implement custom expiration logic if needed
// 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();
});