SDK setup
Use these instructions to install, authenticate and instantiate the Spaces SDK.
Authenticate
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
Install
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.
Using NPM
Install the Ably JavaScript SDK and the Spaces SDK:
npm install @ably/spaces
CopyCopied!
Import the SDKs into your project:
import Spaces from '@ably/spaces';
import { Realtime } from 'ably';
CopyCopied!
Using a CDN
Reference the Ably JavaScript SDK and the Spaces SDK within the <head>
of your HTML file:
<script src="https://cdn.ably.com/lib/ably.min-2.js"></script>
<script src="https://cdn.ably.com/spaces/0.4/iife/index.bundle.js"></script>
CopyCopied!
Instantiate
Instantiate a realtime client using the Ably JavaScript SDK and pass the generated client into the Spaces constructor:
const client = new Realtime({key: "<API-key>", clientId: "<client-ID>"});
const spaces = new Spaces(client);
CopyCopied!
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.
Client connections
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.