Menu

Expand
Rate this page:

Chat with Node.js and Express

We intend to sunset the Programmable Chat API on July 25, 2022 to focus on the next generation of chat: the Twilio Conversations API. Find out about the EOL process. We have also prepared this Migration Guide to assist in the transition from Chat to Conversations.

Ready to implement a chat application using Twilio Programmable Chat Client, Node.js and Express?

This application allow users to exchange messages through different channels, using the Twilio Programmable Chat API. On this example, we'll show how to use this API capabilities to manage channels and their usages.

Properati built a web and mobile messaging app to help real estate buyers and sellers connect in real time. Learn more here.

For your convenience, we consolidated the source code for this tutorial in a single GitHub repository. Feel free to clone it and tweak as required.

Let's get started!

Token Generation

In order to create a Twilio Programmable Chat client, you will need an access token. This token holds information about your Twilio Account and Programmable Chat API keys.

We generate this token by creating a new AccessToken and providing it with an ChatGrant. The new AccessToken object is created using your Twilio credentials.

        
        
        
        services/tokenService.js

        Generate an Access Token

        services/tokenService.js

        We can generate a token, now we need a way for the chat app to get it.

        Token Generation Controller

        Token Generation Controller

        On our controller we expose the endpoint for token generation. This endpoint is responsible for providing a valid token when passed this parameter:

        • identity: identifies the user itself.

        Once we have used the tokenService object to generate a token we can use the AccessToken's method as token.toJwt() to get the token as a String. Then we just return the token as a JSON encoded string.

              
              
              
              routes/token.js

              Token Generation Controller

              routes/token.js

              Now that we have a route that generates JWT tokens on demand, let's use this route to initialize our Twilio Chat Client.

              Initialize the Chat Client

              Initialize the Programmable Chat Client

              Our client fetches a new Token by making a POST request to our endpoint when it calls the fetchAccessToken method.

              With the token we can then instantiate Twilio.Chat.Client in connectMessagingClient.

                    
                    
                    
                    public/js/twiliochat.js

                    Initialize the Chat Client

                    public/js/twiliochat.js

                    Now that we've instantiated our Chat Client, lets see how we can get a list of channels.

                    Get the Channel List

                    Get the Channel List

                    After initializing the client we can use its getPublicChannelDescriptors method to retrieve all visible channels. The method returns a promise which we use to show the list of channels retrieved on the UI.

                          
                          
                          
                          public/js/twiliochat.js

                          Get the Channel List

                          public/js/twiliochat.js

                          Next, we need a default channel.

                          Join the General Channel

                          Join the General Channel

                          This application will try to join a channel called "General Channel" when it starts. If the channel doesn't exist, we'll create one with that name. The scope of this example application will show you how to work only with public channels, but the Programmable Chat client allows you to create private channels and handle invitations.

                          Notice we set a unique name for the general channel as we don't want to create a new general channel every time we start the application.

                                
                                
                                
                                public/js/twiliochat.js

                                Join the General Channel

                                public/js/twiliochat.js

                                Now let's listen for some channel events.

                                Listen to Channel Events

                                Listen to Channel Events

                                Next we listen for channel events. In our case, we're setting listeners to the following events:

                                • messageAdded: When another member sends a message to the channel you are connected to.
                                • typingStarted: When another member is typing a message on the channel that you are connected to.
                                • typingEnded: When another member stops typing a message on the channel that you are connected to.
                                • memberJoined: When another member joins the channel that you are connected to.
                                • memberLeft: When another member leaves the channel that you are connected to.

                                We register a different function to handle each particular event.

                                      
                                      
                                      
                                      public/js/twiliochat.js

                                      Listen to Channel Events

                                      public/js/twiliochat.js

                                      The client emits events as well. Let's see how we can listen to those events as well.

                                      Listen to Client Events

                                      Listen to Client Events

                                      Just like with channels, we can register handlers for events on the Client:

                                      • channelAdded: When a channel becomes visible to the Client.
                                      • channelRemoved: When a channel is no longer visible to the Client.
                                      • tokenExpired: When the supplied token expires.

                                      For a complete list of client events

                                            
                                            
                                            
                                            public/js/twiliochat.js

                                            Listen to Client Events

                                            public/js/twiliochat.js

                                            We've actually got a real chat app going here, but let's make it more interesting with multiple channels.

                                            Create a Channel

                                            Create a Channel

                                            When a user clicks on the "+ Channel" link we'll show an input text field where it's possible to type the name of the new channel. Creating a channel is as simple as calling createChannel with an object that has the friendlyName key. You can create a channel with more options listed on the Channels section of the Programmable Chat documentation.

                                                  
                                                  
                                                  
                                                  public/js/twiliochat.js

                                                  Create a Channel

                                                  public/js/twiliochat.js

                                                  Next, we will see how we can switch between channels.

                                                  Join Other Channels

                                                  Join Other Channels

                                                  When you tap on the name of a channel from the sidebar, that channel is set as the selectedChannel. The selectChannel method takes care of joining to the selected channel and setting up the selectedChannel.

                                                        
                                                        
                                                        
                                                        public/js/twiliochat.js

                                                        Join Other Channels

                                                        public/js/twiliochat.js

                                                        At some point your users will want to delete a channel. Let's have a look at how that can be done.

                                                        Delete a Channel

                                                        Delete a Channel

                                                        Deleting a channel is easier than creating one. The application lets the user delete the channel they are currently on through the "delete current channel" link. The only thing you need to do to actually delete the channel from Twilio, is call the delete method on the channel you are trying to delete. Like other methods on the Channel object, it'll return a promise where you can set the success handler.

                                                              
                                                              
                                                              
                                                              public/js/twiliochat.js

                                                              Delete a Channel

                                                              public/js/twiliochat.js

                                                              That's it! We've just implemented a simple chat application for Node.js using Express.

                                                              Where to Next?

                                                              Where to Next?

                                                              If you are a Node developer working with Twilio, you might want to check out these other tutorials:

                                                              Click-To-Call

                                                              Put a button on your web page that connects visitors to live support or sales people via telephone.

                                                              Automated Survey

                                                              Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

                                                              Did this help?

                                                              Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think.

                                                              Jose Oliveros Jeff Linwood David Prothero Kat King Mica Swyers Andrei Birjukov Andrew Baker Jason Sooter Andres Jaan Tack Jeffrey Linwood
                                                              Rate this page:

                                                              Need some help?

                                                              We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Community Forums or browsing the Twilio tag on Stack Overflow.

                                                                    
                                                                    
                                                                    

                                                                    Thank you for your feedback!

                                                                    We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

                                                                    Sending your feedback...
                                                                    🎉 Thank you for your feedback!
                                                                    Something went wrong. Please try again.

                                                                    Thanks for your feedback!

                                                                    Refer us and get $10 in 3 simple steps!

                                                                    Step 1

                                                                    Get link

                                                                    Get a free personal referral link here

                                                                    Step 2

                                                                    Give $10

                                                                    Your user signs up and upgrade using link

                                                                    Step 3

                                                                    Get $10

                                                                    1,250 free SMSes
                                                                    OR 1,000 free voice mins
                                                                    OR 12,000 chats
                                                                    OR more