If you haven't had a chance to try out the Conversations demo application, follow the instructions in the Twilio Conversations Quickstart guide to get it up and running.
Within the quickstart application, you will find examples of the following:
- Using an access token to initialize the front end SPA
- Joining or leaving a conversation
- Sending messages to a conversation
- Receiving and displaying messages from a conversation
npm install --save @twilio/conversations
There is also a CDN installation, if you prefer:
<script src="https://media.twiliocdn.com/sdk/js/conversations/releases/2.1.0/twilio-conversations.min.js" integrity="sha256-v2SFLWujVq0wnwHpcxct7bzTP8wII7sumEhAKMEqgHQ=" crossorigin="anonymous"></script>
You would typically start by adding the
Conversations.Client from this SDK to your project, and then work with
Conversation objects to send and retrieve
Message objects for a given Conversation. Other important classes are
While we cover some of the basics of the Conversations JS SDK in this Quickstart, you can find reference documentation for each class as JSDocs. We also consider some of these topics in more detail in other pages in our docs, which we will link to in each section that has a corresponding guide.
For your chosen language and/or platform, pick the appropriate Twilio Helper Library:
On each of these pages, you will find instructions for setting up the Twilio helper library (also called a "server-side SDK"). We recommend using dependency management for the Twilio libraries, and you'll find directions for the most common build tools for your platform.
If you don't already have a Twilio account, sign up for a Twilio trial account, and then create a new project. You'll also need to create an API Key and API Secret pair to call Twilio's REST API, whether you use one of the Twilio helper libraries, or make the API calls yourself.
Each chat user in your Conversations project needs an identity - this could be their user id, their username, or some kind of other identifier. You could certainly have anonymous users in your Conversations - for instance, a web chat popup with a customer service agent on an e-commerce web site - but in that case, you would still want to issue some kind of identifier from your application.
Once you build Twilio Conversations into your project, you should generate an access token with a
ChatGrant for end users, along with the identity value.
With the Conversations JS Quickstart, the easiest way to get started is to create an access token from the Twilio Command Line Interface (CLI).
As part of this project, you will see that there are three different ways of providing credentials for Twilio - access tokens, auth tokens, and API keys. What is the difference between all of these different styles?
Although the names are similar, authentication (or auth) tokens are not the same as access tokens, and cannot be used in the same way. The auth token pairs with your Twilio account identifier (also called the account SID) to provide authentication for the Twilio REST API. Your auth token should be treated with the same care that you would use to secure your Twilio password, and should never be included directly in source code, made available to a client application, or checked into a file in source control.
Similar to auth tokens, API key/secret pairs secure access to the Twilio REST API for your account. When you create an API key and secret pair from the Twilio console, the secret will only be shown once, and then it won't be recoverable. In your back end application, you would authenticate to Twilio with a combination of your account identifier (also known as the "Account SID"), an API key, and an API secret.
The advantage of API keys over auth tokens is that it is easy to rotate API keys on your server application, especially if you use one API key and secret pair for each application cluster or instance. This way, you can have multiple credentials under your Twilio account, and if you need to swap out a key pair and then deactivate it, you can do it on an application basis, not on an account basis.
Whether you use auth tokens or API keys, we suggest that you store those credentials securely, and do not check them into source control. There are many different options for managing secure credentials that depend on how and where you run your development, staging, and production environments.
When you develop locally, look into using a
.env file with your project, usually in conjunction with a library named dotenv. For .NET Core, read our article on Setting Twilio Environment Variables in Windows 10 with PowerShell and .NET Core 3.0 to learn a lot more about this topic!
In the Conversations JS Quickstart, you can simply generate an access token using the Twilio Command Line Interface (CLI), and then paste that into the
ConversationsApp.js file. While this works for getting the quickstart up and running, you will want to replace this with your own function that retrieves an access token.
You can use
axios, or another client-side JS library to make an authenticated HTTP request to your server, where you would provide an access token with a
ChatGrant that sets the identity for the user based on your own authentication mechanism (such as a session cookie).
Ideally, this method would be usable for three different scenarios:
- Initializing the Conversations JS Client when the React component mounts
- Refreshing the access token when the Conversations JS Client notifies your application that the token is about to expire
- Refreshing the access token when the Conversations JS Client notifies your application that the token did expire
The first step is to get an access token. Once you have an access token (It is a string value.), you can initialize a Twilio Conversations Client. This client is the central class in the Conversations JS SDK, and you need to keep it around after initialization. The client is designed to be long-lived, and it will fire events off that your project can subscribe to.
After you initialize the Conversations client, the
connectionStateChanged event will fire any time the user's connection changes. The possible states handled in the Conversations JS Quickstart are:
Once the user is
connected, they are able to chat with others in conversations.
Conversation class is the building block of your Conversations application. In the JS Quickstart, as the user joins or leaves conversations,
conversationLeft events from the
ConversationsClient get fired with the
Conversation object as an argument. The React application maintains the list of conversations in its state, and then displays those conversations to the user in the
To send a message (with text content) to a conversation that a user has joined, you need to call the
sendMessage() method on the
Conversation instance. In the quickstart, we update the React component's state for the
newMessage variable to be empty, leaving the text input field open for another message.
While the Conversations JS Quickstart does not implement them, you can find a list of webhooks that you can enable for your Conversations project. These webooks include
onMessageAdd, which is a pre-action webhook that could filter the text in the message, and
onMessageAdded, which is a post-action webhook that could take action based on the contents of a message (such as updating a CRM).
The Conversations JS Quickstart also demonstrates how to send media, such as images, through the web browser interface using drag and drop. This functionality is in the Conversation.js file.
In the React Conversations demo, we created a
Conversation React component, which you can find in the src/Conversation.js file in the GitHub repo. As part of that component, we simply listen to the
messageAdded event on the SDK's
Conversation object. To distinguish between the React component and the representation of a conversation in the Twilio SDK, we will call the SDK version a conversation proxy here. This conversation proxy gets passed into the React component as a property, and then the React component interacts with the SDK by calling methods on it, or adding listeners.
Conversation component loads the existing messages from the conversation proxy, using the
getMessages() method on the Twilio SDK
Conversation class. This returns a paginator, and we load the messages from the first page of results up to display to the user when they join a conversation.
Using React also lets us easily handle the case where a new message gets added to the conversation. We listen to the
messageAdded event from the Twilio Conversations SDK
Conversation object, and then append that message to the messages we already have, and then set the state for the React component.
React handles the rendering for us as the messages list changes, which is much easier than trying to keep the DOM in sync with the message list manually.
For more information, check out these helpful links: