Track users online status
How to track users online status
If you want to detect if a user is online in the app, meaning the user is logged in and has the app open in a browser tab, just follow this process:
First we need to save to the database the moment the user is active in the app. For that we are going to use the 'Last active' user field.
Be aware that if you save to the database using a 'Make change to thing...' action directly in a Do every X seconds, this would be overkill to the page performance and, therefore, its UX.
What we are going to do is use Bubble's Data API, making an API call so the change to the user object is made in the server and the page performance is not going to be affected.
PATCH API Call
Then, when you need to check if a user is online or not, you'll compare the Current date/time with the user 'Last active' date. If the difference between those two dates is less or equal to X seconds (let say 10 seconds), the user is 'online'.
- 1.Add a workflow to the header with just one action that makes an API call every 10 seconds, only if the user is logged in to prevent unnecessary writings to the db, and updates the existing 'Last active' user field for the Current user by sending the Current Date/Time: extract UNIX (so there are no issues with the possible different timezones).
- 2.Where you need to know a user online status, just calculate: Current date/time minus User's Last active is less or equal to 10 seconds or whatever other duration we used in step 1.
- 3.Other: enable Data API, enable modifying the Data type with API, set privacy rules accordingly. And be aware that you are allowing users to see the last time other users were active in the app.
Adding the step 1 workflow to the header will track the user status in all the app pages that contain the header. If you have pages without header where you'd want to track the user, add the workflow there too.
- Send new chat email notifications (or any other notification), only if the user is not online
- Filter users by their online status
- Show users online status in their profiles
This method detect if the user is active in the app, what we usually call 'online', meaning the user is logged in and has the app open in a browser tab.
If you want to detect if the user is actually logged out, you could add a field 'Logged in?' of type yes/no and toggle it when the user logs in or logs out, but if the user is automatically logged out you wouldn't have any way to know it.