You are on page 1of 47

Building a mern stack application-

Whatsapp clone.

Anusha Tripathi

IcfaiTech (Faculty of Science and Technology)


ICFAI Foundation for Higher Education, Hyderabad-
501203,
Telangana, India.

1
Building a mern stack application-
Whatsapp clone.

Project report submitted in partial fulfilment of

the requirements for the degree of

Special project
In
Computer Science and Engineering
by

Anusha Tripathi

Roll No.: 18STUCHH010175

Under the guidance of

Dr. Sandeep Kumar Panda


Associate Professor

Department of Computer Science & Engineering

ICFAI Foundation for Higher Education, Hyderabad

IcfaiTech (Faculty of Science and Technology)


ICFAI Foundation for Higher Education, Hyderabad-
501203,Telangana, India

2
Declaration

I hereby certify that the work presented in this thesis entitled “Building a mern stack
application- Whatsapp clone" in fulfilment of the requirements for the Special project in
Computer Science & Engineering and submitted to ICFAI Foundation for Higher Education,
Hyderabad is an authentic record of my own work carried out during the period from 18
January 2021 to 1 may 2021, under the supervision of Dr. Sandeep Kumar Panda.

The matter embodied in this thesis has not been submitted by me for the award of any other
degree of this or any other University/Institute.

(Anusha Tripathi)

This is to certify that the above statement made by the scholar is correct to the best of our
knowledge.

Anusha Tripathi

3
Certificate

This is to certify that the project entitled “Building a mern stack application-
Whatsapp clone”, submitted by Anusha Tripathi, bearing Roll No.
18STUCHH010175 in partial fulfilment of the requirement for the Special
project in Computer Science & Engineering of ICFAI Foundation for Higher
Education, Hyderabad, Telangana, India, is a bonafide record of original
research work carried out by him under my guidance and supervision. This
work has not been submitted elsewhere for the same purpose.

Dr. Sandeep Kumar Panda


Associate Professor
Computer Science and Engineering
ICFAI Foundation for Higher Education
Hyderabad.

4
Abstract

This project is about building a  free web application, web platform messaging app
that lets you send text messages, to connect to any part of globe using internet. The
key challenge was developing an application that would match the level or standard
set by whatsapp web while providing a practical and easy to use platform that enables
various user chat online with anyone across the globe. The project was performed
with various technology like React,JavaScript,Pusher,PostmanAgent,etc..

Chatting is a method of using technology to bring people and ideas together despite of
the geographical barriers. The technology has been available for years but the
acceptance was quite recent. Our project is an example of a chat server. It is made up
of two applications - the client application, which runs on the user’s web browser and
server application, runs on any hosting servers on the network. To start chatting client
should get connected to server where they can do private and group chat.

Agile methodologies and Scrum were utilised to achieve the project goals and the
final system presented is a highly reactive and sophisticated web application built
with a modular architecture utilising a unidirectional dataflow. The modular,
component-based front end is implemented using Facebook's React library while
Redux allows unidirectional dataflow through it's Actions and Reducers. ES2015, the
latest version of JavaScript is the only language used in this project.

5
Acknowledgement

I, Anusha Tripathi, am proud to present this special project on the title “Building a mern
stack application- Whatsapp clone”. This is to acknowledge all those without whom this
project would not have been reality. First, and foremost I would like to express deepest
gratitude to my supervisors Dr. Sandeep Kumar Panda Associate Professor, ICFAI Foundation
for Higher Education for giving me the guidance, support, and encouragement. Without his
invaluable advice and assistance, it would not have been possible for me to complete this
report.

A project is a bridge between theoretical and practical learning and with this thinking I
worked on this project and made it possible due to timely support and efforts of all who
helped me.

Once again, I would like to thank my classmates and my friends also for efforts and for
encouraging me to do this project . Lastly, I would like to acknowledge each and every one
who contributed for my project work either by directly or indirectly.

Anusha Tripathi

6
Contents

1. Introduction 9

1.1 Problem Statement 11

1.2 Innovative Ideas of Project 11

1.3 Project Objective 11

1.4 Scope of the project 12

1.5 Design and Implementation 12

1.6 The Three tier Architecture 12

2. Introduction to full stack Development with Javascript 13

3. Technologies and Concept 16

3.1 React JS 17
3.2 React Hook 18
3.3 REDUX 20

3.3.1 Reducers in Redux 22

3.3.2 Rdeux Store 22

3.4 Axios 22

3.5 Application programming Interface(API) 23

3.6 Firebase 24

3.7 Node JS 25

3.7.1 Features of Node JS 27

7
3.8 Express JS 27

3.9 MongoDB and Mongoose 29

3.9.1 MongoDB 29

3.9.2 Key components of MongoDB architecture 30

3.9.3 Mongoose 31

3.10 Postman 32

3.11 Project Implementation 32

3.12 Development Environment setup 33

3.13 Version control System(VCS) 34

3.14 Visual Studio Code 34

3.15 JSON Web Tokens(JWT) 34

4 Product Overview 35

4.1User and Stackholder 36

4.2Functional and Non functional requirements 37

4.2.1 Functional Requirements 37

4.2.2 Non-Functional Requirements 37

4.3 Chat App or client part 37

4.4 Chat Server Engine or Server part 37

4.5 Chat App or Client Side 38

4.6 Chat server Engine 39

5 Conclusion and Future work 40

5.1Critical Evaluation 41

5.2Future Work 43

5.3Final Thoughts 44

8
6 References 45

List of Figures
Figure1 Mern stack logo 10
Figure2 The Three tier architecture design 13
Figure3 The Mern Hierarchy 13
Figure4 Most popular technologies 15
Figure5 App module 17
Figure6 A simple React component 18
Figure7 A simple React Hook component 19
Figure8 A simple Redux component 20
Figure9 Redux state management 21
Figure10 A simple web server 26
Figure11 Example of a server build with Express 28
Figure12 MongoDB Cluster 31
Figure13 JWT to access the application server 35
Figure14 Chat Architecture- How to approach it 38
Figure15 Package.json file of client side 39
Figure16 Dependencies for the server 40

List of Tables
Table1 Comparison table 16
Table2 User and Stackholder table 36

