How to Build Simple Chat Apps with JavaScript, Node.js and Twilio

nodejs logo

Twilio Chat makes it easy to add chat capability to your application by handling the worst devilish details that come up when building real-time chat. In this post we’ll walk you through how to add Twilio Chat to your own web application using JavaScript. The requirement to follow along are:

  1. An understanding of HTML, JavaScript and CSS.
  2. Some familiarity with Node.JS and Express or a similar framework
  3. Have node, git, and npm installed.

Below is a peek at what we’ll be building, and the completed source code of what we’ll be building is on GitHub.

Setting Up Twilio Chat Service

To get started we need to create a Chat Service from the Twilio console. If you don’t already have a Twilio account, sign up for a free account here. Then in the Console, create a new chat service and enter a name for the service.

The Chat Service is a way to scope the resources needed for building this application and making sure they do not overlap or interact with other resources we might have defined. The resources available in a Service include:

  • User: A user is a unique entity with an identity that can connect to the chat service and send messages to other users.
  • Message: A message is of a string datatype that is used to pass message across to other users in the system.
  • Channel: A channel is the medium by which messages sent by a user are distributed to other users (Members) of the channel. Chat Messages exist within a Service as part of a Channel. Channels can either be private or public.
  • Public channels are available to users within the service and they can freely join or leave.
  • Private channels are not available when browsed by users. A user can join by invitation or be added by the channel admin.
  • Member: A user within a channel is referred to as a Member.
  • Roles and Permissions: Roles and Permissions are used to enforce what Users and Members can do within a Service instance.

After creating the Service, note the service SID which will be used by the chat client SDK, which provides APIs to connect to the chat service and send messages between users. We also need an API key and secret, which will be used to generate an access token to the Chat Service. All chat client SDK need a valid access token to be able to authenticate and interact with the chat service.  Create a new API key with the following steps:

  • Click the Back link in the side menu.
  • Click the Tools menu that appears, then select API Keys.
  • On the new page that appears, click the Create new API Key button.
  • Enter a name for the key and hit enter on your keyboard.

You should get a page showing your API key (SID) and secret. Save them in a safe place as you won’t be able to retrieve these values again. This page is shown only once.

Source Code

With the Service instance created on Twilio, we now need to write some code. Open the terminal or command prompt and run the following command

These pulls a set of files from GitHub with a defined html, css, and a server script for serving the files and responding to http request.
Run the command npm install to install express, the default package that comes with the source code.

Building the backend

We need to build the backend code that’ll generate and return access token to the frontend. Open the terminal (or command prompt on Windows) and run the following command in the project src directory:

In the src directory, open the file called server.js. It contains a predefined route to serve the files in the public folder. Our next step will be to define a route which will provide users with Access Token based on their identity. An access token is used by the twilio client SDK to interact with the Chat Service. We will generate this token with the help of the twilio library we installed in the last step.

To use this package, add a reference to it in server.js

Define a route named /token with the necessary code to generate the token.

We initialise the AccessToken object with the necessary credentials which can be retrieved from the dashboard and the API secret from the the safe location you saved it in when we created an API Key at the beginning. Then we initialise a ChatGrant object with our chat service SID and add the grant to the AccessToken instance and return the generated token to the client. Take note of the variables which require your credentials from your account. Replace them accordingly.

Crafting the frontend

In the git repository we cloned, we already have some files with content in the src/public folder. If you open the index.js  file, you’ll notice we referenced a couple scripts and styles in the header. Two important script files we’ll look at are, index.js and Twilio Chat client sdk ( We also added a micro-template which will be used as a template for chat messages, a technique used by many javascript templating engines.

index.js is where we’ll add functionality to interact and send messages through the twilio service. Open the file and add the following content.

We have no form of authentication so before a user starts a conversation we request a username as a means of identifying the user. Once we have that we need to generate an access token which will be used by the Twilio SDK to communicate with our chat service on the Twilio server. Add the following code, which calls the backend to request for access token for the user:

When we get the token the next step is to initialise the Twilio Chat SDK  with that token. Once initialised the user can join channels and exchange messages with the members in a channel. Add the following code to index.js in order to initialise the SDK and join a channel:

From the code above, when we get the token we call Twilio.Chat.Client.create(token) which initialises and returns an instance of the Client object. If successfully instantiated, then a call is made to getChannelDescriptor which either creates a new channel or returns the existing one.

 chatClient.getPublicChannelDescriptors fetches a list of Channel Descriptors for all public channels in the service. A channel descriptor is an object that describes a channel. Once we have a channel, we then call the join method on it to have this client join the channel and subscribe to events.

If successfully added to a channel, we need to subscribe to the messageAdded event which signals is raised whenever a new message is published to the channel. Add the code below to index.js to do that:

We subscribe to the messageAdded event on the channel passing it a callback which displays the message to the user, and then call activateChatBox to setup the message input element and button click event to send the message. When the send button is clicked, we call chatChannel.sendMessage(message) to send the message to other connected clients.

Testing the application

To test our application, we’ll need to start the node server and navigate to the page in the browser. Do these following these steps:

  1. Open the terminal (or command prompt on windows) and run the command:  npm start.
  2. It starts the application on localhost in port 5000.
  3. Open 2 or more browser tabs and navigate to localhost:5000
  4. It shows the web page and request for a username. Choose your preferred usernames and send message across users through the message box.


That’s a wrap! Integrating real-time conversation to your application is fast and easy with Twilio Chat. From setting up a Twilio Service to using the SDK, integration is seamless. This post showed how to build a simple chat app, but there are many more features included in Twilio Chat which you can take advantage of. Check the documentation for more details, and stay tuned for more samples on how to use Twilio Chat.

You can find the sample code here on GitHub. If you encounter errors while working through this post or with the finished source code, please leave a comment or open an issue on GitHub. You can extend it and if you’d like to show me what extra functionality you added, got questions, or want to send a thank you tweet, you can reach me on twitter @p_mbanugo.

  • Elena Lauren

    I am beginner in Node.js. Finally, I got my answer after many hours of surfing the web by reading your article. hope to see more posts on this technology.

  • venkatesh

    thanks for the great post corporate website design