Tutorials

Presence Tutorial

Presence enables clients to be aware of other clients that are currently “present” on a channel. Each member present on a channel has a self-assigned name — a “client ID” — along with an optional payload that can be used to describe the member’s status or attributes. Presence allows you to quickly build apps such as chat rooms and multiplayer games by automatically keeping track of who is present in real time across any device.

When someone enters or leaves a channel, or updates their member data, a presence event is emitted to all presence subscribers on that channel. Subscribing to presence events makes it incredibly easy to build an app that shows, in real time, any changes to clients connected to Ably and present on a channel.

The optional payload can be a string, JSON object, JSON array, or binary data, same as with message data.

Using our Presence API is easy. Let’s get started.

Step 1 – Set up a free account with Ably

In order to run these tutorials locally, you will need an Ably API key. If you are not already signed up, you should sign up now for a free Ably account. Once you have an Ably account:

  1. Log into your app dashboard
  2. Under “Your apps”, click on “Manage app” for any app you wish to use for this tutorial, or create a new one with the “Create New App” button
  3. Click on the “API Keys” tab
  4. Copy the secret “API Key” value from your Root key and store it so that you can use it later in this tutorial

    Copy API Key screenshot

Step 2 – Install Ably

To start using Ably in your web app, you first need to include the Ably library. We recommend that you include the latest client library from our CDN using a simple <script> tag. The client library must be instanced with the API key you copied in Step 1. As we’ll be using presence, we also include the clientId, which is what we’ll appear as in the presence set. Note that in production we recommend you always use the token authentication scheme for browser clients, however in this example we use an API key for simplicity.

Include the code below just before your closing your HTML </html> tag.

<script src="//cdn.ably.io/lib/ably.min-1.js"></script>

<script type="text/javascript">
  var realtime = new Ably.Realtime({key: apiKey, clientId: 'jamie'});
</script>

See this step in Github

To start using Ably you first need to install the NPM module. The NPM module can be installed as follows:

npm install ably

The client library must be instanced with the API key you copied in Step 1. API keys used with basic authentication for your own servers is generally preferred, however clients running on insecure devices should always use the token authentication scheme instead. In this example, we use an API key for simplicity.

Add the following to a file named example.js to instance the Ably library inside your Node.js server:

var Ably = require("ably");
var realtime = new Ably.Realtime({ key: apiKey });

See this step in Github

To start using Ably you first need to install the Ably RubyGem. The RubyGem can be installed as follows:

gem install ably

Or if using bundler, simply add the following to your Gemfile and run bundle install:

gem 'ably'

The client library must be instanced with the API key you copied in Step 1. API keys used with basic authentication for your own servers is generally preferred, however clients running on insecure devices should always use the token authentication scheme instead. In this example, we use an API key for simplicity. As we’ll be using presence, we also include the client_id, which is what we’ll appear as in the presence set.

The Ruby realtime library uses EventMachine to run the client library within an asynchronous event loop. However, typically when using Ruby on servers, most developers use the synchronous REST client library API. As this tutorial needs realtime access to be present and subscribe to presence messages, it uses the Ruby realtime library.

Add the following to a file named example.rb to instance the Ably library inside an EventMachine reactor:

require 'ably'
EventMachine.run do
  ably = Ably::Realtime.new(key: api_key, client_id: "jamie")
end

See this step in Github

Step 3 – Enter the presence set

With Ably, you can be attached to a channel (that is: be receiving messages published on that channel, or publishing them yourself) without necessarily being present on the channel. If you want to be present, and be seen by other users, you need to explicitly enter the presence set. For example, for a channel called “chatroom”:

var channel = realtime.channels.get('chatroom');
channel.attach(function(err) {
  if(err) { return console.error("Error attaching to the channel"); }
  console.log('We are now attached to the channel');
  channel.presence.enter('hello', function(err) {
    if(err) { return console.error("Error entering presence"); }
    console.log('We are now successfully present');
  });
});
channel = ably.channels.get('chatroom')
  channel.attach do
    channel.presence.enter(data: 'hello') do
      puts "We are now in the presence set"
    end
  end
end

See this step in Github

We’re now in the presence set. The name we’ll appear as is the client ID that we included in the Realtime constructor in step 2.

Similarly, we can call channel.presence.leave to leave the presence set.

(Side note: while in this tutorial we had free choice of client ID, in most situations you don’t want that. Instead you want your server to constrain what client ID people can use — for example, to their logged-in username — so that no-one can pretend to be someone else. When using Token authentication, your server can issue tokens with a specific client ID. When such a token is used by someone, their connection is bound to that client ID.)