9
CHAPTER 1
Introduction
Web technology is growing tremendously as there have been significant
developments in the past few years which have made developers work easier and
more convenient. When the Internet began in 1989, many developments and changes
have occurred in web technologies. In the first years of the Internet in 1993, the web
was introduced and is called HTML (Hyper Text Markup Language) (Jacksi and
Abass, 2019). After a few years later in 1996 CSS (Cascading Style Sheets) were
introduced as a means of styling web pages. However, both technologies are still in
practice on every web page today. Today, developers are provided with so many
services and options to play around web technologies. While in the past HTML, CSS,
JavaScript was used as options for web- design. Many frameworks and libraries have
been developed to create a web page following certain patterns. In the end, all of them
are focused to develop good looking, reliable and functional web applications.

Today Developers around the world are making efforts to enhance user experience of
using application as well as to enhance the developer’s workflow of designing
applications to deliver projects and rollout change requests under strict timeline.
Stacks can be used to build web applications in the shortest span of time. The stacks
used in web development are basically the response of software engineers to current
demands. They have essentially adopted pre-existing frameworks (including
JavaScript) to make their lives easier. While there are many, MEAN and MERN are
just two of the popular stacks that have evolved out of JavaScript. Both stacks are
made up of open source components and offer an end-to-end framework for building
comprehensive web apps that enable browsers to connect with databases. The
common theme between the two is JavaScript and this is also the key benefit of using
either stack. One can basically avoid any syntax errors or any confusion by just
coding in one programming language, JavaScript. Another advantage of building web
projects with MERN is the fact that one can benefit from its enhanced flexibility.

10
Figure1 Mern stack logo.

However, due to the availability of many options, choosing an appropriate stack leads
to confusion. Out of different stack available today, MEAN (Mongo DB, Express JS,
AngularJS, and Node) and MERN (Mongo DB, Express JS, ReactJS and Node) are
the most popular stacks around JavaScript. Both stacks are open source and offer an
end-to-end framework to build comprehensive web apps that enable browsers to
connect with databases. Any syntax errors or any confusion can be avoided by just
coding in one programming language, JavaScript. Another advantage of building web
projects with MEAN or MERN is the fact of its enhanced flexibility (Bhardwaj,
2018).

MongoDB, Express React, and Node are all used in tandem to build web applications
an make up the mern stack. In this lineup, the Node and Express bind web backend
together, MongoDB servers as the NOSQL database, and React makes the frontend
that the user sees and interacts with.

All four of these technologies are free, open-source, cross-platform, and javaScript-
based, with extensive community and industry support. Each technology has a unique
set of attributes, which, when integrated together, make a simple but effective full
javascript stack for web development.

11
This report will explain the process of development of full-stack web application with
best practices of MERN stack such as reusability of JavaScript components, usage of
React hooks, and many more from scratch. This report starts with a brief introduction
of each tech Stack and then proceeds with the detailed implementation of each of the
Stack processes. A prototype of an application is developed to demonstrate the
implementation of different forms of JavaScript being used to form a single page web
application.

1.1 Problem Statement

• This project is to create a chat application with a server and users to enable the users
to chat with each other’s.

• To develop an instant messaging solution to enable users to seamlessly


communicate with each other.

• The project should be very easy to use enabling even a novice person to use it. • This
project can play an important role in organizational field where employees can
connect through LAN.

• The main purpose of this project is to provide multi chatting functionality through
network.

1.2 Innovative Ideas of Project

• GUI: Easy to use GUI (Graphical User Interface), hence any user with minimal
knowledge of operating a system can use the software.

• Platform independence: The messenger operates on any system irrelevant of the


underlying operating system.

• Unlimited clients: “N” number of users can be connected without any performance
degradation of the server.

1.3 Project Objective

• Communication: To develop an instant messaging solution to enable users to


seamlessly communicate with each other.

12
• User friendliness: The project should be very easy to use enabling even a novice
person to use it.

1.4 Scope of The Project

• Broadcasting Chat Server Application is going to be a text communication software,


it will be able to communicate between two computers using point to point
communication.

• The limitation of Live Chat is it does not support audio conversations. To overcome
this limitation, we are concurrently working on developing better technologies.

• Companies would like to have a communication software wherein they can


communicate instantly within their organization.

• The fact that the software uses an internal network setup within the organization
makes it very secure from outside attacks.

1.5 Design and Implementation

All code presented in this chapter is a simplified version of the original code or has
been translated into pseudo-code to improve readability and abstract over certain
language or library specific details that do not contribute towards the overall concept
or design pattern illustrated.

1.6 The Three Tier Architecture

Modern web applications are idiomatically developed using a three-tier architecture


consisting of a data source for storing persistent data, a web server containing
business logic , and a client-side that provides a user interface and view layer that end
users interact with three tier architecture.

13
Figure2 The Three tier architecture design

Figure3 The mern hierarchy.

CHAPTER 2

Introduction
to full stack Development with
javascript.

A full-stack is a combination of front-end and back-end. Front-end generally refers to the


portion of the application the user sees or interacts with, and the back end is the part of an
application that handles the logic, database interactions, user authentication, server

14
configuration, and so on. A full-stack application can be in any form like a web application,
mobile application, or some other application. A web application is a creation of application
programs that are delivered to the users' devices over the use of the internet. The web
application is accessed through a network and does not need to be downloaded. An end-user
can access a web application through web browsers such as Google Chrome, Safari, or any
other browsers.

Web technology is growing tremendously, and there has been a creation of different stack for
developing a full-stack web app. Among them, JavaScript is one of the dominant
programming languages in web development, that has been around for over 20 years. In the
mid-2000s, the shift from websites to web applications, along with the release of faster
browsers. JavaScript developers created libraries and tools that shortened the development
cycles, giving birth to a new generation of even more advanced web applications which in
turn created a continuous demand for better browsers. The real revolution began in 2008,
when Google released its Chrome browser, along with its fast JIT- compiling V8 JavaScript
engine. Google’s V8 engine made JavaScript run so much that it completely transformed web
application development (Haviv, A., 2014).

Since JavaScript supports both client-side and server-side, it has several benefits over
choosing different languages for client-side and server-side. With the knowledge in a single
programming language, JavaScript one can build a full-stack web application. It is a good
stack for developing a dynamic and high performing application. The JavaScript codes are
reusable, they have good tutorials, they are relatively easy to learn and implement, numerous
resources can be found in Stack Overflow and GitHub projects, they offer faster development,
great distribution through npm. Similarly, JavaScript versions are updated annually by ECMA
(ECMA International – European Association for Standardizing Information and
Communication) (Haviv, A., 2014).

