why deepstreamHub? compare us getting started feature roadmap faq
use cases pricing
products
developers
company
blog contact

Deepstream's presence feature allows the users in your application to track the online or offline status of other users.

Essentially, it is possible to ask presence to either send you a list of all the people who are currently logged in or to send you a notification whenever the login status of the client who is already authenticated changes. Presence comes with the following three methods:

getAll(), subscribe() and unsubscribe()

Using presence

Using the getAll() method we can retrieve the status of all the connected clients at any particular time. It would look like the following:

client.presence.getAll((usernames) => {
  // [ 'userA', 'userB', 'userC' ]
})

The above function would return all the users who are currently logged in.

Whereas the subscribe() and unsubscribe() methods enable or disable continous observation of client logins. In simple terms, when you subscribe using presence, you receive a notification whenever an existing client logs out or a new client logs in.

As the term itself suggests, if you already subscribed to notifications but no longer wish to continue receiving notifications, simply use the unsubscribe() method.

Here's an example of how :

function presenceCallback(username, login) {
  if (login === true) {
    // handle login
  } else {
    // handle logout
  }
}
// Client A
client.presence.subscribe(presenceCallback)

// Client A
client.presence.unsubscribe(presenceCallback)

In the above subscribe function, the server returns the username along with the login status everytime this changes for any connected user.

It is important to understand that if a user logs in on multiple devices, only the first login instance and the last logout instance will be counted as a legitimate state change by presence. Hence, if you log into multiple devices and log out of one of them, your status remains as logged in until you log out of each and every device/browser.

Presence is important because it is the only way to know the connection status of a user and further query on it for any use cases.

Video Demo

The following is a short video of Alex Harley explaining in detail about presence in deepstream.