I am building a chat application with an online/offline feature, using firebase rest API as my backend (without JS SDK).
First I try to implement a solution on the client-side only:
- Detect that the user disconnected (leave the site)
- Update a dedicated path in the RealTime DB - (/userStatus/{userId}/{online||offline})
Similar to the next tutorial: https://firebase.google.com/docs/firestore/solutions/presence
But it didn't work.. the WebSocket onClose or window.onbeforeunload events didn't catch all scenarios.
Second I try to build a server-side solution that checks when the Firebase Websocket is a life. but I didn't find any clue on how to achieve that.
So I come up with the last brute-force solution:
- update the online endPoint every minute with the last userConnectionTime
- Users with lastConnectionTime < now - 1 minute = disconnected.
But this solution means that I need to update the Db every minute for all users, and each user needs to listen to all of his contacts and will receive every minute an irrelevant message with the lastConnectedTime.
This solution is not ideal... My question is does anyone have another better one? Thank you
When using Firebase's
onDisconnecthandlers, there are two types of disconnects:onDisconnecthandlers straight away.onDisconnecthandlers when the socket times out (typically after a few minutes).It sounds like your first approach should have worked, and is in fact the simplest way to do this as Firebase takes care of most of the hard work for you. Firebase has an
onunloadhandler that on most cases can do a clean disconnect, but even when it can't - the server should run theonDisconnecthandlers when it detects that the client is gone.If you're having trouble making this work, I recommend posting a minimal reproduction of the problem so we can help you troubleshoot.