15
Figure4 Most popular technologies.

As illustrated in Figure 4, 67.8 percent of the total surveyed listed JavaScript as the
most used technology. This clearly shows that JavaScript is one of the most popular
programming languages. Languages like PHP, ASP, Ruby, and Python are among the
early server-side languages. Lately, JavaScript has made possible to create full-stack
combining all the factors like a client-side user interface (UI), server-side
communication, server, and database to interact to make a complete package for web
development. MEAN and MERN are the most common stacks of JavaScript today.
Both stacks are similar only the front-end portion is different i.e. React library and
Angular framework. As React, is one of the popular among single page front-end
libraries of JavaScript that makes rendering part of the page easier without refreshing
the page hence was chosen for the thesis.

16
Table1 Comparison Table.

As in Table 1, React uses virtual DOM while Angular uses Regular DOM similarly,
the templating of the React is in JSX whereas the Angular has in HTML. The MERN
stack was chosen due to its popularity for having an advantage in the above-
mentioned table attributes. Therefore, the thesis is focused on developing a full-stack
using MERN stack.

CHAPTER 3

TECHNOLOGIES AND CONCEPTS

As briefly discussed above MERN stack consists of four independent frameworks and
libraries, MongoDB, ExpressJS, ReactJS and NodeJS which supports MVC
architecture to make the development process flow smoothly. MongoDB plays a role
for database management, while NodeJS and Express are used for building routes and
APIs in the backend and ReactJS is used in the frontend. The connection between

17
them is made (The Modern Application Stack – Part 1: Introducing The MEAN Stack
| MongoDB Blog, 2020). Each of the technology is used to develop an application and
each technology will be explained in deep in the coming chapters.

Figure5 App module.

3.1 REACT JS:-

React is one of the most widely used open-source, declarative, efficient, and
component- based JavaScript libraries that helps to build interactive UI where all the
components are reusable and can be applied for multiple projects. It was developed by
Facebook's engineer and is continuously handled and updated by Facebook and the
users around the globe. React is mainly concerned with re-rendering data of the
DOM. It requires additional libraries for the management, route handling and API
interaction.

Comparing with another front-end framework i.e. Angular, React uses views that
make code more predictable and easier to debug. It also helps to update DOM
efficiently and render the right components when the data changes.

18
Figure6 A simple React component.

The above snippet Figure 6 implement a render() method that takes input data and
renders the display. A div tag with the content of plain text "Hello, John" will appear
in a DOM-element with the id "mydiv". The above code uses an HTML like syntax
called JSX which is a syntax extension to JavaScript. Input data that is passed into the
component can be accessed by render () via this.props() (Elboim, 2017).

React components are small, reusable pieces of code. They return a React element to
be rendered to the page. It is also a normal JavaScript function that takes input or
props which is mean to be properties. Components can return other components,
arrays, strings, and numbers and, can be either functional or class-based, with or
without states. Normally, functional components do not have any states in them while
stateful components can holds states and pass on properties to the child-components.
Class components can have lifecycle methods and hence they can make changes to
the UI and data. There is a rule that is applied for writing component names. The
component name should always start with a capital letter (Elboim, 2017).

3.2 REACT HOOKS:-

19
Hooks were introduced to React in version 16.8 that enable the execution of custom
code in a base code. Reacts Hooks are special functions that allow to “hook into” its
core features. It provides an alternative to write class-based components by allowing
to handle state management from functional components.

Even though component-oriented architecture allows reusing views in the application,


one of the biggest issues a developer meets us how to use the logic located in the
required component state between other components. Where there are components
with similar state logic, but no good solutions to reuse the logic, the code in the
constructor and life cycle methods can be duplicated. To fix this developer usually use
high-order components and render props (Introducing Hooks – React, 2020).

Hooks are aiming to solve the issues allowing writing functional components which
have access to state, context, lifecycle methods, refs etc. without writing React
Classes (Introducing Hooks – React, 2020). An example of React hooks can be
observed in Figure 5.

Figure7 A simple React hook componenet.

20
In the above code, the class Component is replaced with a functional component, the local
state is removed and instead the new “useState” function is used. Hooks are used in functional
component to use state, useState() hook is used, while to replace life cycle methods like
componentDidMount() or componentDidUpdate(), useEffect() hook is used.

3.3 REDUX:-

As the data is stored in states among components in React, handling big scale application data
becomes difficult and gets complicated. These states can include server responses and data, as
well as locally created data. UI state is also increasing in complexity, so as we need to
manage active routes, selected tabs, spinners, pagination controls and so on. To tackle all the
big complications Redux is applied (Redux, 2020).

Redux is composed of 3 core principles; state to store necessary data, action to dispatch
changes made to the state and a reducer to make changes. When a user creates an event,
actions are dispatched to the central store. Actions are the only information that the store
receives from the user. This makes reducers fire a method on the previous state depending
upon the action received from the store. It also decides the fate of the old state.

App's state is mainly described as a plain object. For example, the state of people is presented
below.

Figure8 A simple redux component.

21
As states in redux are changing, an action is dispatched containing the payload and reducer
takes the role of making the changes to our state. All the state in an application is stored in
Redux as a single object. Reducers take an action and decide what method to be implemented
or deleted depending upon the action that is being dispatched. This is the only way the new
state gets produced every time (Redux, 2020).

Since, the data is stored as states among components in React, handling big scale application
data becomes difficult. So to tackle that ambiguity, Redux was made. Redux manages the
states in JavaScript applications. Even though React has brought their own state management
tools in the form of hooks, Redux being old practise and stable one at that, this tool was
chosen for this project. It can also be used for other javascript frameworks and libraries, like
angular and vue. It is itself extremely lightweight at memory size 2KB with all the
dependencies, so it doesn’t quite increase the total applications asset size. It was inspired by
Facebook’s Flux and Elm to simplify the MVC structure, specifically the Model and View
relationship when the application size is scaled higher. It is modelled on functional
programming concept. Redux allows us to store all the states in one store and components can
fetch them when required. Like other frameworks, React comes with internal state
management system as well. It is not fully stable during the creating of this project as well as
it is also good at only handling smaller scale application with smaller amount of states across
smaller components. With larger applications state management is better with Redux. When
an app has components that share states or data, a separate handler or store for state to live in
would be a great idea. Hence Redux implements that logic in providing states among
components without linearly depending on the hierarchy. Generally, state has to live in the
parent component in React for children to fetch, so ideally sibling components can’t access
the states among them. From parents to child it has to be passed on as props while Redux
allows direct access to the central store, from where you can fetch all the current states.

