A JavaScript client library for Ably Realtime, a realtime data delivery platform.
This library currently targets the Ably client library features spec Version 1.2. You can jump to the 'Known Limitations' section to see the features this client library does not yet support or view our client library SDKs feature support matrix to see the list of all the available features.
Supported platforms
This SDK supports the following platforms:
Browsers: All major desktop and mobile browsers, including (but not limited to) Chrome, Firefox, IE (only version 8 or newer), Safari on iOS and macOS, Opera, and Android browsers. We also support running ably-js
inside a Web Worker context.
Webpack: see using Webpack in browsers, or our guide for serverside Webpack
Node.js: version 5.10 or newer. (1.1.x versions work on Node.js 4.5 or newer).
React Native: see ably-js-react-native
NativeScript: see ably-js-nativescript
TypeScript: see below
We regression-test the library against a selection of those (which will change over time, but usually consists of the versions that are supported upstream, plus old versions of IE).
However, we aim to be compatible with a much wider set of platforms and browsers than we can possibly test on. That means we'll happily support (and investigate reported problems with) any reasonably-widely-used browser. So if you find any compatibility issues, please do raise an issue in this repository or contact Ably customer support for advice.
Ably-js has fallback mechanisms in order to be able to support older browsers; specifically it supports comet-based connections for browsers that do not support websockets, and this includes JSONP for browsers that do not support cross-origin XHR. Each of these fallback transport mechanisms is supported and tested on all the browsers we test against, even when those browsers do not themselves require those fallbacks. These mean that the library should be compatible with nearly any browser on most platforms.
Known browser incompatibilities will be documented as an issue in this repository using the "compatibility" label.
Version: 1.2.4
The latest stable version of the Ably JavaScript client library is version: 1.2.4 .
For complete API documentation, see the Ably documentation.
Installation
Node.js
npm install ably --save
and require as:
var Ably = require('ably');
For the version of the library where async methods return promises, use var Ably = require('ably/promises');
instead. For the explicitly-callback-based variant use require('ably/callbacks')
– see Async API style.
For usage, jump to Using the Realtime API or Using the REST API.
Serverside usage with webpack
Add 'ably' to externals
in your webpack config to exclude it from webpack processing, and require and use it in as a external module using require('ably') as above.
For browsers
Include the Ably library in your HTML:
<script src="https://cdn.ably.io/lib/ably.min-1.js"></script>
The Ably client library follows Semantic Versioning. To lock into a major or minor version of the client library, you can specify a specific version number such as https://cdn.ably.io/lib/ably.min-1.js for all v1._ versions, or https://cdn.ably.io/lib/ably.min-1.0.js for all v1.0._ versions, or you can lock into a single release with https://cdn.ably.io/lib/ably.min-1.0.9.js. Note you can load the non-minified version by omitting min-
from the URL such as https://cdn.ably.io/lib/ably-1.0.js. See https://github.com/ably/ably-js/tags for a list of tagged releases.
For usage, jump to Using the Realtime API or Using the REST API.
Using WebPack
(This applies to using webpack to compile for a browser; for Node.js, see Serverside usage with webpack)
WebPack will search your node_modules
folder by default, so if you include ably
in your package.json
file, when running Webpack the following will allow you to require('ably')
(or if using typescript or ES6 modules, import * as Ably from 'ably';
). If your webpack target is set to 'browser', this will automatically use the browser commonjs distribution.
If that doesn't work for some reason (e.g. you are using a custom webpack target), you can reference the ably-commonjs.js
static file directly: require('ably/browser/static/ably-commonjs.js');
(or import * as Ably from 'ably/browser/static/ably-commonjs.js'
for typescript / ES6 modules).
TypeScript
The TypeScript typings are included in the package and so all you have to do is:
import * as Ably from 'ably';
let options: Ably.Types.ClientOptions = { key: 'foo' };
let client = new Ably.Realtime(options);
let channel = client.channels.get('feed');
For the version of the library where async methods return promises, use import * as Ably from 'ably/promises';
instead. For the explicitly-callback-based variant use import * as Ably from 'ably/callbacks'
– see Async API style.
Intellisense in IDEs with TypeScript support is supported:
If you need to explicitly import the type definitions, see ably.d.ts (or promises.d.ts
if you're requiring the library as ably/promises
).
Async API style
This library exposes two API variants. Firstly, the original (and presently the default) callback-based API, which follows the usual Node.js error-first callback style. Second, a promises-based API. With the promises variant, you can still pass a callback to methods and the callback will work as expected, but if you do not pass a callback, the method will return a promise. The API in use can be selected explicitly by requiring that specific variant when requiring/importing the library (or in the case of the browser version, when instantiating it). The usage instructions below make reference to both variants.
For this library version, and for all future 1.x versions, the callback-based API will be the default. This means that the promises-based variant will need to be explicitly selected, to avoid breaking backwards compatibility. A move to the promises-based variant as the default is likely at the next major release (i.e. 2.x onwards).
For usage, jump to Using the async API style.
React Native
See the ably-js-react-native repo for React Native usage details.
NativeScript
See the ably-js-nativescript repo for NativeScript usage details.
Delta Plugin
From version 1.2 this client library supports subscription to a stream of Vcdiff formatted delta messages from the Ably service. For certain applications this can bring significant data efficiency savings.
This is an optional feature so our
Vcdiff Decoder plugin
must be supplied to the library in client options to enable this functionality.
var vcdiffDecoder = require('@ably/vcdiff-decoder');
var clientOptions = {
plugins: {
vcdiff: vcdiffDecoder,
},
};
var client = new Ably.Realtime(clientOptions);
See also
Subscribing to a channel with deltas,
which describes how to enable delta compression when getting a channel.
Using the Realtime API
This readme gives some basic examples; for our full API documentation, please go to https://www.ably.io/documentation .
Introduction
All examples assume a client has been created as follows:
var client = new Ably.Realtime(key: string);
var client = new Ably.Realtime(options: ClientOptions);
var client = new Ably.Realtime.Promise(options: string | ClientOptions);
var client = new Ably.Rest.Callbacks(options: string | ClientOptions);
Connection
Successful connection:
client.connection.on('connected', function() {
# successful connection
});
Failed connection:
client.connection.on('failed', function() {
# failed connection
});
Subscribing to a channel
Given:
var channel = client.channels.get('test');
Subscribe to all events:
channel.subscribe(function (message) {
message.name;
message.data;
});
Only certain events:
channel.subscribe('myEvent', function (message) {
message.name;
message.data;
});
Subscribing to a channel with deltas
Subscribing to a channel in delta mode enables delta compression. This is a way for a client to subscribe to a channel so that message payloads sent contain only the difference (ie the delta) between the present message and the previous message on the channel.
Provide the library with Vcdiff decoding capability - see
Delta Plugin.
Request a Vcdiff formatted delta stream using channel options when you get the channel:
var channelOptions = {
params: {
delta: 'vcdiff',
},
};
var channel = client.channels.get('test', channelOptions);
Beyond specifying channel options, the rest is transparent and requires no further changes to your application. The message.data
instances that are delivered to your listening function continue to contain the values that were originally published.
If you would like to inspect the Message
instances in order to identify whether the data
they present was rendered from a delta message from Ably then you can see if extras.delta.format
equals 'vcdiff'
.
Publishing to a channel
channel.publish('greeting', 'Hello World!');
channel.publish('greeting', 'Hello World!', function(err) {
if(err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
})
channel.publish([{name: 'greeting', data: 'Hello World!'}, ...], callback);
Querying the History
channel.history(function(err, messagesPage) {
messagesPage
messagesPage.items
messagesPage.items[0].data
messagesPage.items.length
messagesPage.hasNext()
messagesPage.isLast()
messagesPage.next(function(nextPage) { ... });
});
channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
Presence on a channel
Getting presence:
channel.presence.get(function (err, presenceSet) {
presenceSet;
});
Note that presence#get on a realtime channel does not return a
PaginatedResult, as the library maintains a local copy of the presence set.
Entering (and leaving) the presence set:
channel.presence.enter('my status', function (err) {
});
channel.presence.update('new status', function (err) {
});
channel.presence.leave(function (err) {
});
If you are using a client which is allowed to use any clientId --
that is, if you didn't specify a clientId when initializing the
client, and are using basic auth or a token witha wildcard clientId (see
https://www.ably.io/documentation/general/authentication for more information), you
can use
channel.presence.enterClient('myClientId', 'status', function(err) { ... });
Querying the Presence History
channel.presence.history(function(err, messagesPage) {
messagesPage.items
messagesPage.items[0].data
messagesPage.items.length
messagesPage.hasNext()
messagesPage.isLast()
messagesPage.next(function(nextPage) { ... });
});
channel.presence.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
Symmetrical end-to-end encrypted payloads on a channel
When a 128 bit or 256 bit key is provided to the library, the data
attributes of all messages are encrypted and decrypted automatically using that key. The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption
Ably.Realtime.Crypto.generateRandomKey(function (err, key) {
var channel = client.channels.get('channelName', { cipher: { key: key } });
channel.subscribe(function (message) {
message.name;
message.data;
});
channel.publish('name is not encrypted', 'sensitive data is encrypted');
});
You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
channel.setOptions({cipher: {key: <key>}}, function() {
})
Using the REST API
This readme gives some basic examples. For our full API documentation, please go to https://www.ably.io/documentation .
Introduction
All examples assume a client and/or channel has been created as follows:
var client = new Ably.Rest(key: string);
var client = new Ably.Rest(options: ClientOptions);
var client = new Ably.Rest.Promise(options: string | ClientOptions);
var client = new Ably.Rest.Callbacks(options: string | ClientOptions);
Given:
var channel = client.channels.get('test');
Publishing to a channel
channel.publish('greeting', 'Hello World!');
channel.publish('greeting', 'Hello World!', function(err) {
if(err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
})
channel.publish([{name: 'greeting', data: 'Hello World!'}, ...], callback);
Querying the History
channel.history(function(err, messagesPage) {
messagesPage
messagesPage.items
messagesPage.items[0].data
messagesPage.items.length
messagesPage.hasNext()
messagesPage.isLast()
messagesPage.next(function(nextPage) { ... });
});
channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
Presence on a channel
channel.presence.get(function(err, presencePage) {
presencePage.items
presencePage.items[0].data
presencePage.items.length
presencePage.hasNext()
presencePage.isLast()
presencePage.next(function(nextPage) { ... });
});
Querying the Presence History
channel.presence.history(function(err, messagesPage) {
messagesPage.items
messagesPage.items[0].data
messagesPage.items.length
messagesPage.hasNext()
messagesPage.isLast()
messagesPage.next(function(nextPage) { ... });
});
channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
Generate Token and Token Request
See https://www.ably.io/documentation/general/authentication for an
explanation of Ably's authentication mechanism.
Requesting a token:
client.auth.requestToken(function(err, tokenDetails) {
var clientUsingToken = new Ably.Realtime(tokenDetails.token);
});
client.auth.requestToken(tokenParams, authOptions, function(err, tokenDetails) { ... });
Creating a token request (for example, on a server in response to a
request by a client using the authCallback
or authUrl
mechanisms):
client.auth.createTokenRequest(function(err, tokenRequest) {
});
client.auth.createTokenRequest(tokenParams, authOptions, function(err, tokenRequest) { ... });
Fetching your application's stats
client.stats(function(err, statsPage) {
statsPage.items
statsPage.items[0].inbound.rest.messages.count;
statsPage.items.length;
statsPage.hasNext()
statsPage.isLast()
statsPage.next(function(nextPage) { ... });
});
Fetching the Ably service time
client.time(function(err, time) { ... });
Using the async API style
Realtime Example
import * as Ably from 'ably/promises';
const client = new Ably.Realtime.Promise(options);
const ablyRealtimePromiseExample = async () => {
const channel = client.channels.get('myChannel');
await channel.attach();
const presenceMessage = await channel.presence.get();
console.log(presenceMessage);
await channel.presence.enter();
await channel.presence.update('new status');
await channel.presence.leave();
await channel.publish('greeting', 'Hello, World!');
const history = await channel.history({ limit: 25 });
console.log(history);
client.close();
};
ablyRealtimePromiseExample();
REST Example
import * as Ably from 'ably/promises';
const client = new Ably.Rest.Promise(options);
const ablyRestPromiseExample = async () => {
const channel = client.channels.get('myChannel');
await channel.publish('greeting', 'Hello, World!');
const presenceMessage = await channel.presence.get();
console.log(presenceMessage);
const history = await channel.history({ limit: 25 });
console.log(await history.current());
const token = await client.auth.requestToken(tokenParams);
const tokenRequest = await client.auth.createTokenRequest();
const stats = await client.stats();
console.log(stats);
const time = await client.time();
console.log(`Ably service time: ${time}`);
client.close();
};
ablyRestPromiseExample();
Support, feedback and troubleshooting
Please visit http://support.ably.io/ for access to our knowledgebase and to ask for any assistance.
You can also view the community reported Github issues.
To see what has changed in recent versions, see the CHANGELOG.
Known Limitations
This library currently does not support being the target of a push notification (i.e. web push).
Browser-specific issues
Contributing
For guidance on how to contribute to this project, see the CONTRIBUTING.md.
Credits
Automated browser testing supported by