I'm new to socket.io.
I've implemented a user login using express-session. In req.session.user
I've stored the userinformatiuon so that I can access it later (it works).
Now I want to acces these information in my socket. I've discovered that you can use the package express-socket.io-session to access the session in socket.io with socket.handshake.session
. But the property socket.handshake.session.user
is undefined when I try to access it.
It would be great if anyone knows how this works and could help me with this problem because I couldn't find any solution or help through searching the internet.
This: How to share sessions with Socket.IO 1.x and Express 4.x? for example didn't work for me.
Cheers
This is my code:
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const expressSession = require('express-session');
const sharedsession = require("express-socket.io-session");
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io').listen(http);
app.set('port', process.env.PORT || 3001);
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({
key: 'userID',
secret: 'k39dzqlp@k5d&k@dh&',
saveUninitialized: false,
resave: false,
cookie: {maxAge: 1200000}
}));
io.use(sharedsession(expressSession({
key: 'userID',
secret: 'k39dzqlp@k5d&k@dh&',
saveUninitialized: false,
resave: false,
cookie: {maxAge: 1200000}
})));
app.route('/login')
.post((req, res) => {
//I get user from my database
req.session.user = user.dataValues;
res.redirect('home');
});
});
app.listen(app.get('port'));
io.on('connection', (socket) => {
console.log(socket.handshake.session.user); //user is undefined
});