Yes, you heard it, Today we will implement a Real time private chatting app using React (Latest) and Nodejs.
Now one might ask why on God’s green earth another chat application?
Well, In my defense I would like to say,
This is not just another group chat application. It’s a chat application where you will learn much more than just broadcasting socket event. And I assure you, even if you are new in React, This application will be a piece of cake for you.
Not convinced yet?
No problem, let’s talk about a few more features. As the title reads Realtime Private chat, Here you will get to know how you can implement real-time private chat between users those who are online. It’s better, I list down all these features instead of writing a paragraph.
- First Thing first, you will implement a Login and Registration in your application.
- After a Successful Login/Registration, User will be redirected to the Home Page.
- Here You will implement a Realtime chat list, why Realtime because chat list will update automaticallywhen any new user comes online or any existing user goes offline.
- On the Home Page, User can initiate a conversation with any other online user. Also, the user can read their old conversation.
- Once you are done talking, Then you can use theLogout button to go offline.
If you are familiar with Angular, then you will like to read how to create Real-time private chatting app using Angular.
Let’s take a look at the final outcome of this application, Before going any further.
Login Page
Home Page
So we will implement all the above-listed features in the series of Fours articles. As this article seems little spacious, hence I have divided it into 4 parts. Each part of this article covers a unique part in building the Real Time private chatting app.
First part: Covers the prerequisites, Configuration of React application along with React routes and Nodejs server setup.
Second part: In this part, you will implement Login and Registration. With that, you will implement a feature to check the uniqueness of the username before registration and the session of a user (when the user navigates to the home page).
Third part: Here you will implement a Realtime Chat list.
Fourth part: In the last part, you will implement a chat feature, where the user actually can chat with each other.
Before we start, I want to confess that this series is going to be long, so bear with me and you might also want to go grab a Coffee, Beer or even Water will do; whatever works for you.
Creating a new React project
Let’s use create-react-app CLI to set up our application. If you don’t have create-react-app CLI installed on your machine run the below command to install it globally.npm install -g create-react-app
After create-react-app CLI installation, to create a new React project Run below command. This command will create all the necessary files, download all the required external dependencies and do all of the setup work for us.
create-react-app chatapp
Project structure and Folders
In my opinion, it is very important that you understand what folders and files you will create to in this application. You can see all the folders and files in the below image.
The above Image is a snapshot /src
folder with few folders and files inside it. We have created a few folders, let’s understand the motive of each file and folder.
=> You can create all the files are listed above or just download the code.
1. /pages
: You will create all the pages inside this folder. In this application, we have only two pages with a few components inside them.
Though the name of each React component is comprehensible. But still, I will list down each component along with its usage for the sake of our conscience.
Authentication Component
: We will use it for Login and Registration.Chat-list Component
: As the name suggests, to display the real-time Chatlist.Conversation Component
: This component is used to display messages.Home Component
: This will be the host component of the Chatlist and conversation component.NotFound Component
: This component will be used when the user enters an incorrect URL, which not defined in our application.
2. /utils
: This folder contains the two files which will be used for making an HTTP request and Socket events.
ChatHttpServer class
: In this class we will write all the HTTP request. In this application, we will axios to make HTTP calls.ChatSocketServer class
: In this class, we will write Socket related code to receive and send real-time events.
React Routing
In this section, we will configure our application’s routing. Here we will use react-router-dom to create React routes. Total we will have two routes /
and /home
route.
=> When this application loads in the browser, we will redirect the user to/
route. This route will display the Authentication page which is nothing but Authentication
component.
=>Now theApp.js
file and write down the below code,
App.js:
/* * Real time private chatting app using React, Nodejs, mongodb and Socket.io * @author Shashank Tiwari */ import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Authentication from './pages/authentication/Authentication'; import Home from './pages/home/Home'; import NotFound from './pages/not-found/NotFound'; import './App.css'; class App extends Component { render() { return ( <Router> <Switch> <Route path="/" exact component={Authentication} /> <Route path="/home/" component={Home} /> <Route component={NotFound} /> </Switch> </Router> ); } } export default App;
Creating New Nodejs Project and Application Folder structure
Till now you created and completed React application setup. As of now, your React application is nothing a but clean slate, and you will write rest of the A B C D in next 3 part of the series.
In this section, you will create Nodejs API boilerplate. For those who don’t know why Nodejs server is obvious to us,
- First, you will need a server where you can store and fetch the user’s data and messages.
- Second, you need to implement real-time messaging for that we need a Web Socket.
- Third, it is the best choice available out there, you don’t have to learn anything at all except Javascript sure!
Okay so let’s go ahead and start the development, but before that let’s take a look at our folder structure of nodejs server.
As you can see, There are five Folders in this application; Here you will create Four folders, expect one folder i.e. /node_modules
. As of now, our application is not that much big, so I have kept the folder structure very minimal and easy to understand. In case if you want to go big, I would recommend reading the folder structure guide provided by Rising Stack.
To understand the Purpose of each folder, go through the below-listed points.
/config
: In this folder total, we have Four files as shown in the above image. In these files, we will cover the application and express related configuration along with the database connection./handlers
: Here you will create files, which would include MongoDB query execution and Express route handlers. Which we will see down the road./utils
: You will create files, which are mainly used as sugar in order to fulfill the other operations. In this case password hashing for Login and Registration./web
: All your Express Routes and Socket Events will go here.
And at the end, we have .env
and server.js
file, and I believe these files needs no introduction.
Well, You studied and understood the project structure you have. Now let’s create a Nodejs project by running below command.
npm init
This command will create apackage.jsonfile, by asking about your project. Now let’s take a look at package.json which, I have created.
package.json:
{ "name": "rest-api", "version": "0.0.1", "description": "This Rest API for my React chat APP.", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "rest", "api" ], "author": "Shashank Tiwari", "license": "MIT", "dependencies": { "bcrypt": "^1.0.3", "body-parser": "^1.15.2", "cors": "^2.8.1", "dotenv": "^5.0.1", "express": "^4.14.0", "mongodb": "^2.2.19", "socket.io": "^1.7.2" } }
Creating a Nodejs Server
So you are familiar with the folder structure, it’s time to go ahead a create Nodejs server. You will start your Nodejs in the server.js
file, as the name of the file represent itself. Open the server.js
file and write down the below code.
server.js:
/* * Real time private chatting app using React, Nodejs, mongodb and Socket.io * @author Shashank Tiwari */ 'use strict'; const express = require("express"); const http = require('http'); const socketio = require('socket.io'); const socketEvents = require('./web/socket'); const routes = require('./web/routes'); const appConfig = require('./config/app-config'); class Server{ constructor(){ this.app = express(); this.http = http.Server(this.app); this.socket = socketio(this.http); } appConfig(){ new appConfig(this.app).includeConfig(); } /* Including app Routes starts*/ includeRoutes(){ new routes(this.app).routesConfig(); new socketEvents(this.socket).socketConfig(); } /* Including app Routes ends*/ appExecute(){ this.appConfig(); this.includeRoutes(); const port = process.env.PORT || 4000; const host = process.env.HOST || `localhost`; this.http.listen(port, host, () => { console.log(`Listening on http://${host}:${port}`); }); } } const app = new Server(); app.appExecute();
Explanation:
The above code is straightforward, don’t you think! The server starts in three steps, which are listed below.
- First, The app starts with by executing the constructor method when we create an Object of
Server
class. - Second, in the
appConfig()
method you will include all your configurations. - The last step is, you have to include the Routes and Socket Event.
And all this will happen when you will execute aapExecute()
method by creating the Object of Server.
Creating Configurations Files:
This section is all about writing configuration file, So you will basically deal with the files inside /config
folder.
Let’s start with express-config.js
file, Honestly at this point, you don’t need this file. Though when your application grows, will need to do express configuration. So open the express-config.js file and write down the below code,
express-config.js:
/* * Real time private chatting app using React, Nodejs, mongodb and Socket.io * @author Shashank Tiwari */ class ExpressConfig{ constructor(app){ // Setting .html as the default template extension app.set('view engine', 'html'); //Files app.use(require('express').static(require('path').join('public'))); } } module.exports = ExpressConfig;
Second and our main configuration file is the app-config.js
file, where you will write all your application related configurations, also you will include ExpressConfig
file there. Open theapp-config.js
and write down the below code.
app-config.js:
/* * Real time private chatting app using React, Nodejs, mongodb and Socket.io * @author Shashank Tiwari */ const expressConfig = require('./express-config'); const bodyParser = require('body-parser'); const cors = require('cors'); const dotenv = require('dotenv'); class AppConfig{ constructor(app){ dotenv.config(); this.app = app; } includeConfig() { this.app.use( bodyParser.json() ); this.app.use( cors() ); new expressConfig(this.app); } } module.exports = AppConfig;
Explanation:
- Since this application uses
.env
file to store configurations, you will dotenv module, read more about it here. - Inside the
includeConfig()
you will basically use bodyparser and activate CORS for the application routes.
Nothing much to do here, let’s move on to the next step.
Connecting with database (MongoDB):
Create adb.jsfile under /config folder and write down the below code. Here I am using the MongoDB module, though you can use mongo schema and all. Since I don’t want to make this article more complicated so I will leave that to you.
db.js:
/* * Real time private chatting app using React, Nodejs, mongodb and Socket.io * @author Shashank Tiwari */ "use strict"; /*requiring mongodb node modules */const mongodb = require('mongodb'); const assert = require('assert'); class Db{ constructor(){ this.mongoClient = mongodb.MongoClient; this.ObjectID = mongodb.ObjectID; } onConnect(){ const mongoURL = process.env.DB_URL; return new Promise( (resolve, reject) => { this.mongoClient.connect(mongoURL, (err, db) => { if (err) { reject(err); } else { assert.equal(null, err); resolve([db,this.ObjectID]); } }); }); } } module.exports = new Db();
Conclusion
So here we are at the end of the first part. Before jumping to the next part of the article, let’s encore all the step one more time.
- We created the React application, did all required setup, and understood it’s folder structure.
- Second, we created a new Nodejs application and did the configuration.
- Also, we created a Nodejs server and connected our application to the MongoDB.
In the next part, you will implement Login, Registration, and Logout feature along with other required features. I’ll see you in the next part.
Thank you for this piece, when you will release the other parts?
Maybe this Weekend if time permits or next weekend for sure.
Thanks for stopping by.
waiting for 3rd part …upload it as soon as possible.
waiting for 3rd part …upload it as soon as posible.
There’s a typo. `aapExecute()` should be `appExecute(). 😀
There’s a typo. `aapExecute()` should be `appExecute()`.
hi! i’m new in node and mongodb, i’m struggling to connect connectivity using .env file .i’m install and configure all necessary thing but still getting that error
Error:{“error”:true,”message”:”You are at wrong place. Shhoooo…”}
Hi Adnan,
This response
{“error”:true,”message”:”You are at wrong place. Shhoooo…”}
you get when you try to access the URL that you haven’t created.Check if your MongoDB server is running and try to console something inside the
db.js
file.