Q:

how to make to disconect event fires only when users log out from account (node.js + express+ socket.io)

I have a function to go out from account: 
exports.logout = function(req,res){
    req.session.destroy( err => {
        if(err)
            console.log(err);
       res.redirect("/login");
    });
 };

To use socket.io and express together I have a middleware:
io.use(function(socket, next) {
  sessionMiddleWare(socket.request, socket.request.res, next);
});

And I have function where I use socket.io. I need to disconect event fires only when user log out from application. But now my disconect event is emit always when I refresh a page: 
exports.someFunction = function (io) {

    io.on('connection', function(socket){
        console.log(`Client connected socketId = ${socket.id}`);
        console.log("session_id: " + socket.request.session.session_id);
        usersMap.set(socket.request.session.session_id, socket.id);

       });
          socket.on('disconnect', function(){
             usersMap.delete(socket.request.session.session_id);
             console.log('user disconnected');
             console.log("Map size: " + usersMap.size);     
          });
        });
};

Please help, how to make to disconect event fires only when users log out from account. Sorry for my English. 

A:

The disconnect event simply does not work the way you are asking for.  That event will fire any time the user navigates to a new page or refreshes the current page.  That's how socket.io connections work in the browser.  A given connection belongs to a particular page and when a new page is loaded, the prior connection is disconnected and then a new connection is created.  There is nothing you can do to change that - that's part of the browser architecture.  So, the socket.io disconnect event is simply not the same thing as when your user logs out and can never be the same.
Instead, you need to have your own function that does a logout which the user can trigger by some action in the page.  This can be either a socket.io message, an ajax call from your page or by navigating to the logout page.  That's how a user can logout and it has nothing to do with the disconnect event.
Similarly, a connect event just means that a user (who may or may not already be logged in) has connected.  The login state will be stored in either a cookie or in a server-side session (that is indexed by a cookie).

