Subscribing to Channel Lifecycle Events

Ably’s global platform organizes all of the message traffic within its applications into named channels. Channels are the “unit” of message distribution; clients attach to any number of channels to publish or subscribe to messages. Every message published to a channel is broadcasted to all subscribers.

Many times, developers find it helpful to be aware of specific metadata related to their channels. This metadata can be accessed using our Channel Metadata API. This API allows you to do things such as subscribe to the channel lifecycle events and channel occupancy events. In this tutorial, we’ll see how to subscribe to the channel lifecycle events.

Step 1 – Create your Ably app and API key

To follow this tutorial, you will need an Ably account. Sign up for a free account if you don’t already have one.

Access to the Ably global messaging platform requires an API key for authentication. API keys exist within the context of an Ably application and each application can have multiple API keys so that you can assign different capabilities and manage access to channels and queues.

You can either create a new application for this tutorial, or use an existing one.

To create a new application and generate an API key:

  1. Log in to your Ably account dashboard
  2. Click the “Create New App” button
  3. Give it a name and click “Create app”
  4. Copy your private API key and store it somewhere. You will need it for this tutorial.

To use an existing application and API key:

  1. Select an application from “Your apps” in the dashboard
  2. In the API keys tab, choose an API key to use for this tutorial. The default “Root” API key has full access to capabilities and channels.
  3. Copy the Root API key and store it somewhere. You will need it for this tutorial.

    Copy API Key screenshot

Step 2 – Setting the right permissions on your API key

In order to be able to receive the channel lifecycle events that are offered as part of the Channel Lifecycle API, you’ll need to attach to a special channel called ‘[meta]channel.lifecycle’. This channel, in essence, is similar to any other channel that you would use to share data within Ably’s global platform; however, it’s kept on a different namespace to easily separate concerns. All of the metadata, including channel lifecycle events and occupancy events, will be sent on this channel.

You’ll need to ensure that the Channel Metadata permission is enabled on your API key. Permissions (or privileges or capabilities, used interchangeably) restrict your API key from being used to performing specific actions only, such as publish-and-subscribe or publish-only, etc. These privileges can be set on your API key via your account dashboard. Navigate to the ‘API Keys’ tab of your dashboard as shown in the image below and click on the ‘settings’ button against an existing API key that you’d like to use or create a new one.

A regular Ably API key has a capability which lists resources (glob expressions that match channel names) and, for any given resource, a set of permitted operations. The wildcard resource '*' will match any regular channel name.

In order to grant permission in a key to a channel, however, the resource name(s) in the capability must include the [meta] qualifier explicitly; so the following are examples of capabilities that will validly permit access to a metachannel:

{"[meta]*":["subscribe"]}
{"[meta]*":["*"], "*":["*"]}


Channel metadata permissions

Under normal circumstances you won’t be granted permission to publish to, or be present in metachannels.

Step 3 – Subscribing to the channel lifecycle events using Ably’s Realtime Library

Ably’s realtime library allows you to subscribe to various channels. This means that whenever some new data is published onto the channel you are subscribed, you’ll automatically receive that data, without needing to generate additional requests. You can learn more about the realtime library from our documentation.

In this section, we’ll subscribe to the lifecycle events that will be published on the meta-channel using the realtime library.

Creating a basic HTML page to display results

Since we’ll be using JavaScript in this tutorial, the best way to display results is in a browser. So, go ahead and paste the following simple HTML in a file and name it index.html

<html>

<head>
    <title>Channel Lifecycle Events</title>
    <script src="https://cdn.ably.com/lib/ably.min-1.js" crossorigin="anonymous"></script>
</head>

<body style="padding: 60px; font-family:Arial, Helvetica, sans-serif">
    Ably Channel Lifecycle API - Lifecycle Events Demo
    <br/>
    <br/>
    <div>
        Ably console:
        <br>
        <textarea id="result" rows="30" style="width: 30%; margin-top: 10px; font-family: courier, courier new; background-color: #333; color: orange;  overflow-y: scroll;"
            disabled>
        </textarea>
    </div>
    <script src="main.js"></script>