A single client ID may be present multiple times on the same channel, via different client connections; but each will be seen as a different member of the presence set, as they are differentiated by their unique connection ID. For example, if a client with client ID “Sarah” is connected to a chat channel on both a desktop and a mobile device simultaneously, “Sarah” will be present twice in the presence member set with the same client ID, each with a different connection ID. A member of the presence set is therefore unique by the combination of the client ID and connection ID strings.

Step 3a – Updating your presence data

In the previous step, we set a payload for our entry in the presence set: the string ‘hello’, which other clients will receive with the notification that we’ve entered. We can update that whenever we want, and other clients will receive the update:

channel.presence.update('howdy!', function(err) {
  if(err) { return console.error("Error updating presence data"); }
  console.log('We have successfully updated our data');
})
  channel.presence.update(data: 'hello') do
    puts "We have successfully updated our data"
  end
end

Step 4 – Get present members

The next thing to do is to find out who else is present. (Spoiler: it’s currently just you).

channel.presence.get(function(err, members) {
  if(err) { return console.error("Error fetching presence data"); }
  console.log('There are ' + members.length + ' clients present on this channel');
  var first = members[0];
  console.log('The first member is ' + first.clientId);
  console.log('and their data is ' + first.data);
});
channel.presence.get do |members|
  puts "There are #{members.length} clients present on this channel"
  first = members[0]
  puts "The first member is #{first.clientId} and their data is #{first.data}"
end

See this step in Github

As soon as you are attached to the channel, the presence set starts to sync with Ably. When you make this call to get the presence set, it will (by default) wait until it has finished syncing before completing. For small presence sets this will take only a few milliseconds; for larger ones (with hundreds of members) the full sync can take a little longer.

Step 5 – Subscribe to presence changes

Getting a list of who’s present when your app loads is all well and good, but you probably also want to know when that changes: when new members enter, or existing ones update their data or leave. You can do this by subscribing to presence messages. Presence messages will include the client ID of the member, and an action that tells you what happened to that member: either enter, update, or leave. In this simple example, every time there’s a change, we just call presence.get again to get the new state of the presence set.

channel.presence.subscribe(function(presenceMsg) {
  console.log('Received a ' + presenceMsg.action + ' from ' + presenceMsg.clientId);
  channel.presence.get(function(err, members) {
    console.log('There are now ' + members.length + ' clients present on this channel');
  });
});
channel.presence.subscribe do |presence_msg|
  puts "Received a #{presence_msg.action} from #{presence_msg.client_id}"
  channel.presence.get do |members|
    puts "There are now #{members.length} clients present on this channel"
  end
end

See this step in Github

And that’s it. To see this in action, try out the live demo below.

Live demo

Enter your name and connect to Ably. (Your name will become the client ID of the Ably connection). Once connected, choose an avatar, then click ‘Enter’ to enter the presence set, and ‘Leave’ to leave it again. Open this demo in other browser windows and enter presence in them as well, and see how every window shows an up-to-date presence set.

Once you’re entered, try tapping a different avatar to change it, and seeing it change in all the other windows in real time.

Name:

Download tutorial source code

The complete source code for each step of this tutorial is available on Github.

We recommend that you clone the repo locally:

git clone https://github.com/ably/tutorials.git

Checkout the tutorial branch:

git checkout presence-javascript

And then run the demo locally by adding your Ably API key to example.html and opening the page in your browser.

The complete source code for each step of this tutorial is available on Github.

We recommend that you clone the repo locally:

git clone https://github.com/ably/tutorials.git

Checkout the tutorial branch:

git checkout presence-nodejs

And then run the demo locally by adding your Ably API key to example.js and running the demo node example.js

The complete source code for each step of this tutorial is available on Github

We recommend that you clone the repo locally:

git clone https://github.com/ably/tutorials.git

Checkout the tutorial branch:

git checkout presence-ruby

And then run the demo locally by adding your Ably API key to example.rb and running the demo bundle exec ruby example.rb

Next steps

1. If you would like to find out more about how channels, publishing and subscribing works, see the Realtime channels & messages documentation
1. If you would like to find out more about how presence works, see the Realtime presence documentation
2. Learn more about Ably features by stepping through our other Ably tutorials
3. Gain a good technical overview of how the Ably realtime platform works
4. Get in touch if you need help


Get started now with our free plan

It includes 3m messages per month, 100 peak connections, 100 peak channels, and loads of features.

Create your free account