Cookie Session Middleware

2.1.1 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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

view raw JSON →