</body>

</html>

The key thing to note in the HTML above, is the inclusion of two JS files, ones is the Ably Library, referenced via the CDN, while the other is the main.js file which will include our logic. We’ll work on this next. We have also added a text area to display our results in.

See this step in Github

Step 4 – Adding subscribers for the lifecycle events

For the simplicity of this tutorial, we’ll use Basic authentication in our realtime client. However, it is highly recommended to use Token auth on client-side applications for better security and protection of your API key.

Let’s begin with instantiating the Ably Realtime library using the API key. Create a new file called main.js and add the following to it.

var apiKey = '<YOUR-API-KEY>';
var ably = new Ably.Realtime({
    key: apiKey
});

Next, let’s instantiate the meta-channel using the realtime client that we instantiated above and also reference the text area we added in the HTML, to display results in.

var metaChannel = ably.channels.get("[meta]channel.lifecycle");
var resultArea = document.getElementById("result");
resultArea.scrollTop = resultArea.scrollHeight;

The next step would be to subscribe to the channel lifecycle events. These events are triggered on the [meta]channel.lifecycle that we instantiated above and could be one of these: ‘channel.opened’, ‘channel.closed’, ‘channel.region.active’ and ‘channel.region.inactive’. We can display the results returned in the callback in the text area in our HTML.

metaChannel.subscribe('channel.opened', (msg) => {
    var msgJSONobj = JSON.parse(JSON.stringify(msg.data));
    resultArea.value += ('[METADATA - ' + (new Date().toLocaleTimeString()) + ' ]: Channel "' + msgJSONobj.name + '" has been activated globally\n');
    resultArea.scrollTop = resultArea.scrollHeight;
})

metaChannel.subscribe('channel.closed', (msg) => {
    var msgJSONobj = JSON.parse(JSON.stringify(msg.data));
    resultArea.value += ('[METADATA - ' + (new Date().toLocaleTimeString()) + ' ]: Channel "' + msgJSONobj.name + '" has been deactivated globally\n');
    resultArea.scrollTop = resultArea.scrollHeight;
})

metaChannel.subscribe('channel.region.active', (msg) => {
    var msgJSONobj = JSON.parse(JSON.stringify(msg.data));
    resultArea.value += ('[METADATA - ' + (new Date().toLocaleTimeString()) + ' ]: Channel "' + msgJSONobj.name + '" has been activated in ' + msgJSONobj.region + ' region\n');
    resultArea.scrollTop = resultArea.scrollHeight;
})

metaChannel.subscribe('channel.region.inactive', (msg) => {
    var msgJSONobj = JSON.parse(JSON.stringify(msg.data));
    resultArea.value += ('[METADATA - ' + (new Date().toLocaleTimeString()) + ' ]: Channel "' + msgJSONobj.name + '" has been deactivated in ' + msgJSONobj.region + ' region\n');
    resultArea.scrollTop = resultArea.scrollHeight;
})

In the above code, we have subscribed to the various channel lifecycle events on the meta-channel and then we display the data returned in the text area. Simple as that!

See this step in Github

Step – 5 Live Demo



For the live demo, we’ll manually attach and detach from channels, through button clicks, so we can see the channel lifecycle events live in action.

Whilst it is not recommended to use Basic auth on the client-side, we will be using it for the simplicity of this tutorial. So, feel free to create a dummy app and use it’s API key here

Ably console:

See the full code in GitHub

Next Steps

1. If you would like to find out more about how channels and publishing or subscribing to messages work, see the realtime channels & messages documentation.
2. If you would like to check out the other related tutorials to work with channel metadata, see the Channel Occupancy Events and Channel Enumeration tutorials .
3. Learn more about Ably features by stepping through our other Ably tutorials
4. Gain a good technical overview of how the Ably realtime platform works
5. Get in touch if you need help