How to Build a JavaScript Chat App

This step-by-step tutorial will guide you on how to build a JavaScript chat app using CometChat's chat widget and Firebase.

Hiep Le • Sep 23, 2021

App and web development have come a long way in the last few years. We use a lot of chat applications every day, including Facebook Messenger, WhatsApp, and Snapchat. Using the CometChat Widget and Firebase backend services you will learn how to make a chat app with JavaScript with minimal effort.

What You Will Build

In this tutorial your learn how to build an application which:

  • allow end-users to signup, creating new accounts in CometChat

  • enables users to login in and have a short profile (Name, UID, Photo, About)

  • authenticate users with CometChat and Firebase

You will also use the CometChat Chat Widget and configure it such that:

  • a list of Users/Contacts is visible to all users with the search bar

  • all users can text chat and share images, audio, video, document,

  • all users can initiate voice & video call each other and groups

  • users can create/exit groups and add/remove other users

  • group chat via text, voice, and video chat is enabled for all users

What You Will Need

To follow this tutorial, you need to have a basic understanding of HTML, CSS, and JavaScript. You will also need:

Project Setup

To setup your project Create a folder named javascript-chat-app and ddd the following files and folders

  • css: will contain all styling for your JavaScript chat application

  • img: stores images used by the application such as the logo and background

  • js: contains the applications JavaScript code and business logic

  • screenshots: this folder contains images used in the README.md file

  • favicon.ico: the favicon.ico for the application.

  • index.html: will be displayed when users visit the application

  • login.html: will be displayed when users login to the application

  • .gitignore: contains files to be excluded from git. You need to include the config.js file because it will contain the secret keys for your application

  • README.md: describes the application and provides instructions for how to run the application.

You will create the contents of the required files and folders as you follow the tutorial.

You need to create a styles.css file inside the css folder in your project to store the applications stylesheet. The styles.css file on GitHub contains all the styles for the application.

The img folder on GitHub contains all the image assets required by the application. You should download them and add them to the img folder inside your project.

Installing JavaScript Dependencies

In order to use the application in a web browser you need to setup a simple HTTP server to serve the HTML, CSS and JavaScript files. For this you will use http-server.

Run the command npm install -g http-server install http-server from npm.

Once the module is installed you can start the server by navigating to your projects root folder and running http-server

Setting up CometChat

You will need to create a new App:

Provide a name for your app and select the region you want to use.

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c1485b6ab78a2b3a007d8_AXuV4pmOc0Kzi62uk9L1tMFzK4f7W05r2gd9WWB810makuI5ohhQqdB0gjGmhqh4dgZbQozxAOVgMHw4oP6H4zKi2X6NEDzOT3T3ltOMadhR8XWocAbEvvgaEq6iNzB1mtenggLEBassv5RJmJs9TfZt57VEuSPCd1YIxK8CQDoh0P_4YIv3Ej8AjZyZ5A.png

Creating a new App in the CometChat dashboard

Remove Existing Users and Groups

CometChat will automatically create some Users and Groups to use with your application. You can safely remove these as you will be creating new users that will be shared between your application and CometChat.

Creating a CometChat Chat Widget

CometChat provides tools to help you create and design your chat app window which can then easily be embedded into your application as a widget.

To create a new Chat Widget with CometChat follow the steps below:

  • Select ‘Chat Widget’s from the menu on the left

  • Click on ‘New Chat Widget’

This will create a new widget for you which you can customize in order to change the design or add and remove different features

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c148569455b68a98ad8d0_ucBoctXTB-ONbqeCV3vothqsEpxRAnfnPUUQFjTC3V7Uyfd2msCQ2yUru9jrqsrdU07IJ4ehKJ0N0E9C2Mdf0uBUdlkDJ-Sr8XWgVUoC3bPZbogCnpHgrueTCWYETgf-1z_3Jhkqi0hhrvZD_qG6rfO32uMRrg-67HpZ8DeBF_JfQ5vWsZU2q6PW97984g.png

Modifying a Chat Widget in the CometChat dashboard

You can find more information about the Chat Widgets and different options in the docs. However we’ve done our best to make the features easily discoverable and as you will see the powerful widget means there's no need to build everything from scratch.

