Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express-session and express-socket.io-session not working in angular2 / typescript environment

I have a script.js setting the server up that goes like this:

var io_session = require("express-socket.io-session");

var e_session = require("express-session")({
    secret: "a-secret",
    resave: true,
    saveUninitialized: true
});

(...)

//this block is the last "io.use" before the socket logic (io.on("connection"))    
io.use(io_session(e_session,{
    autoSave: true
}));

In my typescript / angular2 frontend enviroment using the following seed https://github.com/NathanWalker/angular2-seed-advanced I perform http requests in several services / components using the Http class.

However, when I try to request the server again for something I try to log the user session, nothing is logged... I don't really know why this is happening as not only the session for the user is not being kept but also the session is not being shared from the http to the socket layer system (as obviously, if it isn't created it isn't also being shared).

Does anyone know what might be wrong here? I can provide more info if needed but I don't really know what is missing.

like image 914
Fane Avatar asked Nov 26 '16 02:11

Fane


1 Answers

You can have socket.io run with Express easily. By simply invoking socket.io’s listen method and passing it the Express Session as a Middleware(Assuming you are storing all your sessions in FileSystem and not in Redis). I have made a replication of your Code which goes as follows:

    var e_session = require("express-session"); 
    var io_session = require("socket.io")(server); 
    //Storing sessions in file system
    var sessionFileStore = require('session-file-store')(Session);

    //Express-Sessions as middleware
    var e_sessionMiddleware = e_session({
        store: new sessionFileStore({ path: './project-x/sessions' }),
        secret: 'pass',     resave: true,
        saveUninitialized: true 
    });
    //Use of Express-Session as Middleware    
    io_session.use(function(socket, next) {
       e_sessionMiddleware(socket.handshake, {}, next); 
    });

    //Socket Io session and express sessions are now same 
    io_session.on("connection", function(socket) {
       socket.emit(socket.handshake.session);
    });

Hope it helps! Thank You!

like image 177
Rohit Rai Avatar answered Sep 22 '22 17:09

Rohit Rai