title: Keeping track of SocketID in NodeJs and Express
body: <p>After playing around a bit i found out the hard way that the socket.io will change the socketId on a socket reconnection. That said i am looking into a way for my NodeJs to keep track of changes to the socketID. Socket has a build in store which keeps track of SocketId's , Remote addresses etc. How reliable is that store and can i query a socketID quickly by a UserID which i stored in that db ?
  I also found some docs on that one can set its own SocketID which has to be unique but does this allow me to avoid to issue a new SocketID on refresh or is that still not possible.
  Instead of SocketID, is there a way to send a message to a client based on a USERID  instead ?
  If neither of the above work, i guess i will be back to drawing board and store session info in a DB table and update the data.</p>
  
  <p>Many questions but hopefully someone can share some inside with me</p>
  
  <p>Here is my SocketIO helper class i use</p>
  
  <pre><code>const io = require('socket.io');
  class ioWrapper {
  
  constructor(app, { middlewares, updateSession, clearSession } = {}) {
      this.io = io(app);
      this.connected = {};
  
      if (middlewares &amp;&amp; middlewares.length) {
          for (const middleware of middlewares) {
              this.io.use(middleware);
          }
      }
  
      this.io.on('connect', client =&gt; {
          //put callback to constructor to update your session
          if (updateSession) {
              updateSession(client.id);
              console.log('Updated: ' + client.id)
          }
          client.jwt = client.id
          this.connected[client.id] = client;
  
  
  
  
          console.log('Connected: ' + client.id + '  ' )// + this.io.socket.request.connection.remoteAddress)
  
          client.on('disconnect', () =&gt; {
              if (clearSession) {
                  clearSession(client.id);
              }
              if (this.connected[client.id]) {
                  delete this.connected[client.id];
              }
              console.log('Disconnect: ' + client.id )
          });
  
          client.on('error', e =&gt; console.log(e));
          client.on('connect_error', e =&gt; console.log('connect_error', e));
  
      });
  
      this.ioEmit = this.ioEmit.bind(this);
      this.ioInject = this.ioInject.bind(this);
  }
  ioEmit(socketId, event) {
      try {
          if (this.connected[socketId]) {
              this.connected[socketId].emit(...event);
          }
      }
      catch (e) {
          console.log(e);
      }
  }
  ioInject(socketId, handler) {
      try {
          if (this.connected[socketId]) {
              this.connected[socketId].on(...handler);
          }
      }
      catch (e) {
          console.log(e);
      }
  }
  }
  
    module.exports = (app, middleware, updateSession) =&gt; new ioWrapper(app, middleware, updateSession);
  </code></pre>