0

I have Node/Express app for which I am trying to track active users.

The app relies on an external API to issue and receive JWT tokens. These tokens are passed directly to the client, where they are stored and used for subsequent API requests. That's to say, I'm not using Node "sessions".

I'm using socket.io to hook into a custom login, logout and the disconnect events. When these events fire I can update the DB (firebase) and add/remove active users as needed.

The problem is that my app is load balanced across several servers, so I can't key the active users by socket.id, because it might change. My thought was to key the active users by user_id, but, I can't figure out how to get the user ID from the disconnect event. The other events are triggered by the client so I can just send the user ID to the server...

client.js

import io from 'socket.io-client';

const socket = io('/');

socket.emit('login', {user_id: 1234, email: 'example@gmail.com'})

server.js

io.on('connection', (socket) => {
    const activeUsersRef = admin.database().ref('activeUsers');

    socket.on('login', (userData) => {
        activeUsersRef.update({
            [userData.user_id]: userData
        })
    });

    socket.on('logout', (userData) => {
        activeUsersRef.update({
            [userData.user_id]: null
        })
    });

    socket.on('disconnect', () => {

        // How to get user ID?
        activeUsersRef.update({
            [???]: null
        })

    });
});

How can I get access the user ID from the disconnect event if I'm not keeping track of user sessions in a Node server?

Himmel
  • 3,629
  • 6
  • 40
  • 77
  • 1
    I posted a previous answer [here](http://stackoverflow.com/questions/37591541/how-to-change-status-of-perticular-user-when-socket-is-disconnect/37592164#37592164) that might help – Rho Jan 23 '17 at 19:57

1 Answers1

0

I am not sure what your exact scenario is, but here is some code that worked for me:

io.on('connection', function(socket){

  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });

  socket.on('login', (userData) => {
        socket.on('disconnect', function () {
          console.log(userData);
        });
  });
});

Obviously you will need to change some minor things about how the userData is stored and displayed.

Hope this helps!

zoecarver
  • 5,523
  • 2
  • 26
  • 56