SDK setup

Use these instructions to install, authenticate and instantiate the Spaces SDK.

An API key is required to authenticate with Ably. API keys are used either to authenticate directly with Ably using basic authentication, or to generate tokens for untrusted clients using token authentication.

Sign up to Ably to create an API key in the dashboard or use the Control API to create an API programmatically.

API keys and tokens have a set of capabilities assigned to them that specify which operations, such as subscribe or publish can be performed on which resources. To use the Spaces SDK, the API key requires the following capabilities

  • Publish
  • Subscribe
  • Presence
  • History

The Spaces SDK is built on top of the Ably JavaScript SDK and uses it to establish a connection with Ably. Therefore the Ably JavaScript SDK is installed alongside the Spaces SDK.

Both SDKs are available as NPM modules and via CDN.

Install the Ably JavaScript SDK and the Spaces SDK:

npm install ably @ably/spaces

Import the SDKs into your project:

JavaScript v1.2
import Spaces from '@ably/spaces'; import { Realtime } from 'ably';

Reference the Ably JavaScript SDK and the Spaces SDK within the <head> of your HTML file:

<script src=""></script> <script src=""></script>

Instantiate a realtime client using the Ably JavaScript SDK and pass the generated client into the Spaces constructor:

JavaScript v1.2
const client = new Realtime.Promise({key: "<API-key>", clientId: "<client-ID>"}); const spaces = new Spaces(client);

A ClientOptions object may be passed to the Ably JavaScript SDK to further customize the connection, however at a minimum you must set your API key and provide a clientId so that the client is identified.

A Spaces client exposes the underlying connection to Ably that is established via the Ably JavaScript SDK. This means that Spaces clients benefit from the same functionality available in the Ably JavaScript SDK, such as automatic transport selection and connection state recovery in the event of brief disconnections.

Connections transition through multiple states throughout their lifecycle. Whilst these transitions are handled by the Ably SDK, there are certain cases where you may need to observe and handle them within your application. Ably SDKs enable these transitions to be observed and triggered using methods available on the connection object. The Spaces SDK exposes the underlying connection with spaces.connection, which is a reference to client.connection in the Ably JavaScript SDK.