Ably Integration in JavaScript
Easy steps to empower your JavaScript application with Ably.
Ably is an innovative platform that empowers seamless, real-time digital experiences across a multitude of connected devices.
Serving as a messaging platform, Ably simplifies the creation of immersive, interactive events such as virtual live gatherings and ensures real-time updates for dynamic user experience. It also provides simple APIs and SDKs that handle the intricacies of real-time communication and let you focus on your code.
Ably Features and Capabilities
- A globally distributed network of data centers
- Real-time message delivery
- Global fault tolerance
Prerequisites
To include Ably in your project, you have two options: using the CDN or installing it via NPM.
Add the following script tag to your HTML file to include Ably via the CDN:
<script src="https://cdn.ably.com/lib/ably.min-1.js"></script>
Alternatively, install the Ably SDK as an NPM module using the following command:
npm install ably
Pub/Sub
The Ably platform supports both pub/sub and message queue patterns. It provides robust cloud-based pub/sub services, ensuring real-time message delivery to any number of subscribed devices. With Ably, you benefit from scalability, low latency, seamless connections, network outage resilience, enhanced security, and authentication capabilities.
Channels
Ably allows users to subscribe to specific channels to access real-time data. Messages are published by Ably and delivered exclusively to subscribed channels, ensuring efficient traffic distribution. By subscribing to relevant channels, users receive real-time updates from Ably.
Channel Namespaces
For example, you can use the namespace public:news:americas
to access specific channels related to news in America.
Initializing Ably
To establish a connection with Ably and receive real-time updates, you need to generate a token-based authentication mechanism. This token will authenticate your connection with Ably. You can find additional details about authentication in the Ably documentation.
Here’s an example of how to initialize Ably:
const ably = new Ably.Realtime({ authUrl: url, closeOnUnload: true });
In the authUrl parameter, you can specify the URL on your server that will provide the token for authentication. This allows you to automatically connect to Ably using an updated token if the current token has expired. The closeOnUnload option ensures that you disconnect from Ably when the page reloads, improving the reliability of your application.
Subscribe to Ably Channels
The Ably platform enables the delivery of real-time messages to subscribed channels on the client side. Each channel is unique, and Ably broadcasts messages to all connected subscribers.
const realtime = = new Ably.Realtime({ authUrl: url, closeOnUnload: true });
const channelOptions = {
params: {
rewind: '1'
}
};
const channel = realtime.channels.get('channelname');
channel.setOptions(channelOptions);
channel.subscribe((message) => { alert('Received: ' + message.data); });
When you subscribe to an Ably channel, you become a listener for events on that channel. As events are published, you receive real-time messages from Ably for that specific channel.
Ably Rewind
The rewind feature allows you to retrieve the last message from a channel in case of connection loss. To preserve data integrity, you can set the rewind option on Ably.
const channelOptions = { params: { rewind: '1' }
Publishing on a Channel
To publish a message on a channel, you can use the publish method
const realtime = new Ably.Realtime({ authUrl: url, closeOnUnload: true });
const channel = realtime.channels.get('channelname');
channel.publish('example', 'message data');
Ably Channel States
A channel can be in one of the following states: Initialized, Attached, Detached, Suspended, or Failed.
- Initialized: The channel has been initialized but is not attached.
- Attached: The channel is attached to the Ably service, and it subscribes to messages with listeners added.
- Detached: The channel has been detached from the Ably service.
- Suspended: The client is disconnected due to an internet issue or other reasons. Ably will attempt to reattach when the connection is restored.
- Failed: If the connection is not restored after suspension, the channel enters the failed state due to an error from the Ably service.
You can check and handle the channel state, as shown in the example below for the failed state:
channel.connection.on('failed', function() { console.log('✗ Connection failed from Ably.'); }
channel.on('attached', (stateChange) => {
console.log('channel ' + channel.name + ' is now attached');
console.log('Message continuity on this channel ' + \
(stateChange.resumed ? 'was' : 'was not') + ' preserved');
});
Unsubscribe from an Ably Channel
To unsubscribe from a channel, we use the unsubscribe method that exists on channels for Ably. The code below demonstrates how to unsubscribe from channels:
ably.channels.get(channelname).unsubscribe(ablyChannelListener)
/* remove the listener registered for all events */
channel.off(ablyChannelListener);
Handling Channel Failures
Ably’s client library automatically recovers from non-fatal error conditions. You can handle channel attachment failures as shown in the example below:
realtime.channels.get('channelname').attach(function(err) {
if (err) {
console.error('Attach failed: ' + err);
}
});
Ably Health Check
You can check Ably's health status by using this link.
Ably Connection Limits
For detailed information on Ably’s connection limits, you can refer to the documentation here: Ably Limits
Key Takeaways
Integrating Ably into your JavaScript applications offers seamless real-time experiences. By incorporating Ably into your projects, you can deliver dynamic and engaging experiences to your users, focusing on innovation while Ably takes care of the real-time complexities.
If you want to learn more about Ably, read the docs here.
To stay up-to-date with the latest trends in the development ecosystem, follow Simform Engineering.