Socket.IO Express Session Middleware
raw JSON →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.
Common errors
error TypeError: require(...) is not a function ↓
require syntax: const ioSession = require('socket.io-express-session');. error TypeError: Cannot read properties of undefined (reading 'session') when accessing socket.handshake.session ↓
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. ↓
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. Warnings
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. ↓
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. ↓
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. ↓
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. ↓
Install
npm install socket.io-express-session yarn add socket.io-express-session pnpm add socket.io-express-session Imports
- ios wrong
import ios from 'socket.io-express-session';correctconst ios = require('socket.io-express-session'); - ios (main function) wrong
const { connectSession } = require('socket.io-express-session');correctconst connectSession = require('socket.io-express-session'); - ios (TypeScript) wrong
import { SessionMiddleware } from 'socket.io-express-session';correct/// <reference types="node" /> // No official TypeScript types exist, manual declaration or @types/module-name might be needed for older packages.
Quickstart
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}`);
});