Realtime client
The device package uses a realtime client to establish a persistent connection with Ably. The createClient function is the entry point for using the Ably Pub/Sub JavaScript SDK in code that runs on an end user's device, such as a browser, or a React Native, Electron, mobile or desktop app.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { createClient } from '@ably/pubsub-device';
const pubsubDeviceClient = createClient({
authCallback: async (tokenParams, callback) => {
try {
// Request an Ably-compatible JWT from your own server
const response = await fetch('https://your-server.example.com/ably-jwt');
const jwt = await response.text();
callback(null, jwt);
} catch (error) {
callback(error, null);
}
},
});This example uses token authentication: the authCallback requests an Ably-compatible JWT from your server whenever a token is needed, which keeps your API key off the device. A backend service that needs a persistent connection to Ably can create a realtime client on a server instead.
Properties
The realtime client has the following properties, whether it was created on a device or on a server:
connectionConnectionConnection object for this client. Use this to inspect or subscribe to the connection state.clientIdString or Nullnull if anonymous.The Crypto, Message, PresenceMessage and Annotation helpers are not properties of the client. Import them by name from the package that created the client.
Create a device client
Use createClient() from the @ably/pubsub-device package to create a client that runs on an end user's device.
On an account billed by monthly active users, a device connection must carry a client ID, either set in clientId or carried by the token it authenticates with. Ably rejects a device connection without one at connect.
createClient(options: ClientOptions): PubSubClientCreate a client with a ClientOptions object. This is the most common form, allowing all available client options to be configured.
createClient(keyOrToken: string): PubSubClientA convenience form that takes a single API key or token string. Equivalent to passing { key: '<key>' } or { token: '<token>' } as ClientOptions. Useful for test setups.
The following example creates a device client:
1
2
3
4
5
6
7
import { createClient } from '@ably/pubsub-device';
const pubsubDeviceClient = createClient({
authUrl: '/auth',
clientId: 'user-123',
logLevel: 3
});Parameters
createClient() takes the following parameters:
optionsrequiredClientOptionskeyOrTokenrequiredStringCreate a realtime client on a server
If your server requires a persistent connection to Ably, for example to subscribe to channels or enter presence, then you can create a realtime client using createRealtimeClient().
Use createRealtimeClient() from the @ably/pubsub-server package to create the realtime client in a backend service that you operate. It returns a PubSubRealtimeClient, the same client that createClient() from the device package returns under its PubSubClient alias, so every property and method in this section applies to it. Never use the @ably/pubsub-server package in code that runs on an end user's device.
createRealtimeClient(options: ClientOptions): PubSubRealtimeClientcreateRealtimeClient(keyOrToken: string): PubSubRealtimeClientThe following example creates a realtime client in a backend service:
1
2
3
import { createRealtimeClient } from '@ably/pubsub-server';
const pubsubRealtimeClient = createRealtimeClient({ key: process.env.ABLY_API_KEY });Parameters
createRealtimeClient() takes the following parameters:
optionsrequiredClientOptionscreateClient().keyOrTokenrequiredStringOpen the connection
pubsubDeviceClient.connect(): voidCalls connection.connect(), explicitly initiating the connection if clientOptions.autoConnect was set to false.
1
pubsubDeviceClient.connect();Close the connection
pubsubDeviceClient.close(): voidCalls connection.close(), causing the connection to close and entering the closing state. Once closed, the SDK will not attempt to reconnect.
1
pubsubDeviceClient.close();Get server time
pubsubDeviceClient.time(): Promise<number>Returns the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well-maintained time source and wish to issue Ably TokenRequests with a more accurate timestamp should use the clientOptions.queryTime client option instead of this method.
1
const now = await pubsubDeviceClient.time();Returns
Promise<number>
Returns a promise. The promise is fulfilled with the server time as milliseconds since the Unix epoch, or rejected with an ErrorInfo object.
Get account stats
pubsubDeviceClient.stats(params?: StatsParams): Promise<PaginatedResult<Stats>>Retrieves usage statistics for the account, filtered by the supplied query parameters. Returns a paginated set of Stats objects, each containing usage metrics.
1
const page = await pubsubDeviceClient.stats({ unit: 'hour', limit: 24 });Parameters
The stats() method takes the following parameters:
paramsoptionalStatsParamsReturns
Promise<PaginatedResult<Stats>>
Returns a promise. The promise is fulfilled with a PaginatedResult of Stats objects, or rejected with an ErrorInfo object.
Stats
Each Stats entry contains the following properties:
appIdStringintervalIdStringunit was requested as minute this is in the format YYYY-mm-dd:HH:MM, if hour it is YYYY-mm-dd:HH, if day it is YYYY-mm-dd:00, and if month it is YYYY-mm-01:00.inProgressStringyyyy-mm-dd:hh:mm:ss.entriesRecord<String, Number>messages.all.count, messages.inbound.realtime.count) to their values. The schema property provides further information.schemaStringMake a REST request
pubsubDeviceClient.request(method: string, path: string, version: number, params?: any, body?: any, headers?: any): Promise<HttpPaginatedResponse>Makes a REST request to a provided path. Useful for accessing Ably APIs that do not have a dedicated method in the SDK, without having to handle authentication, paging, fallback hosts, and MsgPack or JSON support yourself.
1
2
3
4
5
6
const response = await pubsubDeviceClient.request(
'GET',
'/channels/arc-one-ego/messages',
3,
{ limit: 10 }
);Parameters
The request() method takes the following parameters:
methodrequiredStringGET, POST, PUT, PATCH, DELETE).pathrequiredStringversionrequiredNumber3).paramsoptionalObjectbodyoptionalAnyPOST, PUT, and PATCH methods only. Must be anything that can be serialized into JSON, such as an object or array.headersoptionalObjectReturns
Promise<HttpPaginatedResponse>
Returns a promise. The promise is fulfilled with an HttpPaginatedResponse, or rejected with an ErrorInfo object. Note that if a response is obtained, any response, even one with a non-2xx status code, resolves as an HttpPaginatedResponse rather than rejecting.
HttpPaginatedResponse
HttpPaginatedResponse contains the following properties:
statusCodeNumbersuccessBooleantrue if the status code is in the 200-299 range.errorCodeNumberX-Ably-Errorcode HTTP header, if sent in the response.errorMessageStringX-Ably-Errormessage HTTP header, if sent in the response.errorDetailObject or UndefinedheadersObjectitemsArrayHttpPaginatedResponse also contains the following methods to handle pagination:
Check for more pages
hasNext(): booleanReturns true if there are more pages available by calling next().
Check if last page
isLast(): booleanReturns true if this is the last page of results.
Get next page
next(): Promise<PaginatedResult | null>Returns a promise. The promise is fulfilled with the next page of results as a PaginatedResult, or null if there are no more pages. Rejected with an ErrorInfo object on failure.
Get first page
first(): Promise<PaginatedResult>Returns a promise. The promise is fulfilled with the first page of results as a PaginatedResult, or rejected with an ErrorInfo object.
Get current page
current(): Promise<PaginatedResult>Returns a promise. The promise is fulfilled with the current page of results as a PaginatedResult, or rejected with an ErrorInfo object.
Batch publish to multiple channels
pubsubDeviceClient.batchPublish(spec: BatchPublishSpec): Promise<BatchResult>Publish using a single BatchPublishSpec, fulfilled with a single BatchResult.
pubsubDeviceClient.batchPublish(specs: BatchPublishSpec[]): Promise<BatchResult[]>Publish using an array of BatchPublishSpec objects, fulfilled with one BatchResult per spec.
Each spec publishes one or more messages to up to 100 channels in a single batch publish request.
1
2
3
4
const result = await pubsubDeviceClient.batchPublish({
channels: ['channel1', 'channel2'],
messages: [{ name: 'event', data: 'hello' }]
});Parameters
The batchPublish() method takes the following parameters:
specrequiredBatchPublishSpecspecsrequiredBatchPublishSpec[]Returns
Promise<BatchResult | BatchResult[]>
Returns a promise. For a single spec, the promise is fulfilled with a BatchResult. For an array of specs, the promise is fulfilled with an array of BatchResults. Rejected with an ErrorInfo object on failure.
successCountNumberfailureCountNumberresultsArray of BatchPublishSuccessResult or BatchPublishFailureResultBatch presence query
pubsubDeviceClient.batchPresence(channels: string[]): Promise<BatchResult[]>Retrieves the presence set for up to 100 channels in a single REST request. The presence state includes the clientId of members and their current PresenceAction.
Parameters
The batchPresence() method takes the following parameters:
channelsrequiredString[]Returns
Promise<BatchResult[]>
Returns a promise. The promise is fulfilled with an array of BatchResult objects, one per channel, where each results entry is a BatchPresenceSuccessResult or a BatchPresenceFailureResult. Rejected with an ErrorInfo object on failure.
successCountNumberfailureCountNumberresultsArray of BatchPresenceSuccessResult or BatchPresenceFailureResultGet the local device
pubsubDeviceClient.getDevice(): Promise<LocalDevice>Retrieves a LocalDevice object representing the current device as a push notification target, loading its state from persistent storage if necessary.
Returns
Promise<LocalDevice>
Returns a promise. The promise is fulfilled with the LocalDevice, or rejected with an ErrorInfo object.
PaginatedResult
A PaginatedResult represents a page of results from a paginated query such as stats(), channel.history(), presence.history(), or channel.getMessageVersions().
Properties
PaginatedResult contains the following properties:
itemsArrayPaginatedResult also contains the following methods to handle pagination:
Check for more pages
hasNext(): booleanReturns true if there are more pages available.
Check if last page
isLast(): booleanReturns true if this is the last page of results.
Get next page
next(): Promise<PaginatedResult | null>Returns a promise fulfilled with the next page of results, or null if there are no more pages. Rejected with an ErrorInfo object on failure.
Get first page
first(): Promise<PaginatedResult>Returns a promise fulfilled with the first page of results, or rejected with an ErrorInfo object.
Get current page
current(): Promise<PaginatedResult>Returns a promise fulfilled with the current page of results, or rejected with an ErrorInfo object.
ErrorInfo
A standardized, generic Ably error object that contains an Ably-specific error code, a generic HTTP status code, and a human-readable message. All errors emitted by Ably are ErrorInfo instances.
codeNumberstatusCodeNumbermessageStringcauseErrorInfo or UndefineddetailObject or UndefinedremediationString or Undefinedmessage, which describes what went wrong. Present only on SDK-originating errors with meaningful remediation steps.