6

I am currently trying to implement session management using express 4.x and socket io 1.4, referencing this answer. The problem is that the second argument to the express session function is the res (response) object which is returning 'undefined' in my route. Is this question outdated or am I doing something wrong?

var http = require('http');

var session = require('express-session')(
{
  saveUninitialized : false,
  resave:false,
  secret:'secretstuff',
  cookie : {
    path : '/'
  }
}
);

var express = require('express');

var app = express();

app.use(session)

var http_server = http.createServer(app);

var io = require('./sockets')(http_server,session);

here is my sockets.js

var Server = require('socket.io');

module.exports = function(http_server, session)
{
   var io = new Server(http_server);

   io.use(function(socket,next){

      //socket.request.res === undefined
      session(socket.request, socket.request.res,next);
   })

}

which is where I get

Uncaught TypeError: argument res is required

Community
  • 1
  • 1
naughty boy
  • 1,779
  • 2
  • 12
  • 26
  • 2
    same issue, still relevant – Flion Jan 30 '17 at 06:16
  • I am experiencing the same problem as well! I had it working a while back ago, but I don't know what's changed. – decoder7283 Jun 07 '18 at 05:09
  • 2
    The answer, get rid of `socket.request.res` and just use `{}`, it's gawwbage!!....https://github.com/socketio/socket.io/issues/2971 `session(socket.request, socket.request.res,next) -> session(socket.request, {},next)` – decoder7283 Jun 07 '18 at 05:27
  • @indospace.io I think Your comment could be added as an answer. However I've found a little bit better workaround, see mine answer below. – Aleksey Kontsevich Dec 05 '18 at 21:15

1 Answers1

6

sessionMiddleware() function proposed in many sources worked fine for me:

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

with web socket.io-client <=> socket.io node.js server until I added socket.io-client-cpp application to the chain - server crashed on socket.io-client-cpp connection with above error:

TypeError: argument res is required

in sessionMiddleware() function. People suggest to remove socket.request.res from the middleware completely:

and replace with {}. However think it could be changed to slightly better variant in case somebody still need and use socket.request.res:

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

This works fine for me!

Aleksey Kontsevich
  • 3,639
  • 3
  • 36
  • 89