Mustafa Mustafa - 1 year ago 104
Node.js Question

How to share sessions with Socket.IO 1.x and Express 4.x?

How can I share a session with 1.0 and Express 4.x? I use a Redis Store, but I believe it should not matter. I know I have to use a middleware to look at cookies and fetch session, but don't know how. I searched but could not find any working

var RedisStore = connectRedis(expressSession);
var session = expressSession({
store: new RedisStore({
client: redisClient
secret: mysecret,
saveUninitialized: true,
resave: true

io.use(function(socket, next) {
var handshake = socket.handshake;
if (handshake.headers.cookie) {
var str = handshake.headers.cookie;
} else {
next(new Error('Missing Cookies'));

Answer Source

The solution is surprisingly simple. It's just not very well documented. It is possible to use the express session middleware as a Socket.IO middleware too with a small adapter like this:

sio.use(function(socket, next) {
    sessionMiddleware(socket.request, socket.request.res, next);

Here's a full example with express 4.x, Socket.IO 1.x and Redis:

var express = require("express");
var Server = require("http").Server;
var session = require("express-session");
var RedisStore = require("connect-redis")(session);

var app = express();
var server = Server(app);
var sio = require("")(server);

var sessionMiddleware = session({
    store: new RedisStore({}), // XXX redis server config
    secret: "keyboard cat",

sio.use(function(socket, next) {
    sessionMiddleware(socket.request, socket.request.res, next);


app.get("/", function(req, res){
    req.session // Session object in a normal request

sio.sockets.on("connection", function(socket) {
  socket.request.session // Now it's available from Socket.IO sockets too! Win!