Find Your App’s Credentials

Once your App has been created you can find your APP ID and Auth Key on the ‘Quick Start’ page.

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c14859966fc6f5887dc67_5cRb7ohfcXhqRYQvu1eBiJ9iHGpAHz49iaenhyCH5IjcilHRDt4UfFcpZQaoTMdvil7EQRSZLnYicX6qPaF0-aLWDXUNFP-2D3Z0aA1xT_2M3R0t2jzO3X4jU_AEjBEwnXXVTvl4UADO4l_MaeClTZH8AkEmXxT4RUxYtmvx7ga2cHEjABH0FEAzlgk-fg.png

While the WIDGET ID and REST API KEY can be found on your widgets page

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c14864756ede0ab99e1dd_pO5QvNm3d0Tcyioe4WK_zHF4MEst5dIr2dnRGnmY9vEH2Oj8UeQc_Kv3QOmbODtO9UhpGlNRr27og24HytiClh3exwZzCQcScEdfQPQ5fviY7Z_AbAwUoFw-j2U61f4WObFjkfFQmKqe_GNKu-YM1Fl3jOB0sjrYFIlouNijWEl97xae93v-Yo8G3du8Ug.png

Configuring CometChat in Your Application

In this tutorial, we will be using the CometChat Widget. When users log in to our application, they do not just log in to our application, they also log in to the CometChat platform.

In order to use the CometChat widget or SDK in your application you need to provide the credentials needed to communicate with the CometChat platform.

In the js folder your created earlier add a new file config.js to store your account credentials with the content below:

Be sure to replace the example values with the values from your CometChat account.

Setting Up Firebase

Firebase is a back-end platform provided by Google for building full-stack applications. It provides programmers with authentication options, storage, databases, hosting, A/B testing and other services.

Firebase helps you to focus on developing the front-end of your applications while it does the hidden jobs for you.

You will need to create a new Firebase project:

Create a Realtime Database

Firebase offers two types of databases (Cloud Firestore and Realtime Database). For the his tutorial, you will be using a Realtime Database.

In the sidebar on the left

  • Open the ‘Build’ menu

  • Click on 'Realtime Database' and then ‘Create Database’

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636adaa6da8a9f9e9afd39eb_tCA7fjSbHZQYUH3mSJOYlSwbGRg6LjXZ9rLEWSd7tgwlCMfYjnXzPCJN0l1JAg3VYgk7gqFaeFGn3A5VudtfAOBUd0m1kZmo8rlpGWlom7PA4dFfAHepe4R3RJwn98eeEcU26efR2t9UgAi66S2TFu1pQhg3vN_A6sJnF5eFMVxZiKc7hecp8HazKtxQfQ.png

After that, select the region you want to use

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636adaa6987188de88058605_7xGtFfBUmBTNQs9vhkgZg_u_U_4xU281EQQ6ip30avPnTFeUGxL44h1wT1LO0w-BTI8r5ZP6VOqIylvYL4cvzKLIi77NpSvsyxJ4P1QuR-4-ZHcqMlxWI01dCn0VkcI8DQkv-GdAOw6HDI27bvuxh3ix1H5YS3gnSOLDufsOdhBP90U_uyKIx-5npO5ZVw.png

Finally, start the database in Test mode

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636adaa61d6abbcef6aabec0_xmmkdBhpsO9FKWApYf-mXOYeEw4j0fpCsXaScj1dj4zeMIItR0PQFllmuT1ChTbubT4FccIqMtQ7PHKJJtH8HvzJpTHLAYp8Wy3BuF-npKY3_1JtqFUeKGqz52GZP95v2llCKkHEaRyBC8ZD4ANE1TiN-ouPJb31D_MhhR-YhL3lxYnhCd9oBY086xw7qQ.png

Add an Authentication Service

We will be using Firebase’s Authentication Service to manage users accounts. The service will be configured so that users need to provide a username (email address) and password in order to use the application.

