title: When new user connects the previous connection becomes the new user
body: <p>I've been playing around a bit with NodeJS and recently socket.IO, I come from PHP development and try to understand really how to work with Node and socket.IO</p>
  
  <p>I started building a chat app and when I were to test it on different devices I noticed that when I for instance log in to another account through my phone, the browser window updates and gets the same user as I logged into on my phone</p>
  
  <p>index.html</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;title&gt;Socket.IO chat&lt;/title&gt;
      &lt;style&gt;
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font: 13px Helvetica, Arial; }
        form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
        form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
        form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; }
        #messages li:nth-child(odd) { background: #eee; }
      &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;div id="chatLogin"&gt;
          &lt;input type="text" name="password" id="username" placeholder="Username..." /&gt;&lt;br&gt;
          &lt;input type="password" name="password" id="password" placeholder="Password..." /&gt;&lt;br&gt;
          &lt;button id="chatLoginBtn"&gt;Login / Register&lt;/button&gt;
      &lt;/div&gt;
      &lt;div id="chatWindow"&gt;
          &lt;ul id="messages"&gt;&lt;/ul&gt;
          &lt;form action=""&gt;
              &lt;input id="m" autocomplete="off" /&gt;&lt;button&gt;Send&lt;/button&gt;
          &lt;/form&gt;
      &lt;/div&gt;
  &lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;
  &lt;script src="https://code.jquery.com/jquery-3.4.1.min.js"&gt;&lt;/script&gt;
  &lt;script&gt;
  $(function () {
      var socket = io();
      $(document).ready(function(){
      $("#chatWindow").hide();
          $("#chatLoginBtn").click(function(){
              socket.emit('loginForm', {
                  username: $("#username").val(),
                  password: $("#password").val()
              });
          });
  
      });
  
  
  
  
  
      socket.on('returnValue', function(msg) {
              var html = '&lt;ul id="messages"&gt;&lt;/ul&gt;' + 
              '&lt;form id="sendMsg" action=""&gt;' + 
              '&lt;input id="m" autocomplete="off" /&gt;&lt;button&gt;Send&lt;/button&gt;' + 
              '&lt;/form&gt;';
              $("#chatLogin").html("").hide();
              $("#chatWindow").html(html).show();
  
                $('#sendMsg').submit(function(e) {
                  e.preventDefault(); // prevents page reloading
                  var time = Date.now();
                  var msg = $("#m").val();
                  var data = [time, msg];
                  socket.emit('chat', data);
                  $('#m').val('');
                  return false;
              });
          });
  
      socket.on('chat', function(msg){
        $('#messages').append($('&lt;li&gt;').text(msg));
      });
    });
  &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>index.js</p>
  
  <pre><code>var app = require('express')();
  var http = require('http').createServer(app);
  var phpPass = require('node-php-password');
  var mysql = require('mysql');
  var io = require('socket.io')(http);
  var cookieParser = require('cookie-parser');
  var session = require('express-session');
  
  // DECLARE the variables we will be using
  
  // These does not change
  let userCount = 0;
  
  // These are declared to be later set
  
  var displayName;
  var userDataID;
  
  
  // POOL MySQL Connection
  
  var pool    =    mysql.createPool({
        connectionLimit   :   100,
        host              :   'localhost',
        user              :   'root',
        password          :   '....',
        port              :   '3306',
        database          :   '....',
        debug             :   false
  });
  
  // session &amp; cookieParser
  
  /*var sessionMiddleware = session({
      secret: "keyboard cat"
  });
  
  io.use(function (socket, next) {
          sessionMiddleware(socket.request, socket.request.res, next);
  });
  app.use(sessionMiddleware);
  app.use(cookieParser());*/
  
  app.get('/', (req, res) =&gt; {
    res.sendFile(__dirname + '/index.html');
  });
  
  var hashPassword;
  
  
  
  function checkUser(user, Password, userID) {
      pool.getConnection(function(error,connection) {
          connection.query("SELECT password FROM accounts WHERE `username` = '"+user+"' LIMIT 1",function(error,rows){
              if (!error) {
              var hashPassword = rows[0].password;
  
              if (phpPass.verify(Password, hashPassword)) {
                  console.log(Password);
                  console.log(hashPassword);
                  console.log("Went well");
  
                  // UPDATE user database with current socketID
  
                  connection.query("UPDATE accounts SET `socketID` = '"+userID+"' WHERE `username` = '"+user+"'",function(error,result){
                      connection.release();
                      if (!error) {
                          connection.query("SELECT id,displayName,username,email,fullName,dateofBirth,created,lastSignedIn FROM accounts WHERE socketID = '"+userID+"' LIMIT 1",function(error,userData){
                              if (!error) {
                                  displayName = userData[0].displayName;
                                  userDataID = userData[0].id;
                                  console.log("Current user: " + userData[0].displayName);
                              } else {
                                  console.log("Error" + error);
                              }
  
                          });
  
                          console.log("No error" + result);
                      } else {
                          console.log("We found error" + error);
                      }
                  });
  
                  // send to function to gather all needed info from database and save for the current session
  
  
  
                  return true;
              } else {
                  console.log("Wrong pass");
                  return false;
              }
  
              console.log(hashPassword);
              } else {
                  console.log(error);
                  return false;
              }
          });
          connection.on('error', function(error) {
  
          });
      });
          return true;
  };
  
  
  io.on('connection', (socket) =&gt; {
  
      var req = socket.request;
      var userID = socket.id;
  // When connection is inited
  
      userCount++;
  
      console.log('User connected' + userCount);
  
      // Take the data from login and pass to check if it is valid
  
      socket.on("loginForm", function(data){
          const user = data.username,
          pass = data.password;
          //console.log(checkUser(user, pass));
          if (checkUser(user, pass, userID)) {
              io.emit('returnValue', 'hi');
          }
      });
  
      function joinRoom(room) {
          socket.join(room);
          console.log("Joined " + room);
          return io.emit('chat', "Joined new room " + room);
      }
  
      socket.on('join', (data) =&gt; {
          socket.join(data);
          console.log("Joined " + data);
      });
  
  
      socket.on('chat', (data) =&gt; {
  
          /* Array: Data;
          [0] Time
          [1] Message
  
  
          [2] socketID
          [3] User        
          */
  
          var msg = data[1];
          var time = data[0];
  
  
  
          // Calc time
  
          var date = new Date(time);
          var hours = date.getHours();
          var minutes = date.getMinutes();
          var formatted = hours + ":" + minutes;
          if (minutes &lt; 10) return minutes = "0" + minutes;
          var dateFormatted = "[" + formatted + "] ";
  
          //data.push(user);
  
          pool.getConnection(function(error,connection) {
          connection.query("INSERT INTO `chat_messages` (userID, socketID, message, time) VALUES ('"+userDataID+"', '"+userID+"', '"+msg+"', '"+time+"')",function(error,rows){
              connection.release();
              if (!error) {
                  console.log("Success");
              } else {
                  console.log(error);
              }
          });
          });
  
  
          if (msg.startsWith('/me')) return io.emit('chat', dateFormatted + displayName + msg.substring(3));
          if (msg.startsWith('/join')) return joinRoom(msg.substring(6));
          if (msg.startsWith('/rooms')) return console.log(io.sockets.adapter.rooms);
  
          return io.emit('chat', dateFormatted + displayName + ' said: ' + msg);
          //console.log(displayName + 'said:' + msg);
      });
  
  // When user disconnects
    socket.on('disconnect', () =&gt; {
  
      userCount--;
  
      console.log('User disconnected!' + userCount);
    });
  
  
  });
  
  http.listen(3000, () =&gt; {
      console.log('Listening on *:3000');
  });
  </code></pre>
  
  <p>I do not get any errors and it counts the number of users correctly</p>
  
  <p>The problem is that the user first logged in gets switched to the last logged in user</p>
  
  <p>How do I make the user session unique and so multiple clients can be logged in into different accounts?</p>