TUTORIALS

How to Build a Chat App with Firebase

Njoku Samson Ebere

View GitHub Repo

Introduction

I know you’ve heard of databases like Firestore, Postgres, and MongoDB and chat applications like WhatsApp. But have you thought about how difficult it is to build a chat application, showing you messages as soon as they are sent? In this tutorial we will do just that. I will guide you through how to build a web based chat application using Firebase as a realtime database. 

Note: If you're looking for a chat application and don’t want to build your own, 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 into your website & apps, quickly and securely; saving you countless hours & resources, and dramatically growing engagement on your website. Give us a try for free today!

Sample of What We are going to be building


Prerequisite

To be able to follow this tutorial, you will need a basic understanding of HTML, CSS and JavaScript

What is 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 so on.

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

Setting Up a Firebase Realtime Database

Firebase offers two types of databases (Cloud Firestore and Realtime Database). For the purpose of this tutorial, we will be using the Realtime Database.

Sign Into Firebase

  • You will need to have a Gmail account. 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 successfully signing 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 can 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

  • In the sidebar on the left, click on 'Realtime Database'
click on <code>Realtime Database</code>
  • Then, click the 'Create Database' button
click the <code>create database</code> button
  • Select your preferred location and click Next
Select your preferred location
  • Choose to use the database in 'Test Mode', click on the Enable button and wait for the process to complete.
start test mode

This will create an empty database which we can use for our app.

Alright, let's take a break from Firebase and start building our application.

Project Setup

Our project will consist of 3 files. Go ahead and create a folder with the 3 files named:

  • Index.html
  • Index.css
  • Index.js

That's 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 and links to the other 2 files. It will also include links to the Firebase API. This is where we lay the foundation of our project. Let's begin:

  • Add the following code to start the app

Notice that we have included two script tags in the body. These link to the Firebase API and make it available to our application. The index.css file is also included in the <head> and the index.js file is sourced below the Firebase API scripts.

  • Next, Add the following content to the <body> above the script elements

In the HTML above, we created a <header> with the name of our app. Below the header is the chat body. The <div> element below will contain the bulk of our app. There is a <ul> element, in which all messages from our database will be listed, and a <form> that will be used to send messages by members. That's all for our index.html file.

Below is what my app looks like at the moment:

Page with only HTML

Building the Functionality

You now need to open the index.js file. This is where we will build out the functionality of our application step by step.

First, we need to tell our application about the Realtime Database we just created and initialize Firebase at the top of our file.

Getting Our Realtime Database Configurations

Before you can use Firebase in your app, you will need to register it through the Firebase console to get your API keys.

  • Back in the Firebase console, 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. 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 show your configuration values, like so:

Firebase Configurations

You should keep this information secret so that other people can’t use your project.

  • Finally, copy the Firebase configuration and initialization code

App Initialization

In your index.js file, paste the code you just copied at top of the file

Be sure to replace the details with your own details, then initalize the database by adding the following line:

const db = firebase.database();

Next, add the line:

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

Sending Messages

To send messages, users will type into the input form we provided and click on the send button. Our app will subscribe to the submit event when the send button is clicked 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 we:

  • Prevent the default form behaviour
  • capture and store the message sent by the user
  • clear the input box
  • scroll to the bottom of the page where the new message will appear
  • add the message to the database.

Receiving Text Messages

When a message is sent by one user it should be received by all the other users of the application. To make this possible, we add the following to index.js:

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

In the code above, we subscribe to the database's child_added event to be notified when new messages are sent. Then, we append the messages to the list we created earlier. Our app is now fully functional. See mine below:

Chat App Demo Without 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:

We now have a beautifully styled chat app! See mine below:

Final Demo After being styled with CSS

Congratulations you have now built a realtime chat app. 

If you're looking for a 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

We navigated through creating a realtime chat application with Firebase. We laid the foundation of our application with HTML, gave it functionality with JavaScript and beautified it with CSS. 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!