Figure9 Redux State management

22
3.3.1 Reducers in Redux :-

Reducers govern how the state of an application is changed upon an action is dispatched
containing a payload. All the application state is stored in Redux as a single object. Reducers
takes an action and decide what method is to be fired depending upon the action that was
dispatched. Hence a new state is produced every time. Just like array.reduce in javascript,
reducers take one object and one call back and return one object or array at the end, hence its
called reducer. Same object or state passed through reducers callback yields the same new
state every time because no additional callback is applied since they are usually passed as
action conditions. Instead of mutating the old state a new state is created by the reducers plain
functions.

3.3.2 Redux Store :-

A store is an immutable object tree in Redux. A store is a state container which holds the
application's state. Redux can have only a single store in your application. Whenever
a store is created in Redux, you need to specify the reducer. Let us see how we can create
a store using the createStore method from Redux.

The Redux store is the equivalent of a state tree. The only way the state tree is updated is by
dispatching an Action which passes an object to the Reducer and returns a new state. By
ensuring data is manipulated in this fashion, the logic of the application becomes easier to
manage and reason with especially when a large number of UI elements are changing (often
the case in large web application). Furthermore, the application is more predictable and
debugging is a matter of logging the state tree which is considered the single source of truth
in a unidirectional data flow architecture. If the application is not behaving the way it is
expected to behave, the logged state tree most likely will be incorrect (can be caused by an
erorr in the Reducer logic).

3.4 Axios:-

23
Figure10 A simple Axios component.

In the above figure Axios library is used. Axios is a very popular JavaScript library you can
use to perform HTTP requests, that works in both Browser and Node. js platforms. It supports
all modern browsers, including support for IE8 and higher. It is promise-based, and this lets
us write async/await code to perform XHR requests very easily. The link passed by the user
will update automatically the user will not need to refresh the page again and again.

Axios is a famous JS library that allows performing HTTP requests in both computers via
NodeJS and directly on browsers. It is supported by majority of browsers and is a better
alternative for reacts own Fetch API. Axios is promise based library which enables
performing asynchronous XHR requests.

Axios over native Fetch API comes with a lot of perks, some are listed below

1. Axios supports older browsers without the need of polyfill unlike fetch.

2. It has a way to abort a request as well set response timeout

3. Has a in-built CSRF protection and includes upload progress

4. Allows JSON data transformation and most importantly works with node

3.5 Application Programming Interface (API)

24
While web browsers are powerful and allow ever more complex tasks to be executed
on the client, certain types of tasks must be handled by the server for security or
efficiency reasons. In this case the client will call an endpoint (similar to calling a
method in a program) which is exposed by the server. This is called a request and can
include various request parameters and a payload. The server which is listening to
requests on its endpoints, will then respond by performing the requested tasks and
return a response object.

3.6 FIREBASE:- Firebase is a platform developed by Google for creating mobile and web
applications. It was originally an independent company founded in 2011. In 2014, Google
acquired the platform and it is now their flagship offering for app development. The Firebase
Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data
between your users in realtime. NEW: Cloud Firestore enables you to store, sync and query
app data at global scale. Firebase is Google's mobile application development platform that
helps you build, improve, and grow your app. Here it is again in bigger letters, for impact:
Firebase is Google's mobile application development platform that helps you build, improve,
and grow your app.

Firebase evolved from Envolve, a prior startup founded by James Tamplin and Andrew Lee in
2011. Envolve provided developers an API that enables the integration of online chat
functionality into their websites. After releasing the chat service, Tamplin and Lee found that
it was being used to pass application data that were not chat messages. Developers were using
Envolve to sync application data such as game state in real time across their users. Tamplin
and Lee decided to separate the chat system and the real-time architecture that powered it.
They founded Firebase as a separate company in September 2011 and it launched to the
public in April 2012.

Firebase's first product was the Firebase Realtime Database, an API that synchronizes
application data across iOS, Android, and Web devices, and stores it on Firebase's cloud. The
product assists software developers in building real-time, collaborative applications.

25
3.7 NODE JS

Node.js is the currently most popular open-source web server environment that allows
JavaScript code to be able to run outside of web browsers. It creates a dynamic web page by
helping JavaScript to write command-line tools and server-side scripting before the page is
sent to the user's web browser (Express/Node introduction, 2020). Node.js is suitable for the
foundation of a web library or framework because it has an HTTP a first-class citizen in
Node.js, designed with streaming and low latency. It uses a Google Chromes v8 engine to
execute the JavaScript. NodeJS, in general, makes developing cross-platform, server-side and
networking applications much easier (Chettri, 2016).

Node has earned a good reputation in the tech industry in a short period. It plays a big role in
the technology stack of high-profile companies who depend on its unique benefits. Microsoft
Azure users are provided with end-to-end JavaScript experience for the development of a
whole new class of real-time applications. The locking and concurrency issues of eBay were
freed by Node’s multi-threaded asynchronous I/O. The entire mobile software of LinkedIn is
completely built-in Node (Martonca, 2015).

PayPal after shifting to Node from Java for their existing projects saw significant
improvements over Java. The re-written app using Node was delivered in half the time with
less manpower and fewer lines of code. Hence, PayPal saw their development and product
performance increase dramatically after switching to Node from Java (Anderson, 2014). One
great advantage of NodeJS is the event-driven architecture which allows program code to be
executed asynchronously. The most common tasks for servers include answering queries,
storing data in a database, reading files from hard drive, and establishing connections to other
network components. All these actions are grouped together under the category I/O. In a
programming language like C and Java, I/O is executed synchronously. This means that tasks
are performed one at a time and moves to the next task after completion of the first task.
However, Node uses an asynchronous I/O, with which read and write operations can be
delegated directly to the operating system or database. This makes possible for many I/O
tasks to be carried out parallel to one another, without any blockage. In some cases, this can
prove to be a great advantage when it comes to the speed of the NodeJS and JavaScript-based
applications.

