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

Sometimes, we want to share sessions with Socket.IO 1.x and Express 4.x.

In this article, we’ll look at how to share sessions with Socket.IO 1.x and Express 4.x.

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

To share sessions with Socket.IO 1.x and Express 4.x, we can use the express-session package.

For instance, we write

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

const app = express();
const server = Server(app);
const sio = require("socket.io")(server);

const sessionMiddleware = session({
  store: new RedisStore({}),
  secret: "keyboard cat",
});

sio.use((socket, next) => {
  sessionMiddleware(socket.request, socket.request.res || {}, next);
});

app.use(sessionMiddleware);

app.get("/", (req, res) => {
  console.log(req.session)
});

sio.sockets.on("connection", (socket) => {
  console.log(socket.request.session)
});


server.listen(8080);

to call session to create the sessionMiddleware.

Then we call sio.use with a callback that calls session with the socket.io request and response objects and the next function` to call the next middleware.

Next, we call app.use with sessionMiddleware to use the session middleware.

Now the Express middlewares that come after app.use(sessionMiddleware) should have the session data available in req.session.

And socket.request.session has the value of the session in the sio.sockets.on handler since sio.sockets.on is called after app.use(sessionMiddleware)

Conclusion

To share sessions with Socket.IO 1.x and Express 4.x, we can use the express-session package.