K
K
kranopodem2016-03-08 17:37:41
Node.js
kranopodem, 2016-03-08 17:37:41

How to bind Socket.IO to express-sessions?

I can not combine sessions with Socket.io in any way. I log in through Passport.js and I need to remember this and work as with one client, but after every page update, the Socket works for me as with different users, I can’t combine it in any way.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Q
Quickerz, 2016-03-09
@Quickerz

Option 1. We write our own middleware that will fumble the session

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("socket.io")(server);

var sessionMiddleware = session({
    store: new RedisStore({}), 
    secret: "secret",
});

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

app.use(sessionMiddleware);

app.get("/", function(req, res){
    req.session 
});

sio.sockets.on("connection", function(socket) {
  socket.request.session // Теперь сессия доступна через сокет
});


server.listen(8080);

Option 2. We use https://github.com/techpines/express.io
The option is working, but there are nuances with the express API. It is a bit outdated in places.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question