0% found this document useful (0 votes)
32 views

MERN Stack

Uploaded by

anurag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

MERN Stack

Uploaded by

anurag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Table of Contents

ACKNOWLEDGEMENT………………………………………………………………………….I

CANDIDATE DECLARATION…………………………………………………………………..II

INTERNSHIP COMPLETION CERTIFICATE…………………………………………………..III

ABSTRACT………………………………………………………………………………………..IV

LIST OF ABBREVIATIONS

CHAPTER 1 1

1 INTRODUCTION 1
1.1 Overview of the Company 1
1.2 Internship Program Objective 1
1.3 Vision of the Company 1

CHAPTER 2 2

2 APPLICATION INFRASTRUCTURE – THE MERN STACK 2

2.1 Node.js 3
2.1.1 Node Module 4
2.1.2 Node Package Manager 5
2.1.3 Node Event Loop 7
2.2 Express.js 8
2.2.1 Basic Routing 8
2.2.2 Writing and Using Middleware 9
2.3 MongoDB 10
2.3.1 NoSQL Database 11
2.3.2 Data Models 12
2.3.2.1 Embedded Data Model 12
2.3.2.2 Normalized Data Model 13
2.3.3 MongoDB Atlas 14
2.3.4 Mongoose 16
2.4 React.js 17
2.4.1 JSX 18
2.4.2 Virtual DOM 19
2.4.3 Component 20
2.4.3.1 Functional Components 21
2.4.3.2 Class Components 22

CHAPTER 3 15

3 APPLICATION IMPLEMENTATION 15

3.1 Application requirements 15


3.2 Application development 16
3.2.1 Back-end development 16
3.2.1.1 Basic Setup 16

3.2.1.2 Mongoose Schema Creation 18


3.2.1.2 Authentication with JWT 20
3.2.1.4 Routing and API Documentations 22
3.2.1.5 API Testing with Postman 25

3.2.2 Front-end development 26


3.2.2.1 Basic Setup and Routing 26
3.2.2.2 User Authentication 27
3.2.2.3 Dashboard Component 30
3.2.2.4 Home Component 31
3.2.2.5 Shop Component 33
3.2.2.6 Cart Component and Payment Gateway 33

CHAPTER 4 35

4 DISCUSSION
4.1 Application Evaluation 35
4.2 Further Improvement 36

CHAPTER 5 38

5 CONCLUSION 38

REFERENCES 39
List of Abbreviations

ASP Active Server Pages

JSON JavaScript Object Notation

BSON Binary JavaScript Object Notation

PHP Hypertext Preprocessor

MERN MongoDB, Express, React.js, Node.js

JSX JavaScript Syntax Extension

HTTP Hypertext Transfer Protocol

HTML Hypertext Markup Language

CSS Cascading Style Sheets

REST Representational State Transfer

API Application programming interface

URL Uniform Resource Locator

NPM Node Package Manager

NoSQL Non-Structured Query Language

MVC Model View Controller

UI User Interface

ODM Object Data Modeling

DOM Document Object Model


Chapter 1
1 Introduction
1.1 Overview of the Company

Wisflux Private Limited thrive to empower and enhance the lives of people
Through profound IT Innovative solutions, with the help of our competent
technical team specialized in providing very effective and efficient solutions.
Transforming your ambitious goals into reality.

Core Values:
1. Our cross-functional team structure and collaborative approach ensures that all
reviews and client feedback are incorporated in the development process. This is
done in order to obtain satisfactory outcomes on time, without compromising on
cost or quality.

2. We provide services to cover all aspects of app creation This saves our partners
the trouble of managing multiple teams and allows them to focus on core
business objectives.

3. We understand the vital importance of getting your product to market at the


earliest to stay ahead of the competition. Our team will coordinate with you every
step of the way to make sure that your product is released well within defined
time frames.

1.2 Internship Program Objective

The major objectives of internship are:

 To expose students to a particular job and a profession or industry.

 To provide students with opportunity to develop skills in the field of interest.

 To help students in developing business contacts i.e. creating network contacts.

 To help students potentially land permanent or contractual jobs from host company.

1.3 Vision of the Company

To Provide Quality Service and Solution in the field of Information Technology.


1
Chapter 2

2 Application Infrastructure – The MERN stack

The MERN stack is basically a JavaScript-based stack which is created to facilitate the
development process. MERN comprises of four open-source elements: MongoDB as
thedatabase, Express as server framework, React.js serves as client library and
Node.js is an environment to run JavaScript on the server. These technologies
introduce an end- to-end web stack for developers to utilize in web development.

Figure 1. MERN stack architecture

Figure 1 explains the architecture of MERN stack. Firstly, Express with Node.js create
API which is used for logic and to interact with MongoDB. When React client sends a
HTTP request to the back-end server. The server analyzes the request, retrieves data
from the database and responses with that data. React client is updated based on that
returned data.

2
2.1 Node.js

Node.js is JavaScript environment provider and the most essential core of the MERN
stack. Node.js is now the most widely used free open-source web server environment
created by Ryan Dahl. It allowed to execute JavaScript code on the server. It is able to
run on multiple platforms like windows, Linux and mac OS. Node.js is dependent on
Google V8 engine which is the core of Chrome browser. C and C++ run both Node and
V8 which is better in performance speed and memory consumption.

A Node app runs in an individual process with event looping, without the need of a new
thread for each operation. This is opposed to traditional servers which make use of lim-
ited thread to handle requests. Node is a non-blocking, asynchronous and event-driven
engine aimed for scalable application development. Generally, Node libraries are cre-
ated using non-blocking pattern. Application calls a request and then move on to work
on next task rather than stalling while waiting for a response. When the request is com-
pleted, a callback function informs the application about the results. This allows multiple
connections or requests to a server to be executed simultaneously which is important
when scaling applications. MongoDB is also invented to be used asynchronously, there-
fore it is compatible with Node.js applications.

Table 1. A popular web server task (reading a file on server and send the content as response
to the client) handled by PHP and Node.js

3
Node terminate the waiting time between handling requests and move on to the next
request as table 1 illustrates.

2.1.1 Node Module

Node module is similar to JavaScript libraries which consists of a package of functions


to be included in application when needed. Node has a variety of modules that offer
fundamental features for web applications implementation.
While developers can customize their own modules for personal project, Node has many
built in modules that can be used instantly without installation.
One of the most popular built-in modules is http module, which can be used to create an
HTTP client for a server.

var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.write('This is shown in client'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

Listing 1. A simple code in Node.js to create a server

Listing 1 demonstrates the usage of http module and „createServer‟ function to initiate a
server running on port 8080. A text string is shown in the client as a response.

2.1.2 Node Package Manager

Node Package Manager (NPM) offers two essential functionalities:

 Command line for performing NPM commands such as package installa-


tion and version management of Node packages
 Downloadable repositories for Node package.

In 2017, statistic showed that more than 350 000 packages are found in the npm registry,
make it the largest software repository on Earth. Due to being an open source and
having a basic structure, the Node ecosystem has prospered dramatically, and currently
there are over 1 million open-source free package, which facilitates development process
a lot. Beginning with being a method to download and manage Node dependencies, npm
has become a powerful means in front-end JavaScript.

4
There are two types of Node packages installation, globally or locally by the npm install
command. The package then is downloaded from the NPM registry and presented in a
folder named node_modules. The package is also added to the package.json file under
property dependencies. By using require function follow with the package name, it is
usable in the project as the example below in listing 2:

$ npm install <Module Name>

var name = require('Module Name');

Listing 2. Installation and usage of Node package

Package.json is an obligatory file in all JavaScript/Node project. It is a JSON format


file which displays pair value of names and versions of all the packages that required to
runthe project as well as other commands. Sometimes when a package got outdated, it
will show up by running the command „npm outdated‟. If those updates are main
releases, common „npm outdated‟ do not work because a core release usually comes
up with cru- cial changes which can cause the project trouble. In this case, Node
package „npm- check-updates‟ need to be installed globally and then running command
„ncu-u‟ will up- grade all the version noted in package.json. Now „npm update‟ is ready
to handle all the updates.

Figure 2. A screenshot of package.json file in E-commerce application

Figure 2 illustrates some Node package used in the application under dependencies property
such as body-parser, Braintree, cookie-parser, etc.

5
2.2 Express.js

Express is a micro and flexible prebuilt framework based on Node that can provide faster
and smarter solution in creating server-side web applications. Express is made of Node
so it inherits all Node‟s features like simplicity, flexibility, scalability and performance as
well. In brief, what Express does to Node is the same as Bootstrap does to HTML/CSS
and responsive design. It makes programming in Node a piece of cake and provides
developers some additional tools and features to improve their server-side coding. Ex-
press is literally the most famous Node framework so that whenever people mention
about Node, they usually imply Node combined with Express. TJ Holoway chuk
released Express the first time in 2010 and currently it is maintained by the Node
foundation anddevelopers who contribute to the open-source code.

Despite the fact that Express itself is completely minimalist, developers have pro-
grammed many compatible middleware packages to solve almost all issues in web de-
velopment. Express offers a quick and straightforward way to create a robust API with
a set of helpful HTTP methods and middleware.

2.2.1 Basic Routing

Routing determine the way how an application‟s endpoints (URIs) interact with client re-
quests. The basic syntax consists of an object as instance of Express and the corre-
spondent HTTP request method such as app.get(), app.post() to handle GET and POST
request respectively.

Routing methods take a callback function as parameter. The specified function is called
when the HTTP requests match the defined routes and methods.

var express = require('express')


var app = express()// create instance of express

//respond with 'hello' when a GET request is made to the route :/hello
app.get('/hello', function(req, res) {
res.send('hello') //response method
})
var callback1 = function(req, res, next) {
//
next()
}

6
var callback2 = function(req, res, next) {
//
next()
}
app.get('/multiple', [callback1, callback2])

Listing 3. Example of Routing functions

As can be seen from listing 3, routing method in line 17 has more than 1 callback function
as parameters. In this case, it is crucial to add „next‟ to each callback function arguments
and call it later in the body to switch control to the next callback. „next‟ function will be
discussed more in the next section.

2.2.2 Writing and Using Middleware

Middleware functions have the ability to approach request object, response object and
the „next‟ function in the application‟s request-response phase. Middleware execution re-
turn an output which could be either the final outcome or could be passed as an argument
to the next middleware until the end of the cycle. The ‟next‟ function belongs to the
Express router which starts the following middleware right after the current middleware
finished. If a middleware does not finish the req-res cycle, next() must be called to pass
control to the next one. Otherwise, the request will be suspended.

Figure 3. Middleware function components

Figure 3 illustrates middleware concepts in details.

7
An Express application is basically a sequence of middleware calls. The call orders is
based on the order which they are declared

Figure 4. Diagram of middleware execution order

Figure 4 explains that Express treats all middlewares in the same way so that the order
in which your route handlers and other middleware functions are written is exactly the
execution order.

2.3 MongoDB

MongoDB is a document-based NoSQL database used mainly for scalable high-volume


data applications and data involved jobs which does not work well in a relational model.
It is among the most popular non-relational database which emerged in the mid-2000s.
MongoDB architecture comprises of collections and documents replacing the use of ta-
bles and rows from traditional relational databases point of view. One of the most essen-
tial functionalities of MongoDB is its ability to store dynamic data in flexible BSON docu-
ments, which means documents sharing the same collection can have different fields
and key-value pairs, while data structure can be changed without any restrictions at any
time. Therefore, this removes the necessity of storing strictly structured data which is
obligatory in other relational databases and improves database operation speed
significantly. Indexing and aggregation offer robust method to access and work with data
easily. Whatever field in a document can be indexed, leading to a much better search
performance. MongoDB also provides numerous operations on the documents such as
inserting, querying, updating as well as deleting. With the diversity of field value and
strong query languages, MongoDB is great for many use cases and can horizontally
scale-out to provide storage for larger data volumes, make it stably be the most popular
NoSQL database globally.

8
2.3.1 NoSQL Database

There are big differences between the mechanism NoSQL databases store data and
relational databases do. NoSQL databases are differentiated based on their data model.
There are 4 main types:

 Document databases
 Key-value databases
 Wide-column databases
 Graph databases

They share one common thing which is dynamic schema and can scale easily with large
data loads and high user volumes. A popular misunderstanding is that NoSQL databases
do not handle relationship data well. While in fact, many developers believed that data
modeling relationship is easier for NoSQL databases due to the nested individual data
structure.

During the late 2000s, as a result of the considerable decrement in storage price, there
is no need to create a complicated data model just to avoid data duplication. NoSQL
databases took a big step forward and became a good option for developers and large
data volume applications.

Figure 5. Cost per MB of data overtime

As price of storage critically decreased as figure 5 demonstrates, the number of


applica- tions along with the data needed to store increased incredibly. Defining the
schema be- forehand for all those data is almost impossible. Therefore, NoSQL
databases provide developers flexibility to save a large amount of unstructured data.

9
2.3.2 MongoDB Atlas

MongoDB Atlas, which announced in 2016 by MongoDB creator team, is the cloud ser-
vice for storing data globally. It offers everything MongoDB provide without further re-
quirements when building applications, allowing developers to fully focus on what they
do best. With Atlas, developers do not have to worry about paying for unnecessary
things as they follow a pay-as-you-go standard.

MongoDB Atlas introduces a simple interface to get started and running. Basically, by
choosing instance size, region and any customized features needed, Atlas brings out the
suitable instance and includes it with the following:

 Built-in Replication: Atlas ensures constant data availability by providing


multiple servers, even when the primary server is down.
 Backups and Point-in-time Recovery: Atlas puts a lot of efforts to prevent
data corruption.
 Automated Update and One-Click Upgrade: users take advantage of the
latest and best features as soon as they are released due to Atlas auto-
mated patching.
 Various options for additional tools: users can freely decide on which re-
gions, cloud providers and billing options they prefer to use, making them
feel like customizing their own instances.

 Fine-Grained Monitoring: users are kept up with a diversity of organized


information, to let them know the right time to advance things to the next
level.

MongoDB Atlas is practical and reliable thanks to its integrated automation mechanisms.
With Atlas, it is unnecessary to concern about operational tasks as following:

 Supply and Configuration: Atlas gives clear instruction step by step to go


through the setup process, so developers do not have to think about what
aspect to choose even if they are beginners.
 Patching and Upgrades: Atlas is integrated with automatic upgrade and
patching, ensures user can reach latest features when they are released
as patching process takes just some minutes with no downtime.
 Monitoring and Alerts: database and hardware metrics are always visible
so users can foresee and prepare for any performance and user experi-
ence problems.

10
2.3.3 Mongoose

Mongoose is an Object Data Modeling (ODM) JavaScript-based library used to connect


MongoDB with Node.js. Mongoose provides a straight-forward, schema-based solution
to create your application data template. It handles data relationships, provides methods
to validate schema, and is used to render and represent between objects in MongoDB.

Mongoose schema is covered inside a mongoose model, and a specific schema creates
model. While schema and model are slightly equivalent, there is a primary differ-
ence: schema determines the document formation, default values, validator, etc.
while model is responsible for document-related operation like creating, querying, updat-
ing and deleting. A schema definition is simple, and its structure is usually based on
application requirements. Schemas are reusable and can include multiple child-sche-
mas. Schema applies a standard structure to all the documents in a collection. Moreover,
Mongoose provides additional features like query helper functions and business logic in
the data. For example, Mongoose can help connect database with the server and per-
form typical database operations for reading, writing, updating and deleting data. Mon-
goose removes the need of writing complicated data validations by providing schema
validation rules to allow only acceptable data to be saved in MongoDB.

2.4 React.js

React is an open-source front-end JavaScript-based library that specializes in building


user interfaces. It was originally created by a Facebook software engineer and first im-
plemented in newsfeed feature of Facebook in 2011 and followed by Instagram a year
later. Due to the minimal understanding requirement of HTML and JavaScript, React is
easy to learn and thanks to the support by Facebook and strong community behind it,
React expands its popularity and becomes one of the most used JavaScript library.

Figure 6. Number of package downloads with NPM per year of React, Angular and Vue
11
Figure 6 compares the number of package downloads with NPM among React and two
other popular frameworks - Angular and Vue. As can be seen, the number of React has
increased dramatically in popularity in the past few years and definitely has proven its
preference.

React works only on user interfaces of web and mobile applications. This equivalent to
the view layer of MVC template. ReactJS allows developers to create reusable UI com-
ponents as well as to create scalable web applications that can change data without
reloading the page. In addition to providing reusable component code, which means
reducing development time and lessening the risk of bugs and errors, React released
some key features that add to its appeal for developers:

 JSX (JavaScript Syntax extension)


 Virtual Dom
 Component

2.4.1 Component

React is all about component, which reflects the primary unit of every application. React
allow developers to divide the user interface into simple, independent and reusable

components. A developer can start with common tiny components that can be used re-
peatedly on several pages like navigation bar, button, input form etc. This is what reus-
ability means, which is a perfect way to reduce development time, so that developers
can concentrate on more crucial features and business logic. Then comes the turn of
wrapper components that include children components with internal logic. Each compo-
nent determines its own way how it should be rendered. A component can also be com-
bined with other components or nested inside higher order components. The develop-
ment process keeps going on like that until it reaches the root component which is also
the application. As a result, this approach guarantees the application consistency and
uniformity which make it easier for maintenance as well as further codebase growth.

There are 2 types of components, functional component and class component.

2.4.1.1 Functional components

Functional components are completely presentational and basically are written under the
form of a JavaScript function that can receive some props (properties) as argument and

12
return a React element. Thanks to their predictability and straightforwardness, functional
components always make the same result given the same props. Therefore, developers
tend to pick functional components whenever possible. Stateless component or dumb
component is all functional component‟s name as it comes from the natural fact that
functional components do not manage any state and their task is simply output user
interface elements.

Function Hello (props) {


Return <h1>Hello {props.name} </h1>;
}

Listing 5. A functional component

Listing 5 illustrates an example of a functional component which takes „name‟ as a props


and return a JSX.

2.4.1.2 Class components

ECMAScript6 class syntax are utilized to write class-based components, the one which
not only can return JSX but also can dispatch action, fetch data, handle events and have
local state. Class components offer more functionalities by inheriting from React.Com-
ponent class. They can access all additional lifecycle methods from their parent class
and manipulate code at particularly moment during the process. While functional
components are dumb and stateless, class components are said to be smart and stateful
thanks to being a container of the local state, internal logic and other children compo-
nents. Therefore, a class component should be considered in case if there is a need for
local state management or lifecycle method as well as some logic. Otherwise, a func-
tional component is more suitable.

Figure 7. A class component

13
As figure 11 summarizes, all React.Component subclasses have to define render func-
tion. A constructor function is implemented here because there is initial state and inside
constructor, super(props) should be called first out of all statements. If not, this can lead
to errors because of undefined props.

14
Chapter 3

3 Application Implementation

A prototype version of the e-commerce application was created to apply the study of
MERN stack as well as to understand how they contribute to the whole entity in web
development.

3.1 Application requirements

Typically, a (business to customer) B2C e-commerce web application has two types of
users, which are admin and user. Admins are responsible for some specific management
tasks such as creating, updating and removing the products from the database as well
as managing user orders. A user is able to browse and read product‟s information dis-
played in the application. He can also add the product to the shopping cart and perform
the payment for that product. While some resources and web routes are public, the oth-
ers can only be accessed by an admin or a signed in user.

By interviewing and researching some normal customers and business owners, the au-
thor figured out what different type of user want from the application, what features they
think are necessary for an e-commerce web application. Based on that, a list of user
stories is shown below to illustrate some of the required functionalities for this application:

 As a user, user want to create an account for himself


 As a user, user want to update his profile
 As a user, user want to surf through all the products
 As a user, user want to see product information such as category, price,
name, review, picture, etc.
 As a user, user want to add many products to the shopping cart and is able
to view the cart
 As a user, user want to delete products from the cart
 As a user, user want to modify the quantity of products inside the cart
 As a user, user want to pay for the products in the cart
 As an admin, admin want to add product to the database
 As an admin, admin want to remove product from the database
 As an admin, admin want to update product to the database

15
 As an admin, admin want to add category to the database
 As an admin, admin want to manage user orders

3.2 Application development

This section is dedicated to demonstrate the functionalities development process from


back-end to front-end of the e-commerce application. Due to the limited scope of this
thesis, it is not able to mention all the files or describe every step in the project into
details, but it aims to discuss precisely about all fundamental and important parts that
needed to implement the MERN application. Basic concepts of any third-party libraries
or module are also explained along the way. The project structure is divided into 2 folder,
ecommerce and ecommerce-front which contain the source code of back-end and front-
end respectively.

3.2.1 Back-end development

3.2.1.1 Basic setup

The very first thing to do is to set up an Express application by creating an app.js file,
which is the entrance file of the project, where some of the necessary middlewares and
node packages are stored. Express instance is defined under app variable.

Figure 8. A screenshot of app.js file from the e-commerce application

The purpose of those middlewares in figure 8 are explained as below:

16
 Mongoose is discussed in chapter 2.3.3
 Morgan logs the request details
 bodyParser unzips the whole body part of an incoming request and makes
it available on req.body object.
 cookieParser deconstructs cookie header and populates all the cookie in
req object under property named cookies.
 dotenv let developers use environment variable by accessing .env file

The following step is setting up database connection. MongoDB atlas is used due to
various advantages it brings in for the project as chapter 2.3 summarizes above. Since
Atlas is an online database service, no installation is required. By accessing MongoDB
Atlas official site and following instruction there, a cluster is created with the author‟s
personal choice of cloud provider and region followed by a connection string which is
saved as MONGO_URI variable in the environment file. It is then used by mongoose to
connect to the database. When the connection is successful, „DB Connected‟ is dis-
played in the terminal. Otherwise, a message telling the connection error is printed out
as Figure 9 below explains.

Figure 9. A code snippet of how to connect to the database.

The back-end folder is structured by 3 main sub-folders: models, routes and controllers.
While models contain all the mongoose schemas that are based on application require-
ments, routes define all the API routes and controllers comprise of the logic that needed
to be execute after each incoming request match with the corresponding route.

17
3.2.1.2 Mongoose Schema Creation

There is a total of 4 schemas in this application: category, order, product and user. Each
mongoose schema represents for a document structure User schema is written first be-
cause user model is needed to handle authentication and authorization.

User schema

As can be seen from figure 10 below, a user schema has 3 required properties called
name, email and password. Role property is set to 0 by default as it means this is a
normal user. By manually changing the role value to other (in this application: 1) the user
becomes an admin. The user model only accepts defined properties in the schema to be
added to the database. While history shows an array of purchases that user used to
make, timestamps displays the time of creation and modification of a user object.

Figure 10. A screenshot of User schema

18
For security reasons, real password is not saved in the database but an encrypted one,
therefore the author used Crypto, which is a Node module to hash the password while
combined with a tool called mongoose virtual.

A Mongoose Virtual is a property that is not stored in MongoDB. Mongoose Virtuals,


which has getter and setter methods are great option for computing properties.

Figure 11. Usage of Mongoose Virtual in the application

Figure 11 demonstrates how „hashed_password‟ is created based on Mongoose Virtual.


Firstly, Virtual creates a property named password for user object. When a new user is
signed up, the value of „password‟ property from the req.body is set to the virtual property
and is passed to setter function as an argument. Then „password‟ is encrypted and set
to „hashed_password‟ property. A function is also assigned to userSchema method ob-
ject to create an authenticate method which compare the encrypted input password with
the hashed one to verify the user.

19
Product schema

A product schema is structured as figure 12 below. It has all the properties that any e-
commerce product may need, like name, description, price, quantity, category, etc. Sold
field is set to 0 as default value and is incremented after each user purchase. One differ-
ent with the user schema above is that category field has a type of ObjectId while the
„ref‟ option indicates which model to refer to during population (in this case category
model). This illustrates the relationship between product model and category model and
by using populate method, category data is no longer its original _id but replaced with
mongoose document retrieved from the database.

Figure 12. ProductSchema structure

While user schema and product schema look complex, category schema is pretty simple
and straightforward with only name and timestamps field.

3.2.1.3 Authentication with JWT

JSON Web Token (JWT) is a standard that defines a compact and self-contained way to
transmit data securely between client and server as a JSON object. Tokens can be

20
transferred through an URL or a HTTP request header easily thanks to its compact size
while self-contained feature let JWT comprise all the necessary user information. Data
inside a JWT is verified and reliable because it is signed with a secret key or a public
private key pair. Moreover, the signature also confirms that only the party holding the
private key have signed it.

Figure 13. How JWT works in authorization

Authentication is the most popular use case of JWT. After a user signs in, the authoriza-
tion is granted and a JWT is created by the application and sent back to the user. By that
time, all following requests made by user will contain the token in the authorization
header with Bearer schema. The server will check for a valid token, and if it is available,
the user is allowed to access protected routes, services and resources that require that
token. As JWT is self-contained, all needed data stay there, leading to less works toward
the database. This whole process is analyzed in figure 17 above

21
Figure 14. Usage of JWT in E-commerce application to sign in user

Figure 14 demonstrates how JWT is implemented in the „signin‟ controller method. This
method is executed when there is a POST request to the route „/api/signin‟. Firstly, user
credentials are retrieved from the request body and set to the corresponding variable.
Then database looks for the user with that email and checks if the password is matched
with hashed password. If yes, a signed token is generated with user ID and a secret
random string which is saved in environment file. This secret string key is needed for
security reasons since tokens are user credentials. Then the token is attached in cookie
with an expiry time and is returned with user data as json format to the client.

3.2.1.4 Routing and API Documentations

Data distribution and sharing between two or more systems has always been an essen-
tial aspect of software development. Taking into account a case when a user search for
some books of a specific category, an API is called and the request is sent to the server.
The server analyzes that request, performs necessary actions and finally, user gets a list
of books as a response from the server. This is the way how REST API works. An API
stands for Application Programming Interface, which is a set of rules that allows two
applications or programs to interact with each other.

22
REST determines how the API looks like. It stands for “Representational State Transfer”
-an abstract definition of the most popular web service technology. REST is a way for
two computer systems to communicate over HTTP in a similar way to web browsers and
servers. It is a set of rules that developers follow when they create their API.

Table 2. Product related API

Method Route path Description

GET api/product/:productId Return a product with the given ID un-


der json format

POST api/product/create/:userId Create a new product and save it to da-


tabase, return a json object of that
product. Required to be admin and be
authenticated

DELETE api/product/:productId/:userId Remove a product with the given ID


and return a json message object. Re-
quired to be admin and be authenti-
cated

PUT api/product/:productId/:userId Update a product with the given ID and


return updated product under json ob-
ject. Required to be admin and be au-
thenticated

23
GET api/products Return a list of products under json for-
mat

GET api/products/search Return a list of products based on


search query under json format

GET api/products/related/:productId Return all the products with the same


category as the given ID product

Table 2 above illustrates all the product related API routes with corresponding method
and description in brief. As can be seen, only user with admin role can perform operation
like creating, deleting and updating to a product. Other public routes can be accessed
wherever and by whatever kind of user even without a signed account.

Figure 15. Usage of router.param method

The author also makes use of router.param method as most of the product API routes
above have a parameter (productid, userId) inside. Router.param finds the product with
that ID and populate its information to request object under product property as figure 15

24
summarizes. This is also applied to other routes which have userId, categoryId and or-
derId as well since it facilitates the logic implementation.

3.2.1.5 API Testing with Postman

At this moment of the development process, the front-end is not available yet so a third-
party tool called Postman is used to handle API testing.

Figure 16. A screenshot of Testing with Postman

As can be seen from figure 16, a GET request has been called to the route „api/catego-
ries‟ and been successfully handled. Since this is a public route and categories is not
protected resource, no authorization token in the header is needed. As a result, an array
of json object containing all the categories is returned. Each category object includes all
the properties defined in Mongoose schema like name, timestamps and auto generated
ID.

25
3.2.2 Front-end development

3.2.2.1 Basic setup and Routing

Unlike back-end is performed with multiple technologies, front-end development is han-


dled by only React.js. It is not impossible to set up a React application from scratch, but
this process includes of many intimidating and time-consuming steps, such as setting up
Babel to convert JSX to compatible JavaScript that old browser can understand and
configuring Webpack to bundle all the modules. Fortunately, Facebook has developed
Create React App node module for quickly scaffolding a React template, which saves
developers from all those complicated configurations. Create React App not only gener-
ates a boilerplate with core structure for a React application but also takes care of some
build script and development server.

After running command „npx create-react-app‟ to generate a template, bootstrap – the


most popular CSS framework is added to minimize styling tasks from scratch since the
author want to focus on the development part using MERN stack.

Then Routes.js file is created with the sole purpose of including all the route paths with
their corresponding components by using a package called react-router-dom. Route
component is then rendered by ReactDom as the root component of the application.

Figure 17. A screenshot of Routes.js file, with BrowserRouter wraps around Switch and Route

26
Figure 17 summarizes all the route paths and the component to be render when that
route is accessed. For example, any kind of user can go to public route like „/shop‟ to
access Shop component, but only authenticated user can see Dashboard or Profile com-
ponent as they are protected routes.

There is a total of three main types of components in React Router:

 routers, like <BrowserRouter> and <HashRouter>


 route matchers, like <Route> and <Switch>
 navigation, like <Link>, <NavLink>, and <Redirect>

Router component is the wrapper of React Router application. BrowserRouter is mainly


used for web-based projects. Router component must be rendered as the root element.

Switch and Route are route matchers. When a <Switch> is rendered, it finds the
<Route> element whose path is similar to the current URL. When a <Route> is found, it
renders that <Route> and ignores the rest. This means <Route> with more specific (usu-
ally longer) paths should be written before less-specific ones.

One essential thing to consider when setting up Route is that a Route path matches
the beginning of the URL, not the whole URL. Therefore a <Route path="/"> will match
every URL. That is why <Route> should be located last in the <Switch>, otherwise
<Route exact path="/"> can be used to match the whole URL.

3.2.2.2 User Authentication

Sign up Component

Although some main pages of this application like Home page, Shop page do not require
the user to sign up in order to enhance user experience, if users want to make a pur-
chase, they have to sign up and log in to their account first. Below is a simple user inter-
face to sign up new users.

27
Figure 18. A screenshot of the Signup page

Figure 18 displays a web page with shared navigation bar and layout. Right below is the
signup form which includes some inputs for name, email and password with a submit
button. Bootstrap class „form-group‟ is applied to facilitate these styling tasks. In this
component, beside the state of each input field there are error and success state which
determine if some alerts should be shown up when user fail or succeed to sign up.

Given the user put in correct data and press submit, fetch method is used to send a
POST request with user data under json format in the body to the back-end API „api/sig-
nup‟. After validation process, a new instance of user model is created based on req.body
and is saved into the database. The server then returns a json file containing user data
without hashed password back to the client. Finally, a success alert is shown up and is
redirecting the user to the sign in page.

Sign in Component

The sign in component is quite similar to the sign up one except the data flow when the
user press submit button. As summarized in chapter 3.2.1.3, after the server handled the
POST request from the client, a token is signed and sent back to the client along with

28
user information. Those data then are passed to authenticate function and stored in the
local storage as jwt.

export const authenticate = (data, next) => {


//check if we have window obj
if (typeof window !== undefined) {
localStorage.setItem('jwt', JSON.stringify(data))
next();
}
};

export const isAuthenticated = () => {


if (typeof window == undefined) {
return false;
}
if (localStorage.getItem('jwt')) {
return JSON.parse(localStorage.getItem('jwt'));
} else {
return false;
}
};

Listing 6. A snippet code to store user information in local storage.

Figure 19. A screenshot of Local Storage

As shown in listing 6 and figure 19, user data can be saved in local storage and therefore
can be retrieved from there. By using JSON.parse(), user data is converted from json
string back to JavaScript object and can be used to find out the user role (user or admin).
Based on that signing the user in to the corresponding dashboard.

29
3.2.2.3 Dashboard Component

Admin Dashboard

Figure 20. User interface of Admin Dashboard

Admin dashboard is accomplished with this component as can be seen in figure 20. It
consists of 2 section elements which both applies Bootstrap class Card. All admin infor-
mation is shown on the right side while some admin actions like creating category and
product, viewing and managing order are on the left. By clicking on tasks link, admin will
be navigated to the matching component where he/she can create a category or a prod-
uct. The admin also has the ability to view orders and manage them, for example setting
the order status from processing to shipped or delivered. Moreover, ManageProduct
component enables the admin user to modify products or even delete them from the
database.

User Dashboard

Generally, the user dashboard component is quite similar to the admin one. Since the
user have less power than an admin, there is fewer actions for a user to perform.

30
Checking out in the Cart page or updating their profiles are the two only user‟s tasks, as
visualized in figure 21.

Figure 21. User interface of User Dashboard

Unlike admin dashboard, user‟s purchase history is presented under his/her personal
information. This list provides a precise look of order history, such as product name, price
and the time it was performed.

3.2.2.4 Home Component

UI Description

Home page, which is the main page of this application is demonstrated by Home com-
ponent. This component is accessible through a public empty URL. It plays an important
role in an e-commerce application.

31
Figure 22. User interface of Home component

An overview of the Home page is described in figure 22. Some of the most fundamental
functionalities of an e-commerce application are shown in this component. As can be
seen, there are 2 lists of products. One is for best sellers, which are those products with
highest sold property, the other is new arrivals, meaning that the createdAt property is
closest to the current time. Each product is presented by a Card component which ap-
plies a Bootstrap class called „card‟. The card header shows the product name while
other information like product image, price, category, timestamps are set in the card
body. In stock feature depends on the quantity property of each product. In the end
comes 2 buttons for user to view each product in detail and to add to cart for payment
and purchase. There is also a search engine rendered by the Search component on top

32
of the page right below the shared layout. Here user can search product based on cate-
gory and by text in name.

3.2.2.5 Shop Component

A shop page enables user to sort products based on category and price.
UI description

Figure 23. User interface of Shop component

Figure 23 illustrates the Shop component with shared layout and a navigation bar like
other pages, followed by some filter features on the left side and filtered results on the
right side of the page. Card component is again utilized to render products. Category
filter is handled by checkbox component while price filter is presented by radio-box com-
ponent.

3.2.2.6 Cart Component and Payment Gateway

UI Description

Cart page is the last page users have to go through to get the purchase done. Beside
some common shared components, there are a Card component which renders the prod-
uct that users want to buy and a check-out component that demonstrates the total
amount, delivery address and a form to fill in with payment information. This Card com-

33
ponent inside Cart is slightly different than the one in Home or Shop component. It has
a remove button to delete the product from the cart and an input field where users can
increase or decrease the quantity of product in the end. Cart component is visualized
clearly in figure 24 below.

Figure 24. User interface of Cart component Figure

34
Chapter 4

4 Discussion

This section illustrates the evaluations of the e-commerce web application. There is also
an in-depth discussion about possible improvements that can be done in the future.

4.1 Application Evaluation

In the end, a prototype version of the e-commerce application simulating an online


bookstore was developed successfully with the aid of 4 main technologies in the MERN
stack along with numerous other Node modules. This application is easy to use and user-
friendly as it takes only a couple of clicks from the Home page to get the purchase done.
Users can sign in, edit their profiles, check purchase history and the most important fea-
ture – to search for their favorite book and pay for it. This application offers 2 type of
product filtering, the first one is based on a search engine which takes user input and the
other one is dependent on category and price of the products. Admin users have all the
same functionalities, added some more features such as creating product and managing
orders. Payment gateways also works well as it is already tested in sandbox account.

Figure 25. User Interface of Add-product component

35
Figure 25 provides a view of add-product page, which is only accessible by admin user.
Beside text field, there have also 2 dropdowns option to choose category and shipping
method and a form to upload a book picture.

User orders are saved in the database and are rendered as soon as the Order compo-
nent mounted. Each order contains all the user information and its status can be updated
by the admin as can be seen in figure 26.

Figure 26 User interface of Order component

Generally, the outcome application achieved all the requirements in case of functionality
for an end-to-end e-commerce application which is visualized from the beginning and it
aims to be suitable for small businesses such as an online bookstore.

4.2 Further Improvement

Although this application meets all the feature requirements as planned, there are still
some aspects needed to improve. Concerning the Manage Product page in figure 32,

36
the main improvement would be some CSS styling as the update button are in a mess.
Color design should also be taken into account to enhance the user experience.

Figure 27. User interface of ManageProduct component, where admin can update or delete a
product. It also shows the total number of products in the database.

Despite of all the fundamental and useful implemented functionalities in the application,
these features in the following list can be considered for further development:

 User sign up using Gmail or Facebook


 Email notification after successful payment
 Each product has a review and rating section

Eventually, in order for this e-commerce application to switch from development mode
to production mode, testing and deployment have to be handled appropriately as the
development process may have some unseen bugs.

37
Chapter 5

5 Conclusion

The goal of this thesis was to study different characteristic of each technology in the
MERN stack and develop a full-stack e-commerce web application based on it. It took
the author a considerable amount of time to research and study in-depth each modern
technology in order to carry on the web application. All the technologies that comprise
of the MERN stack were discussed precisely, from fundamental concepts to advanced
features as well as their usage in the application to ensure the reader understand about
this paper. The thesis also provided all the steps needed in the development process to
implement an e-commerce application.

The application was successfully developed at the end. A fully functional end-to-end e-
commerce application featuring an online bookstore was released and aimed to help the
startup develop their business strategy in general. This application was meant to solve
the problem that is mentioned in the first section of this thesis: to help the book retailer
startup become more widely known and gain more potential customers. People and book
lovers also have one more source to expand their knowledge.

Overall, the thesis can be used as a tutorial or documentation of the MERN stack in
particular or full-stack web development in general. By researching and studying this
paper, the author gained much more useful knowledge and understood why MERN stack
is rising its popularity and plays a leading role in web development recently. Although
the application still has some drawbacks and needs more further improvements, both in
styling issue and new features, it is a combination of one of the most widely used web
stack technology with one of the most emerging business ideas nowadays – ecommerce.

38
References

1 Hyperion Development (2018). Everything you need to know about the MERN
stack. Available at: https://blog.hyperiondev.com/index.php/2018/09/10/every-
thing-need-know-mern-stack/

2 Node.js Documentation. The V8 JavaScript Engine. Available at:


https://nodejs.dev/learn/the-v8-javascript-engine

3 Priyesh Patel, Freecodecamp (2018). What exactly is Node.js? Available at:


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

4 w3school. Node.js Introduction. Available at:


https://www.w3schools.com/nodejs/nodejs_intro.asp

5 TutorialsTeacher. Node.js Module. Available at: https://www.tutori-


alsteacher.com/nodejs/nodejs-modules

6 Tutorialspoint. Node.js - NPM. Available at: https://www.tutori-


alspoint.com/nodejs/nodejs_npm.htm

7 Node.js Documentation. An introduction to the npm package manager. Available


at: https://nodejs.dev/learn/an-introduction-to-the-npm-package-manager

8 TutorialsTeacher. Node Package Manager. Available at: https://www.tutori-


alsteacher.com/nodejs/what-is-node-package-manager

9 Node.js Documentation. Update all the Node.js dependencies to their latest ver-
sion. Available at: https://nodejs.dev/learn/update-all-the-nodejs-dependencies-
to-their-latest-version

10 Node.js Documentation. The Node.js Event Loop. Available at:


https://nodejs.dev/the-nodejs-event-loop

11 Impressico Business Solutions. Advantages of using Express.js. Available at:


https://www.impressico.com/2015/10/06/advantages-of-using-express-js/

39
12 Mozilla. Express/Node introduction. Available at: https://developer.mozilla.org/en-
US/docs/Learn/Server-side/Express_Nodejs/Introduction

13 Express Documentation. Routing. Available at: https://ex-


pressjs.com/en/guide/routing.html

14 Express Documentation. Using middleware. Available at: https://ex-


pressjs.com/en/guide/using-middleware.html

15 Derick Bailey (2016) In what order does my Express.js middleware execute?


Available at: https://derickbailey.com/2016/05/09/in-what-order-does-my-express-
js-middleware-execute/

16 Decode Web, Medium (2019) What is MongoDB? Available at: https://me-


dium.com/@decodeweb/what-is-mongodb-7693e2f2f4f6

17 DB-engines (2020) Complete Ranking. Available at: https://db-en-


gines.com/en/ranking

18 MongoDB inc. NoSQL Databases Explained. Available at: https://www.mon-


godb.com/nosql-explained

19 MongoDB inc. Data Modeling Introduction. Available at: https://docs.mon-


godb.com/manual/core/data-modeling-introduction/

20 MongoDB inc. Data Model Design. Available at: https://docs.mongodb.com/man-


ual/core/data-model-design/

21 javaTpoint. MongoDB Atlas. Available at: https://www.javatpoint.com/mongodb-


atlas

22 Nick Parsons, Medium (2017). MongoDB Atlas – Technical Overview & Benefits.
Available at: https://medium.com/@nparsons08/mongodb-atlas-technical-over-
view-benefits-9e4cff27a75e

23 Nick Karnik, freecodecamp (2018) Introduction to Mongoose for MongoDB. Avail-


able at: https://www.freecodecamp.org/news/introduction-to-mongoose-for-mon-
godb-d2a7aa593c57/

24 Jamie Munro, envatotuts (2017) An Introduction to Mongoose for MongoDB and


Node.js. Available at: https://code.tutsplus.com/articles/an-introduction-to-mon-
goose-for-mongodb-and-nodejs--cms-29527

40

You might also like