Detect if the User is online or not

Detect if the User is online or not

Sometimes you may need to know the user's current visibility status (online or offline). Let's discuss some ways to do that.

1. Detect the user's status using WebSocket

You can track status at realtime using that method, but it's a bit costly way. The method is simple. Just put online status when the user connected to your server using WebSocket. Als you can know when the user disconnects from your server. Then set his status to offline.

2. Detect user's status using the simple ping/pong

When the user is browsing on your website online you just need to ping your web server to know that the user is online. You may save last ping timestamp to your database and then check delta between the current time and last ping timestamp. If the delta is bigger than ping interval that means the user is offline.

// front.js
function ping() {
  fetch('/ping').finally(function () {
    setTimeout(function() {
      ping();
    }, 3000);
  });
}


// back.js
app.get('/ping', function (req, res) {
  User.query().patch({
    lastPing: Date.now()
  }).where(...).then(function () {
    res.send('pong');
  });
});


// user.js
class User extends Model {
  ...
  get isOnline() {
    // Not 3000ms, because the user's network connection may be slow
    return (Date.now() - this.lastPing) > 5000;
  }
}