Prerequisites
- Sign up for an Ably account.
- Create a new app, and get your first API key. You can use the root API key that is provided by default, within the API Keys tab to get started.
- Install any current LTS version of Node.js and create a new project:
- Install @ably/chat, typescript to compile TypeScript files and make Ably Chat connections.
- Create a default TypeScript configuration in your project
- Update
tsconfig.jsonto havetypescontainingnode:
- Create a
.envfile in your project root and add your API key:
Step 1: Connect to Ably
Clients establish a connection with Ably when they instantiate an SDK. This enables them to send and receive messages in realtime across channels. Create anindex.ts file in your project and add the following function to instantiate a realtime client with the Pub/Sub SDK and then pass that client into the Chat SDK constructor. Provide an API key and a clientId to identify the client. In production, use token authentication so that your API keys are not exposed publicly.
You can monitor the lifecycle of clients’ connections by registering a listener that will emit an event every time the connection state changes. For now, run the function with npx tsx --env-file=.env index.ts to log a message to the console to know that the connection attempt was successful. You’ll see a message saying Connection status is currently connected! printed to your console.
Step 2: Create a Room and Send a Message
Messages are how your clients interact with one another. Use rooms to separate and organize clients and messages into different topics, or ‘chat rooms’. Rooms are the entry object into Chat, providing access to all of its features, such as messages, presence and reactions. Add the following lines to yourgetStarted() function to create an instance of a room, attach to the room instance, and then register a listener to subscribe to messages sent to the room. You then also send your first message. Afterwards, run it with npx tsx --env-file=.env index.ts:
Next Steps
Continue to explore the documentation with JavaScript as the selected language:- Understand token authentication before going to production
- Read more about using rooms and sending messages
- Find out more regarding presence
- Read into pulling messages from history and providing context to new joiners
