title: How to get persistent express session id in socket.io connection?
body: <p>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. </p>
  
  <p>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.</p>
  
  <pre><code>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) =&gt; {
     io.on('connection', (socket) =&gt; {
       socket.on('join', (options, callback) =&gt; {
  
       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, () =&gt; console.log(`listening on http://localhost:${port}`));
  </code></pre>
  
  <p>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</p>