26
NodeJS also provides tools and functions like NPM and “require”, that help to manage third
party libraries like Mongoose and Express to make the development faster and efficient. NPM
is the default package manager which comes with the Node environment. Such tools help to
load inbuilt node modules into the applications (Chettri, 2016).

Figure10 A simple web server.

In the above code, a request is made to the server. When the code runs, the message “Server is
running on port 3001” is displayed in the console. When visiting the browser address
http://localhost:3001: “Hello World” message is displayed (Fullstack part3 |, 2020).

Node.js makes use of event driven, non-blocking I/O model to execute requests. Non-
blocking I/O model makes node asynchronous. The flow of the programs is defined by the
events taking place. Javascript uses single threaded event-loop, multi threaded processes cant
be executed. Hence, node has to execute multiple threads in parallel without waiting on every
event. Below is an example of what blocking vs nonblocking I/O model looks like. Node also
provides tools and functions like NPM (node package manager) and require, which help
managing third party libraries like Mongoose and Express to make development faster and
efficient. NPM is the default package manager which comes bundled with the Node
environment. These tools also help load inbuilt node modules into respective applications.
Node modules are blocks of codes that can be used where needed but when not loaded do not

27
impact the application codes. Developers can also build their own modules for personal use
and for the community.

3.7.1 Features of Node.js :-

1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its


library is very fast in code execution.

2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are
asynchronous i.e. non-blocking. So, a Node.js based server never waits for an API to
return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the previous
API call. It is also a reason that it is very fast.

3. Single threaded: Node.js follows a single threaded model with event looping

4. Highly Scalable: Node.js is highly scalable because event mechanism helps the
server to respond in a non-blocking way.

5. No buffering: Node.js cuts down the overall processing time while uploading audio
and video files. Node.js applications never buffer any data. These applications simply
output the data in chunks.

6. Open source: Node.js has an open source community which has produced many
excellent modules to add additional capabilities to Node.js application.

3.8 EXPRESS JS:-

Express is a Node.js web application framework that boosts the features of web, mobile API
applications, and APIs. Many libraries have been developed to ease sever side development
with Node, by far the most popular intended library for this purpose is express. The third-
party middlewares are installed to extend the functionality of the express application and add
features as required (Fullstack part3 , 2020).

28
In Express middleware is executed from top to bottom in the request-response cycle. Each
middleware has access to the request and the response object as well as a next function which
are passed from one middleware to another. The middleware takes the request, executes the
code inside, changes the request and response objects and calls the next function which
activates the next middleware in the queue. An express application can have access to the
application-level middleware, router-level middleware, error-handling middleware, built-in
middleware, and third-party middleware. In application-level middleware app.use() and
app.method() functions are used where ‘method’ is an HTTP verb that is being executed. The
router-level middleware is bound to an instance of the express router. Error-handling
middleware is around the object and takes four arguments, error, request, response, and next
objects. “Express.static” and “express.json” files are served statically and parse the incoming
request to JSON respectively in built-in middleware. Different functionality of the express
application can be extended either by logging in the information about the incoming request
or parsing the cookies (Fullstack part3 , 2020).

Furthermore, routers in express divide the application into several mini express applications
and combine to form an express application. The express server is composed of an HTTP
verb (GET, POST, PUT, DELETE). The same server creation from the above code (Figure 7)
can also be done with express. In express callback functions are specified to the routing where
callback functions can be used as arguments. Callback functions are called by using the next()
method to move on to another callback function.

Figure11 Example of a server build with Express.

29
This report demonstrates more about express in the development phase for adding different
functionalities like building the routes APIs, use of all the HTTP verbs and for user
authentication.

3.9 MONGODB and MONGOOSE

3.9.1 MONGODB

MongoDB is an open-source, cross-platform database that encompasses a wide variety of


different database technologies designed to fit into modern applications. MongoDB uses
JSON like files schemas, meaning data are stored as documents or collections which can be
strings, numbers, floats and even arrays and objects. MongoDB is also known as NoSQL
database; it allows the insertion of data without interrupting the service and provides the real-
time application changes. Due to the vast complexity in web development and usage, the
relational database cannot cope with the scale and agility challenges of modern applications.
When comparing relational database to NoSQL, the NoSQL database has better performance
and is more scalable. In this thesis, there is the use of the NoSQL database, which is
MongoDB for the fast development, code integration and for less database administrator time
(MongoDB System Properties, 2020).

Despite having so many advantages, MongoDB also has some drawbacks, as MongoDB
stores key names for each value pairs due to no functionality of joins there is data redundancy
which results in unnecessary consumption of memory. There is a limit for document size not
to exceed 16MB. Also, the nesting of documents is not allowed to have more than 100 levels.
However, the ability to store any kind of data without structuring any rule, governing the
relation can be a strength at times. Applications can be built using any platforms and provide
the preferred data-structure (MongoDB System Properties, 2020).

Among other big MongoDB features, auto sharding data to horizontal scaling and replication
of data among multiple servers for higher reach are the most developer friendly assets. All the
data are stored as documents, therefore horizontal scaling allows data as documents to be
stored at many different servers and locations, efficiency will be the optimum than having a
single machine handle all the valuable user information. More machines means more space to
support data growth and most importantly to maintain efficient read-write operations. Which

30
also allows storing higher scaled information, when the start-up starts taking pace. Similarly,
replication of the data prevents the chances of data-loss since the data is stored in multiple
servers. When one server fails, the data still could be fetched from the replica. Highly
efficient and higher scaled storable informations achieved via auto-sharding and server data
replications keeps MongoDB edges away than other relational database counterparts like
MySQL and Oracle databases.

