I am building a MEAN stack chat application. And I want to be able to get express session id inside socket.io on connection handler. I am able to access the socket.handshake.session.id but it is not the same as req.session.id. Further socket.handshake.session.id keeps changing on every socket.
I have tried to solve this by getting session id from req.handshake.cookie by looking for connect.sid key but this key is not defined in there.
const cors = require('cors'),
express = require('express'),
eSession = require('express-session'),
cookieParser = require('cookie-parser'),
MongoStore = require('connect-mongo')(eSession),
sharedsession = require('express-socket.io-session'),
http = require('http'),
bodyParser = require('body-parser'),
socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const port = process.env.PORT || 3000;
//imports
const mongoose = require('./config/dbconnection');
//routes
const user = require('./api/routes/user');
const socketHandle = (io, mStore) => {
io.on('connection', (socket) => {
socket.on('join', (options, callback) => {
console.log(socket.handshake.headers.cookie); //no connect.sid string present
console.log(socket.handshake.session.id) // has value but keeps changing on each io connection and this id is not the same as req.session.id in an api endpoint method
});
});
const corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200
};
const db = mongoose.connection;
const mStore = new MongoStore({ mongooseConnection: db });
const session = eSession({
secret: 'my-secret',
resave: true,
saveUninitialized: true,
store: mStore
});
app.use(cookieParser('my-secret'));
app.use(session);
io.use(sharedsession(session,{autoSave:true}));
socketHandle(io, mStore);
//body-parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors(corsOptions));
app.use('/user', user);
server.listen(port, () => console.log(`listening on http://localhost:${port}`));
Both socket.handshake.session.id and socket.handshake.headers.cookie(connect.sid key)should have provided the session id that has the same value as req.session.id
There was not any issue with my code. The only thing that was causing different session id was the fact that I was running angular on a different port than node server. I had to ng build --watch for angular and output the files in node server's static files folder. By doing this, I was able to get consistent session id both in routes and socket io.