DEV Community

Cover image for How to Build a Javascript Chat App
Hiep Le for CometChat

Posted on • Originally published at cometchat.com

 

How to Build a Javascript Chat App

What you’ll be building, Git Repo Here.

Featured Articles

If you would like to see more tutorials like this, you can check my profile 😊

Introduction

App and web development have come a long way over the last few years. We use a lot of chat applications every day, including Facebook Messenger, WhatsApp, Snapchat, and so on. One of the most widely used features is live chat. Using the CometChat Widget, Firebase backend services you will learn how to make a chat app with Javascript with minimal effort.

Follow along the steps to build a Javascript chat app that will provide:

  • A way for end-users to signup (email & password is sufficient)
  • A way for users to login in and have a short profile (Name, UID, Photo, About)
  • Use CometChat Chat Widget and configure it such that:
    • 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 must be enabled for all users
  • Login the logged-in user to CometChat
  • Add API call when a user registers so that the user is created in CometChat

This tutorial will use Javascript, Firebase, and CometChat to build Javascript chat application.

Prerequisites

To follow this tutorial, you must have a degree of understanding of the general use of HTML, CSS, Javascript to build Javascript chat app. This will help you to improve your understanding of this tutorial.

Project Structure

To create a new project, you just need to create a folder which is called “javascript-chat-app”. The image below reveals the project structure of our Javascript chat application. Make sure you see the folder arrangement before proceeding.

Figure 1. Project Structure

Each subfolder and file will be explained in detail in the following section:

  • css: contains all styling for our javascript chat application.
  • img: contains images for the application such as logo, background, and so on.
  • js: contains Javascript code and our business logic.
  • favicon.ico: it is favicon.ico for the application.
  • index.html: root HTML file. HTML file for the home page.
  • login.html: HTML file for the login page.
  • .gitignore: this file contains files that will be ignored when committing the code. In this case, we do not want to commit the “config.js” file because it contains the secret keys of the Javascript chat application.
  • screenshots: this folder contains images that are used for README.md file.
  • README.md: describes the application and provides steps by steps to run the application.

Installing the Javascript Chat App Dependencies

  • Step 1: you need to have Node.js installed on your machine

  • Step 2: The application is using HTML, CSS, Javascript. For this reason, you need to have a simple HTTP server to serve our application. In this case, you will use http-server, you can install the http-server by running the following statement. After installing the http-server package, you just need to “cd” to your project’s directory and run “http-server .”

npm install -g http-server
Enter fullscreen mode Exit fullscreen mode

Configuring CometChat

  1. Head to CometChat and create an account.
  2. From the dashboard, add a new app called "chat-widget".
  3. Select this newly added app from the list.
  4. From the Quick Start copy the APP_ID, REGION, and AUTH_KEY, which will be used later.
  5. Also, copy the REST_API_KEY from the API & Auth Keys tab.
  6. Navigate to the Users tab, and delete all the default users and groups leaving it clean (very important).
  7. Create a file called “config.js” in the ”js” folder of your project.
  8. Import and inject your secret keys in the “config.js” file containing your CometChat and Firebase in this manner.
const config = {
    apiKey: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    authDomain: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    databaseURL: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    projectId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    storageBucket: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    messagingSenderId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    appId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    measurementId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatAppId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatRegion: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatAuthKey: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatAPIKey: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatWidgetId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx
};
Enter fullscreen mode Exit fullscreen mode

Make sure to include this file in your gitignore file from being exposed online.

Setting Up Firebase Project

According to the requirements of the Javascript chat application, you need to let users create a new account and login to the application, Firebase will be used to achieve that. Head to Firebase to create a new project and activate the email and password authentication service. This is how you do it:
To begin using Firebase, you’ll need a Gmail account. Head over to Firebase and create a new project.

Figure 2. Firebase

Firebase provides support for authentication using different providers. For example, Social Auth, phone numbers, as well as the standard email and password method. Since you will be using the email and password authentication method in this tutorial, you need to enable this method for the project you created in Firebase, as it is by default disabled.
Under the authentication tab for your project, click the sign-in method and you should see a list of providers currently supported by Firebase.

Figure 3.  Firebase Authentication.

Next, click the edit icon on the email/password provider and enable it.

Figure 4. Enable Firebase Authentication with Email and Password.

Now, you need to go and register your application under your Firebase project. On the project’s overview page, select the add app option and pick web as the platform.

Figure 5. Firebase Dashboard.

Once you’re done registering the application, you’ll be presented with a screen containing your application credentials.

Figure 6. Firebase credentials.

