Getting started: Pub/Sub in JavaScript
This guide will get you started with Ably Pub/Sub in JavaScript.
You'll establish a realtime connection to Ably and learn to publish and subscribe to messages. You'll also implement presence to track other online clients, and learn how to retrieve message history.
Prerequisites
-
Sign up for an Ably account.
-
Create a new app, and create your first API key in the API Keys tab of the dashboard.
-
Your API key will need the
publish,subscribe,presenceandhistorycapabilities. -
Create an HTML file in your project directory where you'll include the Ably JavaScript SDK via a CDN.
(Optional) Install Ably CLI
Use the Ably CLI as an additional client to quickly test Pub/Sub features. It can simulate other clients by publishing messages, subscribing to channels, and managing presence states.
ably init installs the Ably CLI, authenticates, and sets the default app and API key in a single command:
npx @ably/cli initStep 1: Connect to Ably
Clients establish a connection with Ably when they instantiate an SDK instance. This enables them to send and receive messages in realtime across channels.
Open up the dev console of your first app before instantiating your client so that you can see what happens.
Create an index.html file in your project and add the following HTML to include the Ably JavaScript SDK via CDN and establish a connection to Ably. At the minimum you need to provide an authentication mechanism. Use an API key for simplicity, but you should use JWT authentication in a production app. A clientId ensures the client is identified, which is required to use certain features, such as presence:
1
2
3