Types
The Ably client library defines both data types and option types. Data types are used to represent object such as messages. Option types are used in method arguments.
Where client libraries support both Realtime and REST APIs, the types are shared between both clients.
All types are always classes or their respective equivalent for each language implementation. Options on the other hand, may often support both typed option classes or more flexible key value objects such as a Hash or plain JavaScript object.
If you are interested in finding out more about the exact types and options definitions in each language, we recommend you download our open source libraries and review the code.
Data types
ChannelDetails
ChannelDetails is an object returned when requesting or receiving channel metadata. It contains information on the channel itself, along with the current state of the channel in the ChannelStatus object.
| Property | Description | Type |
|---|---|---|
| channelId | The required name of the channel including any qualifier, if any | string |
| region | In events relating to the activity of a channel in a specific region, this optionally identifies the region | string |
| isGlobalMaster | In events relating to the activity of a channel in a specific region, this optionally identifies whether or not that region is responsible for global coordination of the channel | boolean |
| status | An optional ChannelStatus instance | ChannelStatus |
The following is an example of a ChannelDetails JSON object:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"channelId": "foo",
"status": {
"isActive": true,
"occupancy": {
"metrics": {
"connections": 1,
"publishers": 1,
"subscribers": 1,
"presenceConnections": 1,
"presenceMembers": 0,
"presenceSubscribers": 1,
"objectPublishers": 1,
"objectSubscribers": 1
}
}
}
}ChannelDetails.ChannelStatus
ChannelStatus is contained within the ChannelDetails object, and optionally contains an Occupancy object.
| Property | Description | Type |
|---|---|---|
| isActive | A required boolean value indicating whether the channel that is the subject of the event is active. For events indicating regional activity of a channel this indicates activity in that region, not global activity | boolean |
| occupancy | An optional Occupancy instance indicating the occupancy of the channel. For events indicating regional activity of a channel this indicates activity in that region, not global activity | Occupancy |
ChannelDetails.ChannelStatus.Occupancy
Occupancy is optionally contained within the ChannelStatus object, and contains metadata relating to the occupants of the channel. This is usually contained within the occupancy attribute of the ChannelStatus object.
The occupancy attribute contains the metrics attribute, which contains the following members:
| Property | Description | Type |
|---|---|---|
| connections | The number of connections | integer |
| publishers | The number of connections attached to the channel that are authorised to publish | integer |
| subscribers | The number of connections attached that are authorised to subscribe to messages | integer |
| presenceSubscribers | The number of connections that are authorised to subscribe to presence messages | integer |
| presenceConnections | The number of connections that are authorised to enter members into the presence channel | integer |
| presenceMembers | The number of members currently entered into the presence channel | integer |
| objectPublishers | The number of connections that are authorised to publish updates to objects on the channel | integer |
| objectSubscribers | The number of connections that are authorised to subscribe to objects on the channel | integer |
ErrorInfo
An ErrorInfo is a type encapsulating error information containing an Ably-specific error code and generic status code.
Properties
| Property | Description | Type |
|---|---|---|
| code | Ably error code (see ably-common/protocol/errors.json) | Integer |
| statusCode | HTTP Status Code corresponding to this error, where applicable | Integer |
| message | Additional message information, where available | String |
| cause | Information pertaining to what caused the error where available | ErrorInfo |
| href | Ably may additionally include a URL to get more help on this error | String |
Error nesting
ErrorInfo objects can contain nested errors through the cause property, allowing you to trace the root cause of failures. When an operation fails due to underlying system errors, the main ErrorInfo provides the high-level failure reason while the nested cause contains more specific details about what went wrong.
One example of ErrorInfo nesting is 80019: Auth server rejecting request where the main error indicates token renewal failed, while the nested cause contains the specific HTTP error from the auth server.
The following example demonstrates how to handle nested errors:
1
2
3
4
5
6
7
8
9
10
11
12
13
function handleError(error) {
console.log(`Main error: ${error.code} - ${error.message}`);
// Check for nested error
if (error.cause) {
console.log(`Root cause: ${error.cause.code} - ${error.cause.message}`);
// Handle further nesting if needed
if (error.cause.cause) {
console.log(`Deeper cause: ${error.cause.cause.code} - ${error.cause.cause.message}`);
}
}
}Message
A Message represents an individual message that is sent to or received from Ably.
name
The event name, if provided.
Type: String
data
The message payload, if provided.
Type: String, StringBuffer, JSON Object
extras
Metadata and/or ancillary payloads, if provided. Valid payloads include push, headers (a map of strings to strings for arbitrary customer-supplied metadata), ephemeral, and privileged objects.
Type: JSON Object
id
A Unique ID assigned by Ably to this message.
Type: String
clientId
The client ID of the publisher of this message.
Type: String
connectionId
The connection ID of the publisher of this message.
Type: String
connectionKey
A connection key, which can optionally be included for a REST publish as part of the publishing on behalf of a realtime client functionality.
Type: String
timestamp
Timestamp when the message was first received by the Ably, as milliseconds since the epoch.
Type: Integer
encoding
This will typically be empty as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload.
Type: String
action
The action type of the message, one of the MessageAction enum values.
Type: int enum { MESSAGE_CREATE, MESSAGE_UPDATE, MESSAGE_DELETE, META, MESSAGE_SUMMARY }
serial
A server-assigned identifier that will be the same in all future updates of this message. It can be used to add annotations to a message. Serial will only be set if you enable annotations in channel rules.
Type: String
annotations
An object containing information about annotations that have been made to the object.
Type: MessageAnnotations
Message constructors
Message.fromEncoded
Message.fromEncoded(Object encodedMsg, ChannelOptions channelOptions?) -> Message
A static factory method to create a Message from a deserialized Message-like object encoded using Ably's wire protocol.
Parameters
| Parameter | Description | Type |
|---|---|---|
| encodedMsg | A Message-like deserialized object | Object |
| channelOptions | An optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the data | Object |
Returns
A Message object
Message.fromEncodedArray
Message.fromEncodedArray(Object[] encodedMsgs, ChannelOptions channelOptions?) -> Message[]
A static factory method to create an array of Messages from an array of deserialized Message-like object encoded using Ably's wire protocol.
Parameters
| Parameter | Description | Type |
|---|---|---|
| encodedMsgs | An array of Message-like deserialized objects | Array |
| channelOptions | An optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the data | Object |
Returns
An Array of Message objects
Message action
Message action is a String representing the action type of the message.
1
2
3
4
5
6
7
const MessageActions = [
'message.create',
'message.update',
'message.delete',
'meta',
'message.summary'
]MessageAnnotations
Properties
| Property | Description | Type |
|---|---|---|
| summary | An object whose keys are annotation types, and the values are aggregated summaries for that annotation type | Record<String, JsonObject> |
PresenceMessage
A PresenceMessage represents an individual presence update that is sent to or received from Ably.
Properties
| Property | Description | Type |
|---|---|---|
| action | The event signified by a PresenceMessage. See Presence action | int enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE } |
| data | The presence update payload, if provided | String, StringBuffer, JSON Object |
| extras | Metadata and/or ancillary payloads, if provided. The only currently valid payloads for extras are the push, ref and privileged objects | JSON Object |
| id | Unique ID assigned by Ably to this presence update | String |
| clientId | The client ID of the publisher of this presence update | String |
| connectionId | The connection ID of the publisher of this presence update | String |
| timestamp | Timestamp when the presence update was received by Ably, as milliseconds since the epoch | Integer |
| encoding | This will typically be empty as all presence updates received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload | String |
PresenceMessage constructors
PresenceMessage.fromEncoded
PresenceMessage.fromEncoded(Object encodedPresMsg, ChannelOptions channelOptions?) -> PresenceMessage
A static factory method to create a PresenceMessage from a deserialized PresenceMessage-like object encoded using Ably's wire protocol.
Parameters
| Parameter | Description | Type |
|---|---|---|
| encodedPresMsg | A PresenceMessage-like deserialized object | Object |
| channelOptions | An optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the data | Object |
Returns
A PresenceMessage object
PresenceMessage.fromEncodedArray
PresenceMessage.fromEncodedArray(Object[] encodedPresMsgs, ChannelOptions channelOptions?) -> PresenceMessage[]
A static factory method to create an array of PresenceMessages from an array of deserialized PresenceMessage-like object encoded using Ably's wire protocol.
Parameters
| Parameter | Description | Type |
|---|---|---|
| encodedPresMsgs | An array of PresenceMessage-like deserialized objects | Array |
| channelOptions | An optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the data | Object |
Returns
An Array of PresenceMessage objects
Presence action
Presence action is a String with a value matching any of the Realtime Presence states & events.
1
2
3
4
5
6
7
var PresenceActions = [
'absent', // (reserved for internal use)
'present',
'enter',
'leave',
'update'
]PaginatedResult
A PaginatedResult is a type that represents a page of results for all message and presence history, stats and REST presence requests. The response from a Ably REST API paginated query is accompanied by metadata that indicates the relative queries available to the PaginatedResult object.
Properties
| Property | Description | Type |
|---|---|---|
| items | Contains the current page of results (for example an Array of Message or PresenceMessage objects for a channel history request) | Array <Message, Presence, Stats> |
Methods
first
first(): Promise<PaginatedResult>
Returns a promise. On success, the promise is fulfilled with a new PaginatedResult for the first page of results. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.
hasNext
Boolean hasNext()
Returns true if there are more pages available by calling next and returns false if this page is the last page available.
isLast
Boolean isLast()
Returns true if this page is the last page and returns false if there are more pages available by calling next available.
next
next(): Promise<PaginatedResult | null>
Returns a promise. On success, the promise is fulfilled with a new PaginatedResult loaded with the next page of results. If there are no further pages, then null is returned. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.
current
current(): Promise<"PaginatedResult":#paginated-result>
Returns a promise. On success, the promise is fulfilled with a new PaginatedResult loaded with the current page of results. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.
Example
1
2
3
4
5
const paginatedResult = await channel.history();
console.log('Page 0 item 0:' + paginatedResult.items[0].data);
const nextPage = await paginatedResult.next();
console.log('Page 1 item 1: ' + nextPage.items[1].data);
console.log('Last page?: ' + nextPage.isLast());HttpPaginatedResponse
An HttpPaginatedResponse is a superset of PaginatedResult, which is a type that represents a page of results plus metadata indicating the relative queries available to it. HttpPaginatedResponse additionally carries information about the response to an HTTP request. It is used when making custom HTTP requests.
Properties
| Property | Description | Type |
|---|---|---|
| items | Contains a page of results; for example, an array of Message or PresenceMessage objects for a channel history request | Array<> |
| statusCode | The HTTP status code of the response | Number |
| success | Whether the HTTP status code indicates success. This is equivalent to 200 <= statusCode < 300 | Boolean |
| headers | The headers of the response | Object |
| errorCode | The error code if the X-Ably-Errorcode HTTP header is sent in the response | Number |
| errorMessage | The error message if the X-Ably-Errormessage HTTP header is sent in the response | String |
Methods
first
first(): Promise<HttpPaginatedResponse>
Returns a promise. On success, the promise is fulfilled with a new HttpPaginatedResponse for the first page of results. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.
hasNext
Boolean hasNext()
Returns true if there are more pages available by calling next and returns false if this page is the last page available.
isLast
Boolean isLast()
Returns true if this page is the last page and returns false if there are more pages available by calling next available.
next
next(): Promise<HttpPaginatedResponse>
Returns a promise. On success, the promise is fulfilled with a new HttpPaginatedResponse loaded with the next page of results. If there are no further pages, then null is returned. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.
current
current(): Promise<HttpPaginatedResponse>
Returns a promise. On success, the promise is fulfilled with a new HttpPaginatedResponse loaded with the current page of results. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.
Example
The HttpPaginatedResponse interface is a superset of PaginatedResult, see the PaginatedResult example
PushChannelSubscription
An PushChannelSubscription is a type encapsulating the subscription of a device or group of devices sharing a client identifier to a channel in order to receive push notifications.
Properties
| Property | Description | Type |
|---|---|---|
| channel | The channel that this push notification subscription is associated with | String |
| deviceId | The device with this identifier is linked to this channel subscription. When present, clientId is never present | String |
| clientId | Devices with this client identifier are included in this channel subscription. When present, deviceId is never present | String |
TokenDetails
TokenDetails is a type providing details of Ably Token string and its associated metadata.
Properties
| Property | Description | Type |
|---|---|---|
| token | The Ably Token itself. A typical Ably Token string may appear like {{TOKEN}} | String |
| expires | The time (in milliseconds since the epoch) at which this token expires | Integer |
| issued | The time (in milliseconds since the epoch) at which this token was issued | Integer |
| capability | The capability associated with this Ably Token. The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilities | String |
| clientId | The client ID, if any, bound to this Ably Token. If a client ID is included, then the Ably Token authenticates its bearer as that client ID, and the Ably Token may only be used to perform operations on behalf of that client ID. The client is then considered to be an identified client | String |
TokenDetails constructors
TokenDetails.fromJson
TokenDetails.fromJson(String json) -> TokenDetails
A static factory method to create a TokenDetails from a deserialized TokenDetails-like object or a JSON stringified TokenDetails. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenDetails object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenDetails, Ably ensures that all fields are consistently serialized and deserialized across platforms.
Parameters
| Parameter | Description | Type |
|---|---|---|
| json | A TokenDetails-like deserialized object or JSON stringified TokenDetails | Object, String |
Returns
A TokenDetails object
TokenRequest
TokenRequest is a type containing parameters for an Ably TokenRequest. Ably Tokens are requested using Auth#requestToken
Properties
| Property | Description | Type |
|---|---|---|
| keyName | The key name of the key against which this request is made. The key name is public, whereas the key secret is private | String |
| ttl | Requested time to live for the Ably Token in milliseconds. If the Ably TokenRequest is successful, the TTL of the returned Ably Token will be less than or equal to this value depending on application settings and the attributes of the issuing key. | Integer |
| timestamp | The timestamp of this request in milliseconds | Integer |
| capability | Capability of the requested Ably Token. If the Ably TokenRequest is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. The capability is a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilities | String |
| clientId | The client ID to associate with the requested Ably Token. When provided, the Ably Token may only be used to perform operations on behalf of that client ID | String |
| nonce | An opaque nonce string of at least 16 characters | String |
| mac | The Message Authentication Code for this request | String |
TokenRequest constructors
TokenRequest.fromJson
TokenRequest.fromJson(String json) -> TokenRequest
A static factory method to create a TokenRequest from a deserialized TokenRequest-like object or a JSON stringified TokenRequest. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenRequest object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenRequest, Ably ensures that all fields are consistently serialized and deserialized across platforms.
Parameters
| Parameter | Description | Type |
|---|---|---|
| json | A TokenRequest-like deserialized object or JSON stringified TokenRequest | Object, String |
Returns
A TokenRequest object
Stats object
A Stats object represents an application's statistics for the specified interval and time period. Ably aggregates statistics globally for all accounts and applications, and makes these available both through our statistics API as well as your application dashboard.
Properties
| Property | Description | Type |
|---|---|---|
| appId | The ID of the Ably application the statistics relate to | String |
| entries | The statistics for the requested time interval and time period. The schema property provides further information | Partial<Record<String, Number>> |
| inProgress | Optional. For entries that are still in progress, such as the current month, the last sub-interval included in the stats entry. In the format yyyy-mm-dd:hh:mm:ss | String |
| intervalId | The UTC time period that the stats coverage begins at. If unit was requested as minute this will be in the format YYYY-mm-dd:HH:MM, if hour it will be YYYY-mm-dd:HH, if day it will be YYYY-mm-dd:00 and if month it will be YYYY-mm-01:00 | String |
| schema | The URL of a JSON schema describing the structure of the Stats object | String |
StatsIntervalGranularity
StatsIntervalGranularity is an enum specifying the granularity of a Stats interval.
1
2
3
4
5
6
const StatsIntervalGranularity = [
'minute',
'hour',
'day',
'month'
]BatchPublishSpec
A BatchPublishSpec describes the messages that should be published by a batch publish operation, and the channels to which they should be published.
Properties
| Property | Description | Type |
|---|---|---|
| channels | The names of the channels to publish the messages to | String[] |
| messages | An array of Message objects | Message[] |
BatchResult
A BatchResult contains information about the results of a batch operation.
Properties
| Property | Description | Type |
|---|---|---|
| successCount | The number of successful operations in the request | Number |
| failureCount | The number of unsuccessful operations in the request | Number |
| messages | An array of results for the batch operation (for example, an array of BatchPublishSuccessResult or BatchPublishFailureResult for a channel batch publish request) | Object[] |
BatchPublishSuccessResult
A BatchPublishSuccessResult contains information about the result of successful publishes to a channel requested by a single BatchPublishSpec.
Properties
| Property | Description | Type |
|---|---|---|
| channel | The name of the channel the message(s) was published to | String |
| messageId | A unique ID prefixed to the Message.id of each published message | String |
BatchPublishFailureResult
A BatchPublishFailureResult contains information about the result of unsuccessful publishes to a channel requested by a single BatchPublishSpec.
Properties
| Property | Description | Type |
|---|---|---|
| channel | The name of the channel the message(s) failed to be published to | String |
| error | Describes the reason for which the message(s) failed to publish to the channel as an ErrorInfo object | ErrorInfo |
BatchPresenceSuccessResult
A BatchPresenceSuccessResult contains information about the result of a successful batch presence request for a single channel.
Properties
| Property | Description | Type |
|---|---|---|
| channel | The channel name the presence state was retrieved for | String |
| presence | An array of PresenceMessage describing members present on the channel | PresenceMessage[] |
BatchPresenceFailureResult
A BatchPresenceFailureResult contains information about the result of an unsuccessful batch presence request for a single channel.
Properties
| Property | Description | Type |
|---|---|---|
| channel | The channel name the presence state failed to be retrieved for | String |
| error | Describes the reason for which presence state could not be retrieved for the channel as an ErrorInfo object | ErrorInfo |
TokenRevocationSuccessResult
A TokenRevocationSuccessResult contains information about the result of a successful token revocation request for a single target specifier.
Properties
| Property | Description | Type |
|---|---|---|
| target | The target specifier | String |
| appliesAt | The time at which the token revocation will take effect, as a Unix timestamp in milliseconds | Number |
| issuedBefore | A Unix timestamp in milliseconds. Only tokens issued earlier than this time will be revoked | Number |
TokenRevocationFailureResult
A TokenRevocationFailureResult contains information about the result of an unsuccessful token revocation request for a single target specifier.
Properties
| Property | Description | Type |
|---|---|---|
| target | The target specifier | String |
| error | Describes the reason for which token revocation failed for the given target as an ErrorInfo object | ErrorInfo |
Other types
AuthOptions Object
AuthOptions is a plain JavaScript object and is used when making authentication requests. If passed in, an authOptions object will be used instead of (as opposed to supplementing or being merged with) the default values given when the library was instantiated. The following attributes are supported:
Properties
| Property | Description | Type |
|---|---|---|
| authCallback | A functionfunction with the form function(tokenParams, callback(err, tokenOrTokenRequest)) which is called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed TokenRequest; a TokenDetails (in JSON format); an Ably JWT. See our authentication documentation for details of the Ably TokenRequest format and associated API calls. | Callable |
| authUrl | A URL that the library may use to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed TokenRequest; a TokenDetails (in JSON format); an Ably JWT. For example, this can be used by a client to obtain signed Ably TokenRequests from an application server. | String |
| authMethod | GET The HTTP verb to use for the request, either GET or POST | String |
| authHeaders | A set of key value pair headers to be added to any request made to the authUrl. Useful when an application requires these to be added to validate the request or implement the response. If the authHeaders object contains an authorization key, then withCredentials will be set on the xhr request. | Object |
| authParams | A set of key value pair params to be added to any request made to the authUrl. When the authMethod is GET, query params are added to the URL, whereas when authMethod is POST, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response. | Object |
| tokenDetails | An authenticated TokenDetails object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as authUrl or authCallback. Use this option if you wish to use Token authentication. Read more about Token authentication | TokenDetails |
| key | Optionally the API key to use can be specified as a full key string; if not, the API key passed into ClientOptions when instancing the Realtime or REST library is used | String |
| queryTime | false If true, the library will query the Ably servers for the current time when issuing TokenRequests instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably TokenRequests, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an NTP daemon. The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request. | Boolean |
| token | An authenticated token. This can either be a TokenDetails object, a TokenRequest object, or token string (obtained from the token property of a TokenDetails component of an Ably TokenRequest response, or a JSON Web Token satisfying the Ably requirements for JWTs). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as authUrl or authCallback. Read more about Token authentication | String, TokenDetails or TokenRequest |
ClientOptions Object
ClientOptions is a plain JavaScript object and is used in the Ably.Realtime constructor's options argument. The following attributes can be defined on the object:
Properties
| Property | Description | Type |
|---|---|---|
| key | The full key string, as obtained from the application dashboard. Use this option if you wish to use Basic authentication, or wish to be able to issue Ably Tokens without needing to defer to a separate entity to sign Ably TokenRequests. Read more about Basic authentication | String |
| token | An authenticated TokenDetails object, a TokenRequest object, or token string (obtained from the token property of a TokenDetails component of an Ably TokenRequest response, or a JSON Web Token satisfying the Ably requirements for JWTs). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as authUrl or authCallback. Read more about Token authentication | String, TokenDetails or TokenRequest |
| authCallback | A function with the form function(tokenParams, callback(err, tokenOrTokenRequest)) which is called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed TokenRequest; a TokenDetails (in JSON format); an Ably JWT. See our authentication documentation for details of the Ably TokenRequest format and associated API calls | Callable |
| authUrl | A URL that the library may use to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed TokenRequest; a TokenDetails (in JSON format); an Ably JWT. For example, this can be used by a client to obtain signed Ably TokenRequests from an application server | String |
| authMethod | The HTTP verb to use for the request, either GET or POSTDefault: GET | String |
| authHeaders | A set of key value pair headers to be added to any request made to the authUrl. Useful when an application requires these to be added to validate the request or implement the response. If the authHeaders object contains an authorization key, then withCredentials will be set on the xhr request | Object |
| authParams | A set of key value pair params to be added to any request made to the authUrl. When the authMethod is GET, query params are added to the URL, whereas when authMethod is POST, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response | Object |
| tokenDetails | An authenticated TokenDetails object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as authUrl or authCallback. Use this option if you wish to use Token authentication. Read more about Token authentication | TokenDetails |
| tls | A boolean value, indicating whether or not a TLS ("SSL") secure connection should be used. An insecure connection cannot be used with Basic authentication as it would lead to a possible compromise of the private API key while in transit. Find out more about TLS Default: true | Boolean |
| clientId | A client ID, used for identifying this client when publishing messages or for presence purposes. The clientId can be any non-empty string. This option is primarily intended to be used in situations where the library is instantiated with a key; note that a clientId may also be implicit in a token used to instantiate the library; an error will be raised if a clientId specified here conflicts with the clientId implicit in the token. Find out more about client identities | String |
| useTokenAuth | When true, forces Token authentication to be used by the library. Please note that if a clientId is not specified in the ClientOptions or TokenParams, then the Ably Token issued will be anonymousDefault: false | Boolean |
| endpoint | Enables enterprise customers to use their own custom endpoints, which support dedicated, isolated clusters and regional message routing and storage constraints. See our platform customization guide for more details Default: null | String |
| environment | Deprecated, use endpoint. Enables enterprise customers to use their own custom environments, which support dedicated, isolated clusters and regional message routing and storage constraints. See our platform customization guide for more detailsDefault: null | String |
| idempotentRestPublishing | When true, enables idempotent publishing by assigning a unique message ID client-side, allowing the Ably servers to discard automatic publish retries following a failure such as a network fault. We recommend you enable this by default. In version 1.2 onwards, idempotent publishing for retries will be enabled by default Default: false | Boolean |
| fallbackHosts | An array of fallback hosts to be used in the case of an error necessitating the use of an alternative host. When a custom environment is specified, the fallback host functionality is disabled. If your customer success manager has provided you with a set of custom fallback hosts, please specify them here Default: [a.ably-realtime.com, b.ably-realtime.com, c.ably-realtime.com, d.ably-realtime.com, e.ably-realtime.com] | String[] |
| transportParams | Optional. Can be used to pass in arbitrary connection parameters, such as heartbeatInterval and remainPresentFor | Object |
| useBinaryProtocol | If set to true, will enable the binary protocol (MessagePack) if it is supported. It's disabled by default on browsers for performance considerations (browsers are optimized for decoding JSON). Find out more about the benefits of binary encoding Default: false | Boolean |
| queueMessages | If false, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior allows applications to submit messages immediately upon instancing the library without having to wait for the connection to be established. Applications may use this option to disable queueing if they wish to have application-level control over the queueing under those conditions Default: true | Boolean |
| echoMessages | If false, prevents messages originating from this connection being echoed back on the same connection Default: true | Boolean |
| autoConnect | By default as soon as the client library is instantiated it will connect to Ably. You can optionally set this to false and explicitly connect to Ably when require using the connect methodDefault: true | Boolean |
| logLevel | A number controlling the verbosity of the log output of the library. Valid values are: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output) | Integer |
| logHandler | A function to handle each line of the library's log output. If logHandler is not specified, console.log is usedDefault: console.log | Callable |
| transports | An optional array of transports to use, in descending order of preference. In the browser environment the available transports are: web_socket, xhr_polling | String[] |
| recover | This option allows a connection to inherit the state of a previous connection that may have existed under a different instance of the Realtime library. This might typically be used by clients of the browser library to ensure connection state can be preserved when the user refreshes the page. A recovery key string can be explicitly provided, or alternatively if a callback function is provided, the client library will automatically persist the recovery key between page reloads and call the callback when the connection is recoverable. The callback is then responsible for confirming whether the connection should be recovered or not. See connection state recovery for further information | String, Callable |
| closeOnUnload | When true, the client library will automatically send a close request to Ably whenever the window beforeunload event fires. By enabling this option, the close request sent to Ably ensures the connection state will not be retained and all channels associated with the connection will be detached. This is commonly used by developers who want presence leave events to fire immediately i.e. if a user navigates to another page or closes their browser, then enabling this option will result in the presence member leaving immediately. Without this option or an explicit call to the close method of the Connection object, Ably expects that the abruptly disconnected connection could later be recovered and therefore does not immediately remove the user from presence. Instead, to avoid "twitchy" presence behavior an abruptly disconnected client is removed from channels in which they are present after 15 seconds, and the connection state is retained for two minutesDefault: true | Boolean |
| queryTime | If true, the library will query the Ably servers for the current time when issuing TokenRequests instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably TokenRequests, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an NTP daemon. The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request Default: false | Boolean |
| defaultTokenParams | When a TokenParams object is provided, it will override the client library defaults when issuing new Ably Tokens or Ably TokenRequests | TokenParams |
| disconnectedRetryTimeout | When the connection enters the DISCONNECTED state, after this delay in milliseconds, if the state is still DISCONNECTED, the client library will attempt to reconnect automaticallyDefault: 15,000ms | Integer |
| suspendedRetryTimeout | When the connection enters the SUSPENDED state, after this delay in milliseconds, if the state is still SUSPENDED, the client library will attempt to reconnect automaticallyDefault: 30,000ms | Integer |
| pushServiceWorkerUrl | A URL pointing to a service worker script which is used as the target for web push notifications | String |
ChannelOptions Object
Channel options are used for setting channel parameters and configuring encryption.
ChannelOptions, a plain JavaScript object, may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options. The following attributes can be defined on the object:
Properties
| Property | Description | Type |
|---|---|---|
| params | Optional parameters which specify behaviour of the channel. | JSON Object |
| cipher | Requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See an example | CipherParams or an options object containing at a minimum a key |
ChannelState
ChannelState is a String with a value matching any of the Realtime Channel states.
1
2
3
4
5
6
7
8
9
var ChannelStates = [
'initialized',
'attaching',
'attached',
'detaching',
'detached',
'failed',
'suspended'
]ChannelEvent
ChannelEvent is a String that can be emitted as an event on the Channel object; either a ChannelState or an update event.
1
2
3
4
5
6
7
8
9
10
var ChannelEvents = [
'initialized',
'attaching',
'attached',
'detaching',
'detached',
'failed',
'suspended',
'update'
]ChannelStateChange Object
A ChannelStateChange is a type encapsulating state change information emitted by the Channel object. See Channel#on to register a listener for one or more events.
Properties
| Property | Description | Type |
|---|---|---|
| current | The new current state | ChannelState |
| previous | The previous state. (for the update event, this will be equal to the current state) | ChannelState |
| event | The event that triggered this state change | ChannelEvent |
| reason | An ErrorInfo containing any information relating to the transition | ErrorInfo |
| resumed | A boolean indicated whether message continuity on this channel is preserved, see Nonfatal channel errors for more info. | Boolean |
CipherParams
A CipherParams contains configuration options for a channel cipher, including algorithm, mode, key length and key. Ably client libraries currently support AES with CBC, PKCS#7 with a default key length of 256 bits. All implementations also support AES128.
Individual client libraries may support either instancing a CipherParams directly, using Crypto.getDefaultParams(), or generating one automatically when initializing a channel, as in this example.
Properties
| Property | Description | Type |
|---|---|---|
| key | A binary (ArrayBuffer or Uint8Array) or base64-encoded String containing the secret key used for encryption and decryption | Binary or String |
| algorithm | AES The name of the algorithm in the default system provider, or the lower-cased version of it; eg "aes" or "AES" | String |
| keyLength | 256 The key length in bits of the cipher, either 128 or 256 | Integer |
| mode | CBC The cipher mode | String |
ConnectionState
ConnectionState is a String with a value matching any of the Realtime Connection states.
1
2
3
4
5
6
7
8
9
10
var ConnectionStates = [
'initialized',
'connecting',
'connected',
'disconnected',
'suspended',
'closing',
'closed',
'failed'
]ConnectionEvent
ConnectionEvent is a String that can be emitted as an event on the Connection object; either a Realtime Connection state or an update event.
1
2
3
4
5
6
7
8
9
10
11
var ConnectionEvents = [
'initialized',
'connecting',
'connected',
'disconnected',
'suspended',
'closing',
'closed',
'failed',
'update'
]ConnectionStateChange Object
A ConnectionStateChange is a type encapsulating state change information emitted by the Connection object. See Connection#on to register a listener for one or more events.
Properties
| Property | Description | Type |
|---|---|---|
| current | The new state | State String |
| previous | The previous state. (for the update event, this will be equal to the current state) | State String |
| event | The event that triggered this state change | ConnectionEvent |
| reason | An ErrorInfo containing any information relating to the transition | ErrorInfo |
| retryIn | Duration upon which the library will retry a connection where applicable, as milliseconds | Integer |
LastConnectionDetails
A LastConnectionDetails object provides details on the last connection in a browser environment persisted when the window beforeunload fired. This object is provided to the callback specified in the recover attribute of ClientOptions. The callback in turn instructs the client library whether the connection should be recovered or not. See connection state recovery for more information.
Please note that as sessionStorage is used to persist the LastConnectionDetails between page reloads, it is only available for pages in the same origin and top-level browsing context.
Properties
| Property | Description | Type |
|---|---|---|
| recoveryKey | An opaque string obtained from the recoveryKey attribute of the Connection object before the page was unloaded. This property is used by the library to recover the connection | String |
| disconnectedAt | The time at which the previous library was abruptly disconnected before the page was unloaded. This is represented as milliseconds since epoch | Integer |
| location | A clone of location object of the previous page's document object before the page was unloaded. A common use case for this attribute is to ensure that the previous page URL is the same as the current URL before allowing the connection to be recovered. For example, you may want the connection to be recovered only for page reloads, but not when a user navigates to a different page | String |
| clientId | The clientId of the client's Auth object before the page was unloaded. A common use case for this attribute is to ensure that the current logged in user's clientId matches the previous connection's clientId before allowing the connection to be recovered. Ably prohibits changing a clientId for an existing connection, so any mismatch in clientId during a recover will result in the connection moving to the failed state | String |
TokenParams Object
TokenParams is a plain JavaScript object and is used in the parameters of token authentication requests, corresponding to the desired attributes of the Ably Token. The following attributes can be defined on the object:
Properties
| Property | Description | Type |
|---|---|---|
| capability | JSON stringified capability of the Ably Token. If the Ably Token request is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. Find our more about how to use capabilities to manage access privileges for clients. | String |
| clientId | A client ID, used for identifying this client when publishing messages or for presence purposes. The clientId can be any non-empty string. This option is primarily intended to be used in situations where the library is instantiated with a key; note that a clientId may also be implicit in a token used to instantiate the library; an error will be raised if a clientId specified here conflicts with the clientId implicit in the token. Find out more about client identities | String |
| nonce | An optional opaque nonce string of at least 16 characters to ensure uniqueness of this request. Any subsequent request using the same nonce will be rejected. | String |
| timestamp | The timestamp (in milliseconds since the epoch) of this request. timestamp, in conjunction with the nonce, is used to prevent requests for Ably Token from being replayed. | Integer |
| ttl | 1 hour Requested time to live for the Ably Token being created in milliseconds. When omitted, the Ably REST API default of 60 minutes is applied by Ably | Integer (milliseconds) |
TokenRevocationTargetSpecifier
TokenRevocationTargetSpecifier
A TokenRevocationTargetSpecifier describes which tokens should be affected by a token revocation request.
Properties
| Property | Description | Type |
|---|---|---|
| type | The type of token revocation target specifier. Valid values include clientId, revocationKey and channel | String |
| value | The value of the token revocation target specifier | String |
TokenRevocationOptions
TokenRevocationOptions
A TokenRevocationOptions describes the additional options accepted by revoke tokens request.
Properties
| Property | Description | Type |
|---|---|---|
| issuedBefore | An optional Unix timestamp in milliseconds where only tokens issued before this time are revoked. The default is the current time. Requests with an issuedBefore in the future, or more than an hour in the past, will be rejected | Number |
| allowReauthMargin | false If true, permits a token renewal cycle to take place without needing established connections to be dropped, by postponing enforcement to 30 seconds in the future, and sending any existing connections a hint to obtain (and upgrade the connection to use) a new token. The default is false, meaning that the effect is near-immediate. | Boolean |