Please update your created “config.js” file with the above corresponding information. If you do not see the information for the “databaseUrl” field in the config.js file. Please do not worry we will discuss it in the “Configuring the Firebase” section.

Congratulations, now that you're done with the installations, let's do some configurations.

Configuring Styling for the Application

Inside our Javascript chat app project structure, you need to create a styles.css file inside the “css” folder and paste the codes here. styles.css file will contain all CSS of the application.

Setting Up Images for the Application

To store images for the application such as the logo and other images, you need to create the “img” folder inside your “javascript-chat-app” folder. Following that, if you can refer to this link to get the images that will be used in this tutorial.

Configuring the Firebase

You need to create a “firebase.js” file inside the “js” folder and you need to enable Firebase realtime database by following the below steps.

Figure 7. Choose “Realtime Database” option.

Figure 8. Click on “Create Database".

Figure 9. Select location where you realtime database will be stored.

Figure 10. Select “Start in test mode” for the learning purpose.

Please follow the guidance from Firebase. After following all steps, you will see the database URL. If you just need to update the “databaseUrl” field in your “config.js” file with that value.

Figure 11. Database Url.

On the other hand, your Firebase real-time database will be expired in the future. To update the rules you just need to select the “Rules” tab and update the date/time in milliseconds as you can see in the image below.

Figure 12. Update Firebase Realtime Database Rules.

While developing the application, you may see a warning message on the console.

@firebase/database: FIREBASE WARNING: Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "email" at /users to your security rules for better performance.
Enter fullscreen mode Exit fullscreen mode

To resolve the issue, you need to update the rules for your real-time database as follow:

Figure 13. Update database rules for better performance.

For more information about the warning message and how to fix, you can refer to this link.

This “firebase.js” file is responsible for interfacing with Firebase authentication and database services. Also, it makes ready our email/password authentication service provider enabling us to sign in with email/password. Secret keys will be retrieved from the config file. As mentioned above, please do not share your secret keys on GitHub.

The below images demonstrate the data structure of the application. A user should have an avatar, an email, an id.

Figure 14. Data Structure - User.

The Login Page

This page is responsible for authenticating users using the Firebase authentication service. It accepts the user credentials and either signs him up or in, depending on if he is new to our application. To create the login page for the Javascript chat application, you need to follow the below steps:

  • Step 1: Create login.html in the source folder. The source code can be found from here.

You need to include some third-party libraries such as CometChat Widget, Uuid, Validator, Firebase via CDN because you are building the Javascript chat app. Therefore, npm should not be used here. You need to add those libraries for some reasons:

  • CometChat Widget: help us to integrate CometChat Widget to the Javascript chat app. On the other hand, you need to use some other functionalities from CometChat such as registering a new user, letting the user log in to CometChat, or letting the user log out from CometChat.
  • UUID: each created user should have a unique id. Hence, the UUID library is used to generate a unique key for each account.
  • Validator: it is used to validate the login/sign-up form. Because you need to ensure that the input information is valid before creating a new account or letting a user log in to the chat application.
  • Firebase: it helps us to interact with Firebase and use Firebase services such as Firebase Authentication, Firebase Realtime Database, and so on.

Besides using third-party libraries, you need to build some files to handle the logic for the Javascript chat app such as auth.js, config.js, firebase.js, util.js, login.js. Config.js and firebase.js were mentioned in the above sections. We will discuss auth.js, util.js, and login.js in the following parts.

The Auth.js File

According to the requirements of the Javascript chat application, the application needs to provide a way for users to login in and have a short profile. After the user has logged in to the application, the user cannot go back to the login page. On the other hand, if the user has not signed in to the application, the user cannot go to the home page. We need to define a solution to handle this case. Therefore, auth.js will be created to help us achieve that. The full source code can be found from here.

The CometChat Widget provides the “getLoggedinUser” function to get the logged-in user. Auth.js will be used on both the login page and the home page. It means that this file will be executed first before other actions. This file will take responsibility for checking the current user has logged in, or not. If the user has not logged in to the application, the user would be redirected to the login page. Otherwise, if the current user has logged in to the Javascript chat app, the user cannot go back to the login page.

The Util.js File

Some functionalities can be used across pages of the Javascript chat app such as showing or hiding the loading indicator or get the information of the authenticated user. To avoid duplicated code, you should store all common functionalities in a single file, and in this case, this file is called “util.js”. The full source code can found here.

The Login.js File

