IVS Chat Messaging SDK for JavaScript
The IVS Chat Messaging SDK makes it quick and easy to build excellent chat experience in your JavaScript or TypeScript app.
1. Table of contents
1.1. Getting Started
Before starting, you should be familiar with Getting Started with Amazon IVS Chat.
See also SDK Documentation.
1.1.1 Add the Package
$ npm install --save amazon-ivs-chat-messaging
or
$ yarn add amazon-ivs-chat-messaging
1.1.2 Set Up Your Backend
This integration requires endpoints on your server that talk to the Amazon IVS Chat API. Use the official AWS libraries for access to the Amazon IVS API from your server. These are accessible within several languages from the public packages; e.g.
node.js, java, go.
Next, create a server endpoint that talks to the AWS IVS Chat CreateChatToken endpoint in order to create a chat token for chat users.
You can follow our sample backend implementation as a reference.
1.1.3 Token provider function
Create an asynchronous token provider function that fetches chat token from your backend.
type ChatTokenProvider = () => Promise<ChatToken>;
Function should accept no parameters and return a Promise containing chat token object.
Chat token object should have following shape:
type ChatToken = {
token: string;
sessionExpirationTime?: Date;
tokenExpirationTime?: Date;
}
This function is needed to instantiate ChatRoom
object in the next step.
function tokenProvider(): Promise<ChatToken> {
return {
token: "<token>",
sessionExpirationTime: new Date("<date-time>"),
tokenExpirationTime: new Date("<date-time>")
}
}
Note: you need to fill in <token>
& <date-time>
fields with proper data received from you backend.
2. Using the SDK
2.1. Initialize a Chat Room Instance
Create an instance of the ChatRoom
class. It requires passing regionOrUrl
, which is the AWS region in which your chat room is hosted, and tokenProvider
which is the token fetching method created in the previous step.
import { ChatRoom } from 'amazon-ivs-chat-messaging';
const room = new ChatRoom({
regionOrUrl: 'us-west-2',
tokenProvider,
});
Next, you should subscribe for chat room events in order to receive lifecycle events, as well as receive messages & events delivered in the chat room.
const unsubscribeOnConnecting = room.addListener('connecting', () => { });
const unsubscribeOnConnected = room.addListener('connect', () => { });
const unsubscribeOnDisconnected = room.addListener('disconnect', () => { });
const unsubscribeOnMessageReceived = room.addListener('message', (message) => {
});
const unsubscribeOnEventReceived = room.addListener('event', (event) => {
});
const unsubscribeOnMessageDelete = room.addListener('messageDelete', (deleteMessageEvent) => {
});
const unsubscribeOnUserDisconnect = room.addListener('userDisconnect', (disconnectUserEvent) => {
});
The last step of the basic initialization is connecting to the chat room by establishing the WebSocket connection. In order to do that simply call a connect()
method within the room instance.
room.connect();
The SDK will attempt to establish a connection to chat room encoded in chat token received from your server.
After calling connect()
the room will transition into connecting
state and will also emit a connecting
event. When room successfully connects, it will transition into connected
state and will emit a connect
event.
In case of connection failure, which might happen either due to issues when fetching token or issues when connecting to WebSocket, the room will try to reconnect automatically up to number of times indicated by maxReconnectAttempts
constructor parameter. During the reconnection attempts the room will be in connecting
state and will not emit additional events. After exhausting the reconnect attempts the room will transition to disconnected
state and will emit a disconnect
event with relevant disconnect reason. In disconnected
state room will no longer attempt to connect, you will need to call connect()
again to trigger the connection process.
2.2. Perform Actions in a Chat Room
IVS Chat Messaging SDK offers user actions dedicated for sending messages, deleting messages and disconnecting other users.
Those are available on the ChatRoom
instance, and return Promise
object that allows you to receive request confirmation or rejection.
2.2.1. Sending a Message
Note: that for this particular request you need to have a SEND_MESSAGE
capacity encoded in your chat token.
To trigger a send-message request:
const request = new SendMessageRequest('Test Echo');
room.sendMessage(request);
If you are interested in receiving the confirmation or rejection of the request, you can await
returned promise or use then()
method:
try {
const message = await room.sendMessage(request);
} catch (error) {
}
2.2.2. Deleting a Message
Note: that for this particular request you need to have a DELETE_MESSAGE
capacity encoded in your chat token.
To trigger a delete-message request:
const request = new DeleteMessageRequest(messageId, 'Reason for deletion');
room.deleteMessage(request);
If you're interested receiving confirmation or rejection of the request, you can await
returned promise or use then()
method:
try {
const deleteMessageEvent = await room.deleteMessage(request);
} catch (error) {
}
2.2.3. Disconnecting Another User
In order to disconnect another user for moderation purposes call disconnectUser()
method.
Note: that for this particular request you need to have a DISCONNECT_USER
capacity encoded in your chat token.
To disconnect another user for moderation purposes:
const request = new DisconnectUserRequest(userId, 'Reason for disconnecting user');
room.disconnectUser(request);
If you're interested receiving confirmation or rejection of the request, you can await
returned promise or use then()
method:
try {
const disconnectUserEvent = await room.disconnectUser(request);
} catch (error) {
}
2.3. Disconnecting from a chat room
In order to close your connection to the chat room, call the disconnect()
method on the room
instance:
room.disconnect();
Calling this method will cause room to closes the underlying Web Socket in an orderly manner. The room instance will transition to a disconnected state and will emit a disconnect event, with disconnect reason being set to "clientDisconnect"
.
3. License
Amazon Interactive Video Service (IVS) (https://docs.aws.amazon.com/ivs/)
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Provided as AWS Content and subject to the AWS Customer Agreement
(https://aws.amazon.com/agreement/) and any other agreement with AWS
governing your use of AWS services.
See full license text for more information.