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?