In the sidebar on the left

  • Open the ‘Build’ menu

  • Click on 'Authentication' and then ‘Get Started’

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c17d31a56a574f1cabcb1_pjWrd8KsdLmjsWdpe34bh3-NRzkgF7sfvx_ebaj2DlPLLz02nuhhPYKm8kf8p2-ottNqxJ4RljydKV_ZFggNz1jO1yoDQk_9kDNaI_TaNlWEmgpUsMoz94sy7aHHLVL-PL4J-VbBcTj-zvr5dwZBM77xJ5js_SQYb1oi-xyA8Q5Qm1XfY23ePyKqI0sClg.png

Then select ‘Email/Password’ from the ‘Native providers’ list as your authentication method.

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c17d261d7b158ef9b5268_hhH69-V2MW5Y_WGHt1_xm886ofCL1szlvZZVL80DPvyT0xmdy6MBL5UkGRuAASo9h3Tyq4b0OdImO9j-qrdy31dr3nc7i3NzKq56ljagU04lWSk8hRDx-8ZHpePEV02n6UUo1e55CfjERqWuEzFZ4zPBtXBEEaSOg_QjCRsUFSsrz6TEKx6WGUHaJfZJ2Q.png

Finally, enable the ‘Email/Password’ option and click ‘Save’.

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c17d2c1d5c03076a82733_42teUtNFhJaDK1eZgyXBNt8dRgcMTdMU51ca0cXS-KU3XAD2cYK7WdBsUybJ0KbBx8Zf9oDkVtj4avpVWnezKLpT6Yc5CoejQxFgUV0qFcLRxxZUzwDs0QkWfrDRn1GMDN_t_3heUT-4mDl1RAwuKSFM6GOSe0VTX1GxrRNeBwBYUQhEngcoljeWXvLupw.png

Get Your Configuration Details

Once your database is set up, the only thing left to do is to get your configuration details. You will use these in order to authenticate your application with the Firebase service.

You can find your configuration details in the Firebase console:

  • Click the Gear icon next to Project Overview

  • Choose Project Settings

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636adaa69b117042a35d24c7_zyjcO_cQiDHSrkh8M9f7HOPXQt0H1CdEmq3gkEgDG6WKkgWAme19WOtty3H8b38KYdFadWVvH7ATmKUJrtjQCYDxFQ3uUfWQI4TID94h0B2V4zBt5cG3aYILz5X4jP8xLRPnI4uZ821un27xCQPsNLp1devJc21HZSMv6UJ-dIcRTmIK98OWNjeWOd9acg.png

Under ‘Your apps’, select a ‘Web app’:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636adaa63981e2823077c0e5_9w2RPnby1MEWrTn2aIBrx3SD7dlsU5VfBNzMsWhkNI6IDYZQKOlc_4ZO_vpYpxC6yhmQCdZDMaAG2hhtTfYHRtPYDoOwFSstoMEZ0c5qJT4gV5zf_w_jGnRswCNRHxHRCCq2DHMo_QiygLq5e0lX2oZ4CR9FZsFzmZuoAfAVJSSVR6y49npZn6t3aTQejA.png

Next you need to register your application

  • Enter a name for your application e.g. javascript-chat-app

  • Click on ‘Register App’

You can ignore the next screen and click on ‘Continue to Console’

Your application’s config values will then be visible in the ‘Your apps’ section

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636adaa673415e55d94be4b6_ez224roBRt78GRdpy7YgvaEuke3K5mNwg1aOZc0BA5k8eMAF-fxOOqYk2ipKfB75x8u48d3JmLthKi2UpcmjX2Toc6QkKWZ7bSGtJplMg8Tuk5SlC02Tpnf2v5XE8htI6oZSxvkzF7ENSzNVJO6F8bAUREPPHJoOUwtTW6ieqtdETA_f5TmXFByTYiGS2Q.png

You will need to add these values to the config.js file you created earlier.

Initializing Firebase in Your Application

The firebase.js file will be responsible for interfacing with Firebase's Realtime Database service and  initialize the email/password authentication service provider enabling users to sign in with their email/password. The projects secret keys will be retrieved from the config.js file.

Inside your js folder create a new firebase.js file with the following content:

The Login Page​​

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/636c196aededf685acda7f95_wdhQpR21NzzLd26Nd6OBmHKp455u-o8tYyg956BTQjy7Z1W5O-DftnUBurjsteRqHz9HuLJCyC8eagDVcudQUQGR1vcIW9Oy7pOyGtZYYMCRTo3UisRsNKtpKLwFVvL30eFc68d2GZFLad2V4iZuRk4Z9vuCl_iK-15MIf7q97FG2E-QC3ov8K6V32g16g.png