Everything has drawbacks, of course MongoDB has few, one being the inability of processing
multiple operation as one transaction like other relational databases. Therefore, if any
operation causes an error the whole transaction fails. It also lacks joint operations features like
MySQL which in turn makes it weak against data with multiple relationships among them.
When making changes, multiple documents has to be updated. Changes in multiple data
clusters in different documents should be tied to a single transaction to make sure all the
collections are updated. Hence MongoDB being a nontransactional database, processes like
such could be few of its weaknesses, it has hard times at such. However, the ability to store
any kind of free form data structure without any rule governing the relation can be a strength
at times, applications can be built at any platforms and they can have any sort of data-
structure they prefer. For the handling of such ambiguous ungoverned data structure,
Mongoose was created by MongoDB. Mongoose is an Object Data Modeling (ODM) library
for MongoDB and Node.js. It provides schemas to model application data which therefore
cleans up the ambiguity of databases. Mongoose as a library contains built-in type casting,
validation, query building, business logic hooks and more. Therefore it aids in handling the
relationships between the data, provides schema validation, and is used to translate between
objects in code and the representation of those objects in MongoDB. Mongoose removes the
need of writing difficult data validations, business logics and casting broiler-plates in the
documents. Moreover, it provides additional sets of features on top of MongoDB, for instance
it can help manage the connections to MongoDB database. It can be helpful just even to
perform basic operations like read, write, and save data. By providing schema level validation
rules, it also allows only valid data to be saved in MongoDB.

3.9.2 Key Components of MongoDB Architecture:-

1. _id – This is a 24-digit unique identifier field required in every MongoDB


document in the collection. The _id field is like the document's primary key. If the
user creates a new document without an _id field, MongoDB will automatically create
the field.

31
2. Collection - Collection is a group of MongoDB documents. It is the equivalent of
an RDBMS table. A collection exists within a single database. Collections do not
enforce a schema. Typically, all documents in a collection are of similar or related
purpose.

3. Document - A document is a set of key-value pairs. Documents have dynamic


schema. Dynamic schema means that documents in the same collection do not need to
have the same set of fields or structure, and common fields in a collection's
documents may hold different types of data.

4. Database - Database is a physical container for collections. Each database gets its
own set of files on the file system. A single MongoDB server typically has multiple
databases.

5. Field - A name-value pair in a document. A document has zero or more fields.


Fields are analogous to columns in relational databases.

Figure12 MongoDB cluster.

3.9.3 Mongoose:-

32
Mongoose is a query language to communicate between the server and the database and
performs reading, writing, updating and deleting operations of the data. It is an Object Data
Modeling (ODM) library for MongoDB and NodeJS which provides schemas to model
application data which therefore cleans up the ambiguity of databases. It enforces a standard
structure to all the documents in a collection using schema. It also validates the stored data in
the documents as well as allow only valid data to be saved in the database. Overall Mongoose
provides all the features to the MongoDB including query building functions and business
logic in the data (Mongoose ODM v5.9.12, 2020).

3.10 Postman:- Postman is a software development tool. It enables people to test


calls to APIs. Postman users enter data. The data is sent to a special web server
address. Typically, information is returned, which Postman presents to the user.
Postman is an interactive and automatic tool for verifying the APIs of your project.
Postman is a Google Chrome app for interacting with HTTP APIs. It presents you
with a friendly GUI for constructing requests and reading responses. It works on the
backend, and makes sure that each API is working as intended.

In Postman, we create a request, and Postman looks at the response to make sure it
has the element we want in it. As it is an automation tool, it drastically improves
testing time and quality of the project. It helps in the early detection of bugs that
might sprout at later stages and cause more damage to the system.

Postman is the way to streamline the process of API testing. All APIs that we create
and deploy first rigorously go through Postman so that any major or show stopper
bugs are identified on time and fewer bugs leak through to later stages.

3.11 PROJECT IMPLEMENTATION:-

Developers Connecting Application (DEVAPP) is a web application project designed using


the MERN stack which facilitates the user to create a resume profile and other features. This
thesis guides the process of making a managed resume of developers who are looking to

33
create a profile. The sole function of the app is to help the developers create a nice-looking
profile. There is a dashboard where the users must sign up first and later, they can log in and
create own profile. In the dashboard, a normal user without registering into the application
can view the profile of users who have already created the resume in the system. The app has
features like view profile, edit-profile, add-education, and add-experience. Also, users are
facilitated with the options to delete their profile permanently. By creating a profile user can
give and take the feedback on own's and other developers profile. Users from anywhere can
be connected by resume. Also, this thesis could be a good social networking site like other
social sites. These are the only feature the app included for now and other features or
improvements will be considered if the application continues to be developed. The
architecture of the project is shown below.

Figure13 The architecture of the project

3.12 DEVELOPMENT ENVIRONMENT SETUP:-

It is always important to choose the right tools and a suitable environment to perform any
kind of task. A combination of such tools and environment increases the efficiency of work,
increases productivity, and saves a lot of time. Choosing a comfortable stack is also one of the
keys to succeed in the development process and make it easier. The application was entirely
developed in MacBook Pro 2018 with macOS Catalina 10.15.3 as the operating system.
Besides, several third parties’ tools and software were used to make the development process
easier and get an expected result. Visual Studio Code was used as a code editor for this

34
project. VS Code is an open-source project spearheaded by Microsoft, which was first
released in 2015. Since then it has become one of the most popular code editors among the
developers. VS Code is a great package starting from setup, adopting UI for showing the
content of files, customizable settings, debugging a NodeJS web app to the deploying of the
web application to the cloud (Code, 2020).

3.13 Version Control System (VCS):-

Version control is a component of software configuration management, that keeps a record of


changes to a document or set of documents over time so the specific versions can be recalled
later. Changes are identified by a number or letter code, which is termed as “revision
number”, “revision level”, or simply “revision”. For instance, an initial set of files is “revision
1”. When the change is made, the resulting set is “revision 2” and so on. “Each version is
associated with a timestamp and the person making the change. Revision can be compared,
restored, and with some types of files, merged” (Blischak, Davenport and Wilson, 2016).
Version control makes a group or team working together on a project easier to collaborate.
There are many different version control systems available which are Git, SubVersion, Team
Foundation Version Control and so on. Git one of the most common version control system
and was chosen for the project as this is a distributed version control system which
emphasizes on speed, data integrity and support for distributed non-linear workflows
(Blischak, Davenport and Wilson, 2016). The advantage of Git is that it provides backups by
the nature of its design. Whereas other VCSs have a ‘single source of truth’, every Git
repository stores the entire repository. Typically, developers have a working copy of a
repository which is stored locally on their computers, as well as one repository stored in a Git
cloud provider such as GitHub, GitLab or BitBucket.

3.14 Visual Studio Code (VS Code) :-

VS Code is a popular source code editor by Microsoft. It can be used with many languages
but since it is based on Electron, one of the Node.js frameworks, MERN development is easy
and efficient. It is free for developers use and is open source under MIT license. Built-in
terminal support makes it much easier for web-development.

