I'm using Socket.io
in a chat application I'm building. I'm trying to setup the session so that I can persist the login of the users in between sessions.
Here's the relevant code :
index.js (server)
var cookieParser = require('cookie-parser')();
var session = require('cookie-session')({ secret: 'secret' });
app.use(cookieParser);
app.use(session);
io.use(function(socket, next) {
var req = socket.handshake;
var res = {};
cookieParser(req, res, function(err) {
if (err) return next(err);
session(req, res, next);
});
});
io.on('connection', function(socket){
socket.on('test 1', function(){
socket.handshake.test = 'banana';
});
socket.on('test 2', function(){
console.log(socket.handshake.test);
});
});
chat.js (client)
var socket = io();
socket.emit('test 1');
socket.emit('test 2');
The code above works, it will print banana
to the console as expected. However, if I comment out the 'test 1' like so :
var socket = io();
// socket.emit('test 1');
socket.emit('test 2');
It will print undefined
to the console.
Shouldn't it still be able to print banana
, since it's using a session and it's persisting between requests? I also run into the same issue if I inverse the order in which I call 'test 1' and 'test 2'.
What am I doing wrong? What am I missing for the session to persist as expected?