The login page is responsible for authenticating users using the Firebase authentication service. It accepts the user credentials and either creates and account for them or logs them in, depending on if they are a new user or not.

Add the following HTML to the login.html file in your project:

In the HTML above you have  included some third-party libraries:

  • CometChat Widget: helps integrate the CometChat Widget

  • UUID: The UUID library is used to generate a unique ID for each account

  • Validator: used to validate the login form

  • Firebase: helps us to interact with Firebase and use Firebase services including Firebase Authentication, and Firebase Realtime Database

As well as using third-party libraries, you need to create some files to handle the logic for your application: auth.js, config.js, firebase.js, util.js, login.js. You have already created config.js and firebase.js, however you will now need to add the other files.

The auth.js File

The application needs to provide a way for users to login in and have a short profile. Once  the user has logged in to the application, the user cannot go back to the login page but if the user has not signed in to the application, the user cannot go to the home page. auth.js will be used to handle this functionality

auth.js will be used on both the login and the home page and will be executed first before any other actions. This file will be responsible for checking if the current user has logged in, or not using the getLoggedinUser() function provided by the CometChat Widget SDK. If the user has not logged in to the application, the user will be redirected to the login page.

In the js folder create a new auth.js file with the following content:

The util.js File

Some functions can be used across multiple pages in the application, such as showing or hiding the loading indicator or getting information for the authenticated user. To avoid duplicating code, you should store all common functions in a single file.

In the js folder create a new util.js file with the following content:

The login.js File

The login.js file is responsible for handling the business logic for the login page. This file contains functions which let the user register a new account or log in to the application. The full source code can be found on GitHub.

In the js folder create a new login.js file and copy the contents of the login.js on GitHub

Reading through the file, after clicking the sign-up button, the registerNewAccount() function will be called. It accepts a JSON object as a parameter containing the user’s information including email address, password, and password confirmation. Before proceeding, the user’s information is validated using the validateNewAccount() function. If the information is valid, the user’s avatar and unique id will be generated. The application then registers a new user account with the Firebase Authentication service as well as CometChat using the CometChatWidget SDK.

In order to log in to the chat application, the user needs to click on the ‘Login’ button. The code snippet below describes how to handle the business logic for the sign-in feature. The user’s credentials will be taken from the input elements first and the application validates that information. If the input information is valid, the application will let the user log in using the Firebase Authentication Service and the CometChatWidget. The authenticated user will then be redirected to the home page.

The Home Page

After the user has logged in to the application, the user will be redirected to the home page which will display the CometChat Widget.

Add the following HTML to the index.html file in your project:

The index.js File

This file is responsible for showing a greeting to the user, handling the logic when clicking on the “Logout” button, and launching the CometChat Widget.

The most important part of the above code snippet is how to launch the CometChat Widget. According to the CometChat Widget documentation, you need to initialize the CometChat Widget first, if initialization is completed successfully, the code for launching the CometChat Widget will be executed. Aside from that, all configurations will be taken from the ‘config.js’ file.

Clicking the “Logout” button, will call the “logout” function provided by the CometChat SDK. If the function is executed successfully, you need to redirect the user to the login page.

Conclusion

You have now built your fist chat application using a CometChat Widget and Firebase.  You have seen how to integrate most of the CometChat functionalities such as texting and real-time messaging.

I hope you enjoyed this tutorial and that you were able to successfully build the JavaScript chat app. It's time to get busy and build other related applications with the skills you have gotten from this tutorial. You can start building your chat app for free by signing up to the CometChat dashboard.

About the Author

Hiep Le is a software engineer. He takes a huge interest in building software products and is a full-time software engineer. Most of his work is focused on one thing - to help people learn

Hiep Le

CometChat

Hiep Le is a software engineer. He takes a huge interest in building software products and is a full-time software engineer. Most of his work is focused on one thing - to help people learn.

Try out CometChat in action

Experience CometChat's messaging with this interactive demo built with CometChat's UI kits and SDKs.