3.15 JSON Web Tokens (JWT) :-

35
JWT is a JSON web object which helps creating a safe data communication between two
parties which in application’s context are the application’s server and the end-user. The token
is composed of a header, a payload and a signature. Header provides information how
signature is to be computed. Payload is the data stored in the token, like the user information.
The payload is encrypted or hashed to produce a signature. It is used for the authentication of
users in the application. Below is the way JWT attaches with the application to provide
security and privacy to the contents.

Figure13 JWT to access the application server.

CHAPTER 4

PRODUCT OVERVIEW
The functionality of the chat application is to give the ability to chat with whoever is
online on the application. The users and stakeholders will be a small group for now,
the use cases will be what is available to the user, and the functional/nonfunctional
requirements will be covered, as well as the milestones of the chat application.

4.1 Users and Stakeholders

36
This section will deal with the users and stakeholders. The users will be using the chat
application and the stakeholders will develop, maintain, and test the chat application.

Team We will be developing, maintaining, and


and I testing the chat application through its phases
of development.

Users The users will be anyone who has the chat


application and registers for it.

Table2 User and stakeholder table.

1.1 Project Perspective: • The system to be developed here is a Chat facility. It is a


centralized system. It is Client-Server system with centralized database server. All
local clients are connected to the centralized server via LAN. • There is a two-way
communication between different clients and server. This chat application can be used
for group discussion. It allows users to find other logged in users.

1.2 Interface: • This application interacts with the user through G.U.I. The interface is
simple, easy to handle and self-explanatory. • Once opened, user will easily come into
the flow with the application and easily uses all interfaces properly. However, the
basic interface available in our application is: -

• Title panel

• Message panel

• Contact list panel

• Status panel

4.2 Functional and Non-Functional Requirements: -

37
4.2.1 Functional Requirements

1. User Registration: User must be able to register for the application through an
Email, Username and Password. On Opening the application, user must be able to
register themselves or they can directly login if there have an account already. If user
skips this step, user should able to chat. The user’s email will be the unique identifier
of his/her account on Chat Application.

2. Adding New Contacts: The application should detect all contacts from the server
database. If any of the contacts have user entered with Chat Application, those
contacts must automatically be added to the users contact list on Chat Application.

3. Send Message: User should be able to send instant message to any contact on
his/her Chat Application contact list. User should be notified when message is
successfully delivered to the recipient by coloring message.

4. Broadcast Message: User should be able to create groups of contacts. User should
be able to broadcast messages to these groups.

4.2.2 Non-Functional Requirements

1. Privacy: Messages shared between users should be encrypted to maintain privacy.

2. Robustness: In case user’s system crashes, a backup of their chat history must be
stored on remote database servers to enable recoverability.

3. Performance: Application must be lightweight and must send messages instantly.

4.3 Chat App or client part, which is a Web chat application. Build on React

4.4 Chat Server Engine or server part, which is a pool of external servers
responsible for the chat operation. This is the place where all the chat magic happens.

Both parts contain various components that communicate to each other and bring the
chat into action

38
Figure14 Chat Architecture-How we approach it.

4.5 Chat App or Client Side

Chat App is the other major part of the chat architecture, the one that users directly
interact with. It's split into two separate root components:

• Chat Client Engine handles all the communication with the Chat Server Engine via
its internal components: Chat REST API Client Library and Chat WebSocket Client
Library.

• Chat UI displays data to users: Chat Contact List UI, Chat Dialog UI Component:

Components:- Components are the building blocks of any React app and a typical
React app will have many of these. Simply put, a component is a JavaScript class or
function that optionally accepts inputs i.e. properties(props) and returns a React
element that describes how a section of the UI (User Interface) should appear.

App.js is the starting point of our React app. A package.json file.

• lists the packages your project depends on

39
• specifies versions of a package that your project can use.

• makes your build reproducible, and therefore easier to share with other developers.
A package.json file may look similar to this.

Figure15 Package.json file of client side.

4.6 Chat Server Engine:-

This is a core of the chat architecture that handles message delivery and dispatch. In
our version of chat architecture, it includes the following

Components

• Chat REST API handles the tasks that are not connected directly to message
dispatch and delivery, such as user authentication, changing of user settings,

friends invitation, downloading sticker packs, etc. The Chat App (the chat client part)
communicates with the Chat REST API via the Chat REST API Client Library.

• Chat WebSocket Server is responsible for transmitting messages between users. The
Chat App communicates with the Chat WebSocket Server via the Chat WebSocket

40
Client Library. This connection is open two ways; that means users don’t have to
make requests to the server if there are any messages for them, they just get them
right away.

Dependencies:- The third-party package or modules installed The package.json file is


the heart of Node.js system. It is the manifest file of any Node.js project and contains
the metadata of the project. The package.json file is the essential part to understand,
learn and work with the Node.js. It is the first step to learn about development in
Node.js.

Figure16 Dependencies for server.

CHAPTER 5

Conclusion and
Future work
The achievement of this project is researching the basic components of MERN stack
technology: MongoDB, ExpressJS framework, ReactJS library and NodeJS platform.
Using MERN stack technology in conjunction with firefox and postman to build a
clone of Whatsapp that is capable enough to send and receive messages. Concept of

41
Redux and other plugins to make the project fast yet attractive are also discussed all
around the report.

In the light of JavaScript development and right when they made it work outside of
browsers, JavaScript front end development had to take its pace, developers were
given with frameworks after frameworks, Angular, React etc. With the ability of
working front and back-end solely with JavaScript, MERN stack was authors choice
of stack. So the report is a documentation of all the MERN development. It opens up
opportunities for anyone wondering about the stack. It explains on creating APIs
using Express on NodeJS framework. Briefly defines the attachment of MongoDB
and its benefits.

There is always a room for improvements in any apps. Right now, we are just dealing
with text communication. There are several chat apps which serve similar purpose as
this project, but these apps were rather difficult to use and provide confusing
interfaces. A positive first impression is essential in human relationship as well as in
human computer interaction. This project hopes to develop a chat service Web app
with high quality user interface. In future we may be extended to include features
such as:

• File Transfer

• Voice Message

• Video Message

• Audio Call

• Video Call

• Group Call

5.1 Critical Evaluation

