How to Build a Chat App With Next.js & Firebase
In this tutorial, we will guide you through building a simple chat application with Next.js and Firebase.
This tutorial will provide you an opportunity to learn how to build a chat application with jQuery and PHP. We will start by downloading a starter application built with PHP and contains enough code and logic to authenticate a user. Afterward, I will walk you through a step by step guide on how to integrate CometChat into this application and make it a functional chat application.
At the close of this tutorial, you would have gathered enough knowledge on how to build a chat application leveraging CometChat infrastructure and can easily integrate with an existing or new project. Take a look at the image below:
Check out the complete code for the project built in this tutorial on the completed branch of this repository on GitHub.
First things first, download or clone the starter repository earlier mentioned by issuing the following command:
git clone https://github.com/yemiwebby/jquery-cometchat-starter.git
The preceding command will download the project into a folder named jquery-cometchat-starter. This project already contains the following files and folders:
Having perused the details of the files within the starter repository, we need to configure and set up a connection to a database. First, create a local database and run the following script from a MySQL terminal to create users table.
Here, we set up a connection with the created database using MySQLi. Replace the YOUR_DB_USERNAME, YOUR_DB_PASSWORD and YOUR_DB_NAME placeholders with yours
Once you are done, open the index.php file for this project within a browser.
Go ahead and click on the Register link to access the registration form and create an account. You will be redirected to the homepage afterward. Now enter your credentials to login and you will be able to view the chat view depicted by the image below:
This is a chat page with dummy data hardcoded into the page. Our main task in this tutorial will be to make this app fully functional by connecting it with CometChat.
Before we proceed, you will need a CometChat account. For that, do the following:
Enter the desired name for your application, select a region, technology, and a use case. Once you are done, click on the Add App button to complete the process.
This will automatically spin up a new application for you on CometChat and take you to the quick start guide. CometChat Quick Start guide does a wonderful job in explaining the steps in detail.
Copy your APP_ID, API_KEY and APP_REGION details. Keep this information safe as it will be required later in this tutorial.
Please be sure to use the value of your REST API Key instead of the Auth Key:
For a better understanding of what we intend to achieve in this tutorial, these are the steps to follow. Once a user is logged in, we will:
To begin, one of the key concepts of CometChat is that it must be initialized within your project using the unique APP_ID obtained from the CometChat dashboard as one of the arguments to the init() method from CometChat JavaScript SDK. But before that, navigate to chat.php file and include the CometChat JavaScript library via CDN:
Don’t forget to replace the placeholders YOUR_APP_ID and YOUR_APP_REST_API_KEY with the appropriate values from your CometChat dashboard. Also, ensure that the scripts above is placed immediately after the JQuery CDN.
With that in place, open js/chatService.js file and replace its content with the following:
Here, we called the init() method from CometChat with the appropriate App ID and Region. Please ensure that you replace the region defined here in .setRegion("US") method, if your app belongs to a different region.
Noticed the retrieveUserDetails() method? It is a function that we will define to retrieve the details of a particular user and make a decision based on the result. Next, copy the following code and paste it immediately after the initializeApp() function:
To ascertain if the user with the username specified during authentication already exists on CometChat, the defined function will be used to get the user. If the user does not exist, a function to programmatically create such user on CometChat will be called, otherwise, we will obtain the authToken from the user object returned from CometChat SDK to automatically log the user in.
In this section, we will define the functions required to create a user on CometChat, add such user to a particular group, generate an authentication token, and finally log the user in on CometChat respectively. For these purposes, update the chatService by including the following code:
From the code snippet above, we defined the following functions:
After a successfully login, add the following code to get the currently logged-in user, show his or her username on the navigation bar and then fetch messages from the group that the participant belongs to:
If there are no messages to be fetched for the group, we will show an empty chat with an input field for the user to enter text and start a chat.
In this section, we will define the appropriate logic to send a message to a group. Update the ChatService with the following code:
Here, we obtained the text typed in by the user and send it to the group in which he or she belonged. With this in place, every other participant will receive this message and be able to respond.
Just like we did earlier, having changed and restructured the initialisation process and enhanced your local application with CometChat, you need to update the ./js/scripts.js file to initialize the application once the DOM is ready and then proceed to listen for onSubmit event on the chat HTML form. To achieve this, replace the content of scripts.js with the following code:
Open the index.php again and refresh the page. Next, open two different browsers and register two different users.
Now log in using the details of the created users and you should see the chat view:
Send a message to start a chat.
In this tutorial, we improved a basic PHP application by implementing a chat feature powered by CometChat with ease. This application can create, add, and generate an authentication token for a new user on CometChat.
Feel free to download the source code for the application built here from the complete branch of this repository on GitHub. You can add new exciting features as you deem fit. To explore further, check the official documentation of CometChat Pro for more chat related features.
Check out the complete code for the project built in this tutorial on the completed branch of this repository on GitHub.