TUTORIALS

How to Build a Chat App with Firebase

Njoku Samson Ebere

View GitHub Repo

Introduction

I know you have heard of Databases like Firestore, Postgres and MongoDB. I also know you have heard of Chat Applications like WhatsApp. But have you thought of the difficulty to build a chat application showing you messages as soon as they are sent?

Well, there is good news! You don't have to stress so much to create a chat application. In this tutorial, I will guide you on how to build a web based chat application using Firebase Realtime Database. The finished application will look like this:

Note: If you're open to an alternative, consider CometChat. Our robust suite of cloud-hosted text, voice & video solutions, ranging from simple drag-and-drop plugins to UI Kits, APIs and fully customizable SDKs, plus a host of unique ready-to-use extensions, will seamlessly integrate onto your website & apps quickly & securely, saving you countless hours & resources, dramatically growing engagement on your website. Give us a try for free today!

Sample of What We are going to be building

Let's begin by talking a bit about Firebase.

What is Firebase?

Firebase is a back-end platform provided by google to enable developers to build full-stack applications. It provides programmers with authentication options, Storage, databases, hosting, A/B testing and so on.

In a nutshell, Firebase helps us focus on the front-end of our applications while it does the hidden jobs for us.

Installation

Firebase can be installed in 2 ways on the web:

  • First, using the node package manager (npm) by installing it through the terminal in our project folder.

npm i firebase

  • Secondly, using the content delivery network (CDN) by adding it to our project.

<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-database.js"></script>

Setting Up a Firebase Realtime Database

Firebase offers us 2 types of databases (Cloud Firestore and the Realtime Database). For the purpose of this tutorial, we will be using the Realtime Database. After all, we are building a Realtime Chat Application. So let me walk you through creating your own Realtime Database step by step.

Sign Into Firebase

  • First, you will need to have a Gmail account. Remember we said google gave us Firebase? So create one here if you do not already have an account.
  • Now that you have your Gmail handy, navigate to https://firebase.google.com/
firebase landing page
  • Sign in through the sign in button at the top right corner on the page
sign in button
  • After a successful sign in, click on Go to Console at the top-right corner of the page
Go to Console button

You should be redirected to your dashboard where you are asked to add a project

Create a project

  • Click on the add project button
add a project
  • Give your Project a Name and Click on continue
Give your Project a Name
  • Disable Google Analytics. We will not be needing it.
Disable Google Analytics
  • Click on Create Project and wait till it's done. Then click on Continue
wait till it's done

You will be redirected to you new project's dashboard like this:

project dashboard

Create a Realtime Database

  • On the sidebar by the left, click on Realtime Database
click on <code>Realtime Database</code>
  • In the page that shows up, click the create database button
click the <code>create database</code> button
  • Select your preferred location and click next. United States is a good location to use
Select your preferred location
  • Next, choose to use the database in test mode and click on the Enable button and wait for the process to complete.
start test mode

This will create an empty database that we will use in a minute. See mine below:

Wow!!! That was a big win. You just created a Firebase Realtime Database.

Alright, let's take a break from Firebase and start building our application. We will be back to our Realtime Database shortly. Stick with me...

Prerequisite

For you to be able to follow through with this tutorial, it will be nice if you already have basic understanding of HTML, CSS and JavaScript

Project Setup

Our project will not be bulky. We will have 3 files in a folder. So go ahead and create a folder and add 3 files. The 3 files should be named: index.html, index.css and index.js.

That is all for our project setup. This is what my files look like:

Project Files

Laying The Foundation

The index.html file will contain our HTML codes and links to the other 2 files. This is where we lay the foundation of our project. Let's begin:

  • Add the following code to start the app

Notice that the CSS file is included at the head, the Firebase CDN is included in the body and our index.js file is placed below the Firebase CDN

  • Next, Add the following code in the body. This will be above the firebase CDN

In the code above, we gave our chat app a title in the header. Below the title is the chat body. The chat body contains a ul tag in which all messages from our database will be listed and a form that will be used to send messages by members

That will be all for our index.html file. Below is what my app looks like at the moment:

Page with only HTML

Building the Functionality

We will now navigate to the index.js file. Here is where we will build out the functionality of our application step by step. Let's do this!

First we need to tell our application about the Realtime Database we just created and initialize Firebase at the top of our file. I told you we will get back to Firebase in a minute, didn't I?

So let's go get the configurations of our Realtime Database.

Getting Our Realtime Database Configurations

  • Back in our Firebase console or dashboard, click on the gear icon you see at the top of the sidebar.
  • Click on Project Settings from the options that pop up
Click on <code>Project Settings</code>

This opens up the settings page

  • In the General tab, scroll down to the Your Apps section and click on the web icon
In <code>You Apps</code> section, click on the web icon
  • In the page that follows, give your app a nickname and click on Register App

This will now open up your configurations below like so:

Firebase Configurations

You should keep these information secret. Notice how I have taken time to conceal mine.

  • Finally, copy the Firebase configuration and initialization.

App Initialization

  • Back in the index.js file, paste the code you just copied at top of the file like this:

Be sure to replace the details with your own details

  • Next, initialize your database like this:

const db = firebase.database();

Login a User

We will use a prompt to login a user. The user will provide us with a name to identify with. So enter the following code to login a user

const username = prompt("Please Tell Us Your Name");

Send Messages

To send messages, our user will type into the input form we provided and click on the send button. Our Chat App will keep an ear down and listen to when the send button is clicked (in order words, when the form is submitted) and then trigger a function to be executed.

  • Add the following code to listen to the submit event

document.getElementById("message-form").addEventListener("submit", sendMessage);

Notice that it triggers a sendMessage function. Add the following code to send the message to the database

In the code above, the page is prevented from refreshing, the details to be entered into the database is collected, the input box is cleared, the page is scrolled to the bottom where the new message will appear and the message is finally sent to the database.

Receiving Text Messages

Messages sent are received by other users as soon as the messages are sent. To make this possible, we do the following:

  • Make a reference to the collection created earlier like this:

const fetchChat = db.ref("messages/");

  • Listen to the collection to see when there is a new message and then render it on the page. Add the following code at the bottom of you page

In the code above, we are listening to the database with the child_added event to see if there are new messages. Then, we append the messages as a list. With this, our app is now fully functional like a regular chat app. See mine below:

Chat App Demo Without CSS

Well, Not really like a regular chat app. So what is missing? You guessed right! CSS!

Styling The App

To style our app and make it feel like a regular chat app, navigate to the index.css and add the following code:

And we have a beautifully styled chat app! See mine below:

Final Demo After being styled with CSS

We did it! If you're looking to build a more robust application that's built to scale, consider CometChat, which is widely considered to be an easier alternative that have you up and running in 30 minutes or less. Create an account for free here, and start building right away. Develop for as long as you need, and don't pay a thing until you're ready to scale. Really!

Conclusion

It's being a nice ride with you as we navigated through creating a database on Firebase. We laid the foundation of our application with HTML, gave it functionality with JAVASCRIPT and beautified it with CSS. Yes! We have been able to see how we can create a Realtime Chat Application even as a beginner.

We initially pointed out that there are many tools offered by Firebase. Do check them out especially if you are a front-end developer who do not enjoy the back-end job

The source code for our application can be found here

About the Author

Njoku is a software engineer who loves building solutions to real world problems and teaching others about the things he knows. Something he really enjoys doing besides writing code and technical articles is body building.

Related Posts

No items found.
No items found.
No items found.

Try Us for Free 

For as Long as You Like!