This section looks at what went well and what could have been done differently in
this project.

42
The design choices and decisions that were validated include:

• Unidirectional data flow: as the amount of components and code base grew, the
decision to utilise React with Redux while eschewing the MVC architecture paid off.
The modular architecture and single state tree that controlled the UI allowed for fast
bug detection and more significantly, made the application easier to reason about.
Encapsulation of logic and view information inside a single React component and file
also resulted in quicker modifications and changes which would have had to be made
in two different files (in the View and Model) in an MVC architecture and is typically
more error prone.

• Choosing React over Angular: at the time of writing, the Angular community is still

fragemented between Angular 1 and Angular 2. With every month that passes, the
React community grows and more developers switch from Angular to React. The
future of React looks very positive which decreases the chances of the Unibuddy
Platform front end becoming obselete in the very near future.

• NoSQL: Being able to add and remove fields from the various database collection on
an almost daily basis proved to be an invaluable advantage. However, this proved to
be a double edged sword as not having enforced data integrity meant more work on
the client side as every database field had to be verified (check that it existed and is of
the right type) before being rendered on the client. In the end, the advantages provided
by MongoDB’s flexible scheme outweighed this additional verification overhead. On
the other hand, the design choices, project management and decisions that could have
possible be done better include:

• Bootstrap: While Bootstrap comes with a very flexible CSS library, the Unibuddy
design sketches featured a very unique and custom design. While Bootstrap saved

43
many hours of writing custom CSS classes especially since it provides a responsive
grid framework, there were some occasions where it appeared that the author was
trying to fit “a round peg in a square hole”, so to speak. The semantic overloading of
the grid system in Bootstrap often results in attempting to implementing certain UI
components using the grid system that are not really suitable it.

• Lack of strong typing: Javascript is a weakly typed language (variables are not
restricted to consisting of a specific type). During the development of the project, a
large number of bugs occurred due to the lack of type checking in Javascript. In
retrospection, a static type checker like the Flow library for Javascript should have
been integrated and utilised by the author.

• Meteor Hot Reloading: The decision to use Meteor was validated as features like

authentication, session management, accounts, publications, Meteor Methods etc.


were hugely valuable to the project. The major drawback was the Meteor build
process and hot reloading which became very slow as the project grew and the
number of files grew. The hot reloading time (the time that the project takes to re-
build after code changes are saved) often exceeded thirty seconds. Instead of using the
Meteor Hot Reloader, an attempt to use an external hot reloader such as Webpack and
decoupling it from the Meteor framework should have been executed in order to avoid
this wasteful ‘waiting’ time throughout the project.

5.2 Future Work

In addition to the points discussed in the previous section, a number of other aspects
in the project could benefit from refactoring or improvement in the future:

• Testing of API methods

44
• Replacing Publications/Subscriptions with GraphQL.

• Caching of slow loading data

• Replace try/catch and chained callbacks with Javascript Promises.

Lastly, a few major future features that will be implemented post-project according to
the Unibuddy

roadmap:

• Group Chat Rooms for Applicants interested in the same courses/universities.

• Integrating credit charging into the chat system

• Purchasing of a “Full Access” to a Mentor

• Connecting the Schools Dashboard to the backend and adding full functionality to it.

5.3 Final Thoughts

Software engineering is difficult. While there are vast amounts of research and best
practices, completing and evaluating a software project in entirety is not a trivial task.
Reflecting on this project, it is clear that regardless of the amount of analysis and
design conducted for a software project, there will almost always be unexpected
challenges and changes that arise. Hence, the Agile approach that embraces change
was validated by this project and the I understands why Agile has reached such a high
degree of popularity in the software engineering community. This chapter assessed
the successes and failures of this project. In summary, virtually all requirements were
met and the personal aims were achieved. The logical verdict is that the project was
largely successful. The degree of success will be more apparent once the platform is
used by a significant number of users in the near future.

45
References

1. What is ReactJS and Why should we use it? [Internet]. c-sharpcorner.com 2018
[cited 14 November 2018]. Available from:
https://www.c-sharpcorner.com/article/whatand-why-reactjs/

2. The modern application stack [Internet] Mongodb Official Website 2017 [cited 26-

January 2017] Available at: https://www.mongodb.com/blog/post/the-modern-


application-stack-part-1-introducing-the-mean-stack

3. React.js: a better introduction to the most powerful UI library ever created.


[Internet] hackernoon.com 2018 [cited 3 September 2018]. Available from:
https://hackernoon.com/react-js-a-better-introduction-to-the-most-powerful-ui-library-
ever-createdecd96e8f4621

4. A beginners guide to Redux [Internet] gistia software engineering 2017 [cited 4


September 2017] Available from: https://www.gistia.com/beginners-guide-redux/

5. “Hello World” in React-Redux [Internet] medium.com 2018 [cited 4 April 2018]


Available at: https://medium.com/@lavitr01051977/easy-redux-b29391b499cb

6. Build a Login/Auth App with the MERN stack [Internet] Bits and Pieces 2018
[cited 21 November 2018] URL: https://blog.bitsrc.io/build-a-login-auth-app-with-
mernstack-part-1-c405048e3669

7. What exactly is Node.js? [Internet] freeCodeCamp 2018 [cited 18 April 2018]


URL:

https://medium.freecodecamp.org/what-exactly-is-node-js-ae36e97449f5

46
8. Components and Props [Internet] reactjs.org Official Website URL:
https://reactjs.org/docs/components-and-props.html

9. MERN Stack Front To Back: Full Stack React, Redux & Node.js [Internet] Udemy

Brad Traversy 2019 [last updated April 2019] Available at: https://www.udemy.com/

mern-stack-front-to-back/

10. React-strap [Internet] Official Website Available at:


https://reactstrap.github.io/components/listgroup/#

11. Basic routing [Internet] Express JS Official Website 2018 URL: https://expressjs.-

com/en/starter/basic-routing.html

12. ReactJS-JSX [Internet] TutorialsPoint 2019 URL: https://www.tutorialspoint.com/

reactjs/reactjs_jsx.htm

13. 5 Easy Steps to Understanding JSON Web Tokens (JWT) [Internet] Vandium
Software [cited 16 May 2016] URL: https://medium.com/vandium-software/5-easy-
stepsto-understanding-json-web-tokens-jwt-1164c0adfcec

47

You might also like