Socket.IO Express Session Middleware

raw JSON →
0.1.3 verified Thu Apr 23 auth: no javascript abandoned

This package, `socket.io-express-session`, provides middleware to integrate and share `express-session` instances with `socket.io`. It allows developers to access the same session object (`socket.handshake.session`) within Socket.IO connection handlers that they would normally access via `req.session` in an Express application. The package is extremely old, with its latest version (0.1.3) published over 10 years ago in September 2015. Due to its age, it is considered abandoned and does not support modern JavaScript module systems (ESM) or recent versions of `express-session` and `socket.io` without potential compatibility issues. Modern applications typically integrate `express-session` with `socket.io` directly by using the `sessionMiddleware` within `io.engine.use()` or `io.use()` with a custom wrapper, as shown in current Socket.IO documentation.

error TypeError: require(...) is not a function
cause Attempting to use ES Module `import` syntax (`import ioSession from 'socket.io-express-session';`) for this CommonJS-only package, or misinterpreting its export.
fix
Use CommonJS require syntax: const ioSession = require('socket.io-express-session');.
error TypeError: Cannot read properties of undefined (reading 'session') when accessing socket.handshake.session
cause This error typically occurs if the `socket.io-express-session` middleware was not correctly applied to the Socket.IO instance (`io.use(ios(session))`) or if the `express-session` configuration itself is not correctly initialized or shared. It can also happen if the client does not send the session cookie.
fix
Verify that io.use(ioSession(sessionMiddleware)) is called after sessionMiddleware is defined and app.use(sessionMiddleware) is set up. Ensure client-side socket.io-client connections are configured with withCredentials: true if cookies are expected to be sent. Double-check that secret, store, and other critical session options are identical between Express and Socket.IO setups.
error Session data not persisting across Socket.IO reconnections or page refreshes.
cause This is often due to using the default `MemoryStore` in a multi-process or scaled environment, or if the `secret` key or session `store` instance is not identical between Express and Socket.IO, leading to new sessions being created. Cross-origin issues without proper CORS configuration can also cause this.
fix
Migrate from MemoryStore to a production-ready session store (e.g., Redis). Ensure the *same instance* of the session configuration (especially secret and store) is passed to both Express and Socket.IO. For cross-origin setups, configure CORS headers appropriately on your server and withCredentials: true on the Socket.IO client.
breaking The package is over 10 years old and has been abandoned. It is not compatible with modern ES Modules (ESM) syntax and may have severe compatibility issues or security vulnerabilities with current versions of Node.js, Socket.IO, or Express.js.
fix Migrate to a more modern solution. The official Socket.IO documentation provides direct examples of integrating `express-session` using `io.use(sessionMiddleware)` or `io.engine.use(sessionMiddleware)` without relying on this deprecated package.
gotcha Using the default `MemoryStore` for `express-session` in a production environment is strongly discouraged. It can lead to memory leaks and will not scale across multiple process instances or servers, causing inconsistent session data.
fix Always configure `express-session` with a persistent, production-ready session store like Redis (`connect-redis`), MongoDB (`connect-mongo`), or a database-backed store for any non-trivial application. Ensure the store is accessible by all Node.js instances if scaling horizontally.
gotcha It is critical to pass the *exact same* `express-session` configuration (including the `store`, `secret`, and other options) to both your Express application and the `socket.io-express-session` middleware. Mismatched configurations will result in session data not being shared or incorrect session identification.
fix Declare your `express-session` middleware once with all its configuration, and then pass that *instance* of the middleware to both `app.use()` and `io.use(ioSession(...))`.
deprecated `express-session` itself has deprecated the `undefined resave option` and `undefined saveUninitialized` options. While not directly a `socket.io-express-session` warning, using an old version of `express-session` with this middleware could lead to warnings or unexpected behavior if these options are not explicitly set.
fix Ensure `resave` and `saveUninitialized` are explicitly set to `true` or `false` in your `express-session` configuration. For new projects, use modern `express-session` versions and the recommended direct integration patterns.
npm install socket.io-express-session
yarn add socket.io-express-session
pnpm add socket.io-express-session

This quickstart demonstrates how to set up `socket.io-express-session` to share Express sessions with Socket.IO connections, allowing access to `socket.handshake.session`. It includes basic Express and Socket.IO server initialization and highlights session access within Socket.IO connection handlers.

const express = require('express');
const { createServer } = require('http');
const session = require('express-session');
const { Server } = require('socket.io');
const ioSession = require('socket.io-express-session'); // The package being documented

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);

// IMPORTANT: Use a production-ready session store, not MemoryStore for production.
const sessionMiddleware = session({
  secret: 'my-super-secret-key-that-should-be-long-and-random',
  resave: false,
  saveUninitialized: true,
  // store: new (require('connect-redis')(session))({ client: require('redis').createClient() })
});

app.use(sessionMiddleware);

// Integrate express-session with Socket.IO
io.use(ioSession(sessionMiddleware));

io.on('connection', (socket) => {
  console.log('A user connected:', socket.id);
  // Access the session from the handshake object
  const userSession = socket.handshake.session;
  if (userSession) {
    console.log('Session data on connection:', userSession);
    userSession.views = (userSession.views || 0) + 1;
    console.log('Updated views:', userSession.views);
    // In older packages, you might need to manually save if 'autoSave' isn't configured/available.
    // userSession.save(); // Not explicitly mentioned as needed by this package
  }

  socket.on('disconnect', () => {
    console.log('User disconnected:', socket.id);
  });
});

app.get('/', (req, res) => {
  req.session.pageViews = (req.session.pageViews || 0) + 1;
  res.send(`Hello from Express! Page views: ${req.session.pageViews}`);
});

const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});