The file will take responsibility for handling the business logic for the login page. This file contains functions which can let the user register a new account or log in to the application. The full source code can be found from here.
After clicking the sign-up button, the “registerNewAccount” function will be triggered. It accepts a JSON object as a parameter and the JSON object contains the user’s information including the user’s email, user’s password, and user’s password confirmation. Before proceeding with further actions, the user’s information needs to be validated by using the “validateNewAccount” function. If the information is valid, the user’s avatar and user’s id will be generated. As mentioned before, each user should have a unique id. After that, the application will register a new account by using the Firebase Authentication service and then register an account on CometChat by using the “CometChatWidget”. You can refer to the below code snippet for more information.

To log in to the Javascript chat application, the user needs to click on the “Login” button. The below code snippet 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 sign in by using the Firebase Authentication Service and the “CometChatWidget”. Aside from that, the authenticated user will be redirected to the home page.

How to Create Chat Widget on CometChat.

As mentioned above, you will learn how to make a chat app with Javascript with minimal effort. You can achieve that because we have strong support from CometChat. Thanks to the CometChat team. They are providing great services. To create a chat widget on CometChat you need to follow the below steps:

  • Step 1: Go to the CometChat dashboard by using your created account and then go to your created app. Hopefully, you had one after finishing the “Configuring CometChat” section.

Figure 15. CometChat Dashboard - Chat Widget Application - Javascript Chat Application.

  • Step 2: You need to choose the “Chat Widget” option on the left sidebar. You will be redirected to the page in which you can create a new chat widget.

Figure 16. CometChat Dashboard - Chat Widget Application - Javascript Chat Application - Choose the “Chat Widget” option.

  • Step 3: On the current page, you need to choose the “New Chat Widget” option, CometChat system will create a new chat widget for you and redirect you to the created chat widget.

Figure 17. CometChat Dashboard - Chat Widget Application - Javascript Chat Application - Choose the “New Chat Widget” option.

  • Step 4: You need to update your config.js with the following keys.

Figure 18. CometChat Dashboard - Chat Widget Application - Javascript Chat Application - Chat Widget Credentials option.

const config = {
    ...
    CometChatAppId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatRegion: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatAuthKey: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatAPIKey: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx,
    CometChatWidgetId: xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx
    ...
};
Enter fullscreen mode Exit fullscreen mode

The CometChat dashboard provides a great way to help us configure all features for the Javascript chat application with minimum effort. You just need to select the section that you want to customize and toggle those features by clicking on the “toggle” button. Aside from that, you can customize by adding your Javascript code and your CSS. The following images help you understand clearly what we are talking about.

Figure 19. CometChat Dashboard - Chat Widget Application - Javascript Chat Application - Customize your Javascript code and your CSS.

Figure 20. CometChat Dashboard - Chat Widget Application - Javascript Chat Application - Customize sections

The Home Page

After the user has logged in to the application, the user will be redirected to the home page and on this page, you will integrate CometChat Widget to build the Javascript chat application. We have set up, created a new chat widget, and update the secret keys in the “config.js” file. It is time to integrate the created chat widget into the home page. To create the home page, you need to follow the below steps:

  • Step 1: Create index.html file in your project folder. The full source code can be found here.

As you can see on the code snippet above, you need to include the “CometChat Widget” from the CDN because we want to build the Javascript chat app by using Javascript and CometChat Widget. You also need to include some common files, which were mentioned in the above sections, such as auth.js, config.js, util.js. The index.js file will be discussed in the following part.

The Index.js File

This file will take responsibility for showing greeting to the authenticated user on the header, handling the logic when clicking on the “Logout” button, and launching the CometChat Widget.
The full source code can be found from here.

The most important of the above code snippet is how to launch the CometChat Widget. Therefore, we can set up full features for the Javascript chat application. According to the CometChat Widget documentation, you need to initialize the CometChat Widget first, if initialization is completed successfully, the code of launching the CometChat Widget will be executed. Aside from that, all configurations will be taken from the “config.js” file. You can refer to the below code snippet for more information.

After clicking the “Logout” button, we should call the “logout” function which is provided by the CometChat team. If the function is executed successfully, we need to redirect the user to the login page. You can refer to the below code snippet.

Conclusion

In conclusion, we have done an amazing job in developing a Javascript chat application by leveraging Javascript, Firebase, and CometChat. You’ve been introduced to the chemistry behind the Javascript chat application and how the CometChat Widget makes chat applications buildable.
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 here.

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.

Top comments (2)

Collapse
 
obaino82 profile image
Obaino82

Well done Boss

Collapse
 
lukeshiru profile image
Luke Shiru

Maybe a better fitting title would be "How to Build a Chat app using CometChat", and ideally if the post is sponsored, that should be clarified at the start.

Cheers!