Document Edited
Document Edited
MAJOR PROJECT
ON
E-SHOP WEB APPLICATION
This is submitted in partial fulfillment of the requirement for the degree
of
Bonafide certificate
Internal Guide
Acknowledgement
1. ABSTRACT
2. INTRODUCTION
3. OBJECTIVES
4. SCOPE
7. DESIGN DIAGRAMS
8. DATABASE STRUCTURES
(SAMPLE)
11. CONCLUSION
0|Page
ABSTRACT
The web development industry has grown significantly with the evolution of technology.
devices with the Internet and real-time capabilities have made performance essential.
Unfortunately, despite their general use and long history of developing and maintaining
traditional technology, some fail to meet today's customer performance expectations. The
E-commerce has exponentially risen over the last decade, offering more benefits and
conveniences than traditional businesses. Furthermore, the COVID-19 era has irreversibly
changed how businesses interact with customers, allowing merchants to approach clients
online bookshop.
This project will demonstrate and comprehend each MERN stack technology's essential
concept before building a functional E-commerce web application to help small companies
formulate their business strategy. The functionality and browser capabilities tests were all
conducted on various platforms. The outcome was satisfactory since the web application
constructed and deployed. Additionally, the application's results and potential enhancements
were discussed. The thesis can be utilized as a reference on the MERN stack, aimed at
1|Page
INTRODUCTION
1. PROBLEM DEFINITION: -
Nowadays, technology is growing incredibly fast. The rapid innovation of hardware devices makes
software technologies advance as well, automatically taking the place of old technologies. Because of
the significant expansion in the number of electronic devices that use the Internet and real-time
features, performance is key. By tradition, web development has been carried out by technologies such as
JAVA servlets, ASP.NET or PHP. While those technologies are quite widespread and have good
features with many years of development and are supported by a large community, they still have some
limitations concerning today’s need, which is performance. The MERN stack (MongoDB, Express,
React and Node) with their simplicity and uniformity, has been recently developed to become a better
solution for this performance issue.
The objectives of this thesis were to illustrate and understand the fundamental concepts and usage of
each technology in the MERN stack, as well as their compatibilities and advantages as a complete
stack in web application development. The thesis achieved that goal by utilizing these modern
technologies and implementing a web application. The idea of this web application was for a startup
run by the author’s parents as they decided to open a book retail store. By researching, the author
realized how e-commerce an enormous platform is emerging at an extraordinary speed over the last
decades all over the world and providing more advantages and conveniences as compared to physical
stores. E-commerce has changed permanently the way businesses and consumers interact, which allows
users to connect with their favorite shops and brands whenever and wherever they want and also helps
stores to more actively approach consumers. It is believed that the growth of e-commerce for the next
incoming years is increasing beyond measure rate with the release of modern technologies.
Understanding this need, the author’s solution was to create an e-commerce web application as an
online bookstore in order for the startup to develop its business strategy.
This document structure was organized as follows. The first section brought in the goal of the thesis and
the technologies used. Next, essential concepts and theoretical background of each technology in the
stack were introduced along with the example, followed by the third section which demonstrated
carefully and thoroughly the application development process, from back-end to front-end. In the end,
this paper provided a discussion of the project with further improvements and gave a conclusion about the
final product.
2|Page
OBJECTIVES
The ‘Online E-commerce Web application’ Services department strives to provide
solutions to develop and transfer easy and efficient ways in the digital age and to help reduce
human pressure and time. To help support shop collections, digital initiatives, and external
partner institution digital projects, it provides services that include the digitization of
analogue objects, metadata management, digital preservation, and discovery and
access of digital collections. “E-SHOP” is a web application written for all operating
systems, designed to help users maintain and organize shop virtually. This software
is easy to use for both beginners and advanced users. It features a familiar and well-
thought-out, attractive user interface, combined with strong searching Insertion and reporting
capabilities. The report generation facility of the shop system helps to get a good idea of
which are the various items brought by the members, making it users possible to get the
product easily. The ‘Online E-commerce Web application’ Services department strives to
provide solutions to develop and transfer easy and efficient way in the digital age and to help
reduces human pressure and time. To help support shop collections, digital initiatives, and
external partner institution digital projects, it provides services that include the digitization of
analogue objects, metadata management, digital preservation, and discovery and access of
digital collections. “E-Shop” is a web application written for all operating systems,
designed to help users maintain and organize shop virtually. This software is easy to use for
both beginners and advanced u s e r s . It f e a t u r e s a f a m i l i a r a n d well-thought-out,
attractive user interface, combined with strong searching Insertion and reporting
capabilities. The report generation facility of the shop system helps to get a good idea of
which are the various items brought by the members, making it users possible to get the
product easily.
3|Page
•To develop a database to store information on products.
2. THEORETICAL BACKGROUND: -
4|Page
application layer with NodeJS and Express, and database tier provided by MongoDB.
5|Page
success as the world’s most popular NoSQL database.
Document Oriented: All the data is kept in fields containing a clear structure with
key-value pairs rather than rows and columns, which provides more flexibility
than RDBMS.
Scalability: The horizontal scalability from MongoDB was offered through sharding,
which refers to the process of distributing data across numerous servers. By
utilizing the shard key, a significant quantity of data is divided into data chunks,
and these data chunks are equally spread among shards that involve multiple
physical servers. Moreover, it will add new machines to the existing database.
Replication: With the benefit of replication, MongoDB enables high availability and
redundancy by producing several copies of data and storing them on a separate
server to protect the database against hardware failure, ensuring that the data can be
recovered from another if one server fails
6|Page
3.3 EXPRESS: -
Representing the letter “E” in the MERN stack, Express is a lightweight and versatile
web application framework built on top of NodeJS. Thanks to the large community of
support, it includes a rich collection of functionalities for developing web and mobile
applications. Even though many support packages along with the functionality for
better software creation, Express does not affect the performance of NodeJS.
Based on the GitHub repository, Express was established on May 22, 2010, by T.J.
Holoway Chuk. After that, Strong Loop acquired the project management rights in
June 2014 until IBM owned the company in September 2015. Then, in January
2016, the NodeJS Foundation took over the management of Express, and Express is
now the primary function of the NodeJS platform.
Express.js is a routing and middleware framework for managing the many routings’
options fora website. It operates between the request and response cycles. Middleware
is invoked after the server receives the request and before the controller actions
transmit the response. One or more pieces of middleware are executed to perform
tasks, such as authorizing requests or parsing request content. Express applications are
composed of a sequence of middleware function calls. Typically, the first middleware
executed to process the request initiates the task pipeline. The initial middleware can
either complete the request and provide it to the users or call the subsequent
middleware to continue the request. The same approach will be continued until the
pipeline's last middleware takes the result of the preceding middleware as input.
3.4 REACT: -
React, representing the letter ‘R’ in the MERN stack, focuses on creating the View
Layer, which is well-known for all visible parts of the page of an application. React is
7|Page
a multi-purposed, open-source JavaScript library used for building user interfaces
based on UI components.
Since React was established to cope with sophisticated, large-scale user interfaces
combined with real-time dynamic data and data binding, it has been steadily improving
its single-page application development and frontend utilities for programmers of all
levels.
Compared to other popular libraries and frameworks such as jQuery, Angular, and
VueJS, React is considered the most popular framework for web development. Along
with offering reusable component code, which reduces development time and the
likelihood of bugs and errors, React introduced many essential characteristics that
contribute to its developer appeal, which are discussed below.
JSX: -
JSX (JavaScript XML) is a syntactic extension to JavaScript that is similar to HTML.
Because JSX optimizes the translation to standard JavaScript and leverages its full
power, it is much faster than the regular one. Even though React does not need the
usage of JSX to construct React-based applications, it is suggested as it simplifies the
development for developers whenever markup components and binding events are
required. Rather than dividing markup and logic into different files, JSX enables
developers to generate cleaner and more manageable codebases for their websites by
combining rendering logic and user interface logic in the same components.
VIRTUAL DOM: -
Virtual DOM (or VDOM) is an abstract representation of DOM (Document Object
Model), and its solutions are constructed on top of the regular DOM. DOM represents
the UI of the program, and its model portrays the document as a collection of different
nodes and objects to interact with the structure, layout, and content of the website
8|Page
through programming languages. Figure 3 below indicates an example of the DOM
structure.
While regular DOM manipulation is slow due to the re-rendering of both the updated
element and its children after getting new data, the Virtual DOM renders only the
components that need updating, which fastens the rendering process and increases the
performance. To further understand why Virtual DOM is fast and practical, the
functionality of Virtual DOM must be discussed. The state of the DOM tree hierarchy
is stored when Virtual DOM is utilized to render a page. Instead of constructing a new
tree, a diffing approach is employed when UI modifications are necessary. At that
point, the React library employs the Virtual DOM, which allows it to do the
calculations inside this domain without involving the actual DOM. Therefore,
whenever a component's state changes, React keeps track of it and updates.
The Virtual DOM tree by comparing the current version to the prior one. This
comparison employs a diffing algorithm to reduce the number of DOM
9|Page
operations/refreshes, leading to considerable boosting speed. The whole procedure
is titled Reconciliation.
Figure 4. The difference between Virtual DOM and real DOM update process
COMPONENTS: -
Components are the primary concept of React, which encourages developers to separate
complicated user interfaces into reusable and independent parts. React components are
10 | P a g e
classified into two types: class-based components and functional components. The
functional component is considered the most straightforward method to construct as it
can be implemented as a JavaScript function to return JSX. The class-based component is
constructed using the ECMAScript6 class syntax combined with the built-in React library
class “Component”.
Components can refer to one another, which means one component can be a parent
component containing several child components with no restriction on the amount of
complexity. Moreover, both functional and class-based components adhere to one strict
rule assigned by React: all React components must be pure functions in which their props
are immutable. Props, which stands for Properties, are a collection of inputs passed as
parameters to a component, while pure function depicts the state in which the function
performs the logic without affecting the arguments. As a result, a React component
behaves like a pure function while respecting its inputs and rendering the same result for
the same props.
HOOKS: -
Prior to version 16.8, the majority of React components were class-based as class-based
components offer life-cycle methods for component state management. Since version
16.8, however, React has introduced a new notion called Hooks, which provides a new
method to leverage state and other React capabilities inside a functional component. By
using Hooks, a component's stateful logic can be isolated, tested separately, and reused
without affecting the component hierarchy. In addition, Hooks enables the developer to
break down a component into separate functions based on the relationship instead of life-
cycle methods.
There are two built-in React hooks that should be discussed. First, the State hook, commonly
known as the use State hook, enables component-level state management. It hooks into
React's state by creating a state variable that React maintains. useState hook accepts and
11 | P a g e
returns two results: the current state and a function to alter it. The component state can be
efficiently initialized, utilized, and modified using the useState hook. The second hook is the
Effect hook, also known as the use effect hook. useEffect hook assists programmers in
managing component life cycles. The difficulty of separating related functionality and data
into several class life cycles, such as componentDidUpdate, componentDidMount, and
componentWillUnmount, has been thoroughly addressed by Effect Hook. A React
component can support multiple effects to isolate data manipulation issues.
3.5 NODE: -
12 | P a g e
Node package manager (npm): -
Node package manager (NPM) is the NodeJS default package manager for
applications, and it is utilized to maintain all the NodeJS packages and modules
along with the command line client npm. Therefore, it facilitates time-consuming
manual tasks by automating managing third-party packages, allowing developers to
spend more time on the development process.
NPM was first published on January 12, 2010, by Isaac Z. Schlueter. It is installed
alongside NodeJS and is utilized to install the required packages and modules in the
NodeJS project. It is currently the world's largest software registry, with approximately
two million packages at the end of APRIL 2024.
3.5 MONGOOSE: -
Mongoose is an object document mapping (ODM) library that is utilized for facilitating Node and
MongoDB development. It is responsible for managing data relationships, performing schema
validation, and serving as a middleman between objects in code and object representations in
MongoDB. In addition, Mongoose offers multiple methods and functions that effectively facilitate
communication between NodeJS and MongoDB. Figure 6 below illustrates the relationship between
Mongoose, NodeJS, and MongoDB.
As shown in Figure 6, Mongoose is utilized to create the interaction between Node and MongoDB
through object mapping. After that, Mongoose forms the connection with MongoDB using a Mongo
Driver. Therefore, the relationship between Mongoose, NodeJS, and MongoDB ensures data
capabilities.
The first step in getting started with Mongoose, like with other ODM libraries, is to create a schema. As
Mongoose's documentation page described, a schema specifies the data structure and property casting,
along with the following techniques: instance methods, compound indexes, static Model methods, and
middleware. Once the first stage is finished, the developed schemas will be utilized to map to MongoDB
collections and shape the data documents included inside each collection. The second stage required by
programmers is to construct a Mongoose model. Models are composed of builders of schemas, with the
primary responsibility of producing and scanning documents in the Mongo database. Querying, deleting,
and updating documents in the database are additional capabilities of models worth mentioning.
13 | P a g e
Figure 6. The relationship between Mongoose, NodeJS and MongoDB
Software Specification: -
Operating System:
14 | P a g e
MERN stack can be set up on Windows, macOS, or Linux. Choose one that you are
comfortable with.
Choose a text editor or IDE for writing your code. Popular options include Visual
Studio Code, Sublime Text, Atom, or JetBrains WebStorm.
Node.js:
Node.js is a JavaScript runtime environment that allows you to run JavaScript on the
server-side. Install the latest stable version of Node.js from the official website:
Node.js.
Package Manager:
npm (Node Package Manager) or yarn are required to manage dependencies and
packages for your project.
npm comes bundled with Node.js installation.
yarn can be installed globally via npm with the command: npm install -g yarn.
MongoDB:
Express.js:
Express.js is a web application framework for Node.js used to build APIs and
web servers. It is installed as a Node.js module.
Install Express.js locally in your project directory using npm or yarn: npm
install express or yarn add express.
React.js:
React.js is a JavaScript library for building user interfaces. It's used for the front-end
part of your MERN stack application.
Web Browser:
• A web browser is essential for testing your frontend code and viewing your web
applications locally. Popular web browsers include Google Chrome, Mozilla
Firefox, Microsoft Edge, and Safari.
• Install any of these browsers based on your preference and operating system.
15 | P a g e
REQUIREMENT SPECIFICATION (SRS)
I. LITERATURE SURVEY
MERN stack is a commonly used combination of technologies for building modern web
applications, comprising MongoDB, Express.js, React, and Node.js. E-commerce
websites are increasingly important due to the rise of online shopping. This literature
review discusses the use of the MERN stack for e-commerce website development,
covering its advantages, technical aspects, security considerations, case studies, best
practices, and future developments.
Scalability is a key advantage of using the MERN stack for e-commerce website
development. The modular architecture allows easy scaling of the application, while the
use of MongoDB as a NoSQL database enables flexible data modelling for complex and
dynamic data structures. Another advantage is the stack's performance, which is boosted
by its ability to handle both client-side and server-side components. Furthermore, React
allows for the efficient rendering of components, thus reducing load times.
Developing an e-commerce website using the MERN stack involves creating an API with
Express.js for server-side communication. MongoDB stores and retrieves data while
React builds dynamic and responsive user interfaces. Node.js is used for server-side
scripting to enable real-time communication between client-side and server-side
components.
Security is a critical aspect of e-commerce website development, and the MERN stack
provides several features to ensure the security of the application. MongoDB provides
authentication and access control, and SSL/TLS encryption for secure communication.
Express.js handles authentication and authorization and can be used to prevent common
security vulnerabilities. React and Node.js support SSL/TLS encryption and XSS
protection.
Several successful e-commerce websites have been built using the MERN stack, such as
Airbnb in India and HULU in the Middle East.
Best practices for e-commerce website development using the MERN stack include
optimizing performance, testing thoroughly for reliability and security, deploying to a
reliable and scalable infrastructure, and maintaining the application through regular
updates and bug fixes. Additionally, it is important to adhere to industry standards and
regulations such as PCI DSS compliance for payment processing.
One of the potential drawbacks of using the MERN stack for e-commerce website
development is its learning curve. The technology stack requires expertise in multiple
16 | P a g e
technologies, which can be challenging for novice developers. Additionally, the
modularity of the MERN stack can result in many dependencies, which can increase the
complexity of the application and make maintenance more difficult. Finally, the MERN
stack may not be the most appropriate choice for all e-commerce websites, particularly
those with simpler requirements. The future of e-commerce website development using
the MERN stack will see the integration of emerging technologies like machine learning,
blockchain, and augmented reality. Machine learning can provide personalized product
recommendations, blockchain can facilitate secure payment processing, and augmented
reality can provide a more immersive shopping experience.
MERN stack offers a flexible and powerful solution for e-commerce website
development, with advantages in scalability and performance. Its security features and
successful case studies make it a reliable and popular choice for e-commerce developers.
Best practices and future developments provide guidance and opportunities for continued
innovation.
II. EXISTING SYSYTEM: -
The present scenario for shopping is to visit the shops and market manually and then
from the available product list one needs to choose the item he or she wants and then pay
for the same item mainly in cash mode is done, as not every society is well educated and
aware to use net banking or card modes or wallets etc.
This system is not much user-friendly as one needs to go to the market physically and
then select items only from the available list. So mostly it is difficult to get the product as
per our desire. Description About the products is less available and are mostly verbal
only. For this type of shopping, one needs to have an ample amount of free time.
Also, not good markets exist everywhere, so many times good markets become out of
reach for certain people. In the proposed system customers need not go to the shops for
purchasing the products. He/she can order the product he/she wishes to buy through the
use of this system. The shop owner can be the admin of the system.
The shop owner can appoint officials particularly to handle this, who will help the owner
in managing the customers and product orders. The system also endorses a home delivery
system for delivering the purchased products. The current system for shopping is to visit
the shop manually and from the available product choose the item customer wants and
buy the item by payment of the price of the item.
● It is less user-friendly.
● User must go to the shop and select products.
● It is difficult to identify the required product.
● Description of the product limited.
● It is a time-consuming process.
17 | P a g e
● Not in reach of distant users.
III. PROPOSED SYSYTEM: -
The proposed system for an e-commerce website using the MERN stack will leverage the
latest technologies to provide a user-friendly, secure, and scalable e-commerce platform.
The MERN stack, comprising MongoDB, Express.js, React, and Node.js, will be used to
develop a robust and dynamic e-commerce website that will enable businesses to sell
products online.
The proposed system will have a client-server architecture, with the server-side
component built using the MERN stack. MongoDB will be used as the database to store
and retrieve data, and Express.js will handle the server-side communication and routing.
Node.js will be used for server-side scripting, allowing real-time communication between
the client-side and server-side components.
The client-side component will be developed using React, which will enable the creation
of dynamic and responsive user interfaces. React will also provide an efficient rendering
of components, resulting in reduced load times and enhanced user experience.
Additionally, the proposed system will be developed using a modular approach, allowing
for easy scaling of the application.
The proposed system will have a range of features to provide a seamless e-commerce
experience for users. These features will include:
●Product Catalog: The product catalogue will allow users to browse through a wide
range of products and filter them based on their preferences.
●Shopping Cart: The shopping cart will enable users to add products to their cart, review
their orders, and checkout.
●Payment Gateway Integration: The payment gateway integration will allow users to
make secure payments using a variety of payment methods, such as credit cards, debit
cards, and digital wallets.
●Order Management: The order management system will enable businesses to manage
orders, track shipments, and generate invoices.
●User Management: The user management system will enable businesses to manage user
accounts, including registration, login, and authentication.
●Search Engine Optimization: The proposed system will be optimized for search engines
to improve the visibility of the e-commerce website and increase traffic.
The proposed system will incorporate several security features to ensure the safety and
security of user data and transactions. These features will include:
18 | P a g e
●SSL/TLS Encryption: The system will use SSL/TLS encryption to secure all
communication between the client-side and server-side components
●Access Control: Access control will be implemented using role-based authentication to
ensure that only authorized users have access to sensitive data.
●PCI DSS Compliance: The system will be compliant with the Payment Card Industry
Data Security Standard (PCI DSS) to ensure the secure processing of credit card
payments.
●Regular Security Audits: The proposed system will undergo regular security audits to
identify and address any vulnerabilities or security issues.
The feasibility study for an e-commerce website using the MERN stack is essential to
evaluate the practicality and viability of the proposed system. This study will assess the
technical, operational, economic, and legal aspects of the project and provide insights
into the feasibility of developing an e-commerce website using the MERN stack.
Economic Feasibility:
The economic feasibility of the proposed system is determined by assessing the cost of
development, deployment, and maintenance of the e-commerce website. The MERN
stack is an open-source technology, and the initial cost of development is relatively low.
However, ongoing maintenance and updates will require a dedicated team, which may
result in recurring expenses. The project's profitability will depend on the volume of sales
generated, and the e-commerce website's scalability and flexibility will enable businesses
to expand their operations and generate more significant profits.
Technical Feasibility:
19 | P a g e
SYSTEM ANALYSIS DESIGN
PROJECT SPECIFICATION: -
The project specification for an e-commerce website using the MERN stack is a
comprehensive document that outlines the requirements, functionality, and features of the
proposed system. This specification will provide a detailed description of the e-
commerce website, including its design, user interface, functionality, security, and
performance.
General Requirements:
The e-commerce website must be developed using the MERN stack, which includes
MongoDB, Express.js, React, and Node.js. The website should be responsive, intuitive,
and easy to navigate. It should be designed with a clean and modern interface, consistent
with the branding and image of the business. The website must support multiple
languages and currencies to facilitate global sales.
Functional Requirements:
The e-commerce website must have the following features and functionalities:
●User Account Management: The website should allow users to create and manage their
accounts, including personal information, shipping addresses, and payment options.
●Product Catalog: The website should provide a comprehensive catalogue of products,
including product descriptions, images, prices, and reviews. Users should be able to
search and filter products based on different criteria, such as price, category, and brand.
●Shopping Cart: The website should allow users to add products to their shopping cart,
view the contents of their cart, and proceed to checkout.
● Payment Gateway Integration: The website should integrate with a secure and
reliable payment gateway to facilitate secure online transactions.
● Order Management: The website should allow businesses to manage orders,
including order tracking, order processing, and order fulfillment.
● Customer Service: The website should provide customer service options, such as live
chat, email support, and FAQ section.
Security Requirements:
●The e-commerce website must have the following security features:
●SSL Encryption: The website should use SSL encryption to secure user data and
prevent unauthorized access.
20 | P a g e
●User Authentication: The website should require users to create and use strong
passwords to protect their accounts.
● Payment Security: The website should use a secure payment gateway to ensure
secure and safe online transactions.
Performance Requirements:
The e-commerce website must have the following performance features:
●Fast Load Time: The website should load quickly to provide a seamless user
experience.
●Scalability: The website should be scalable to accommodate growing user traffic and
transactions.
●Reliability: The website should be reliable and available 24/7 to facilitate sales and
transactions.
The project specification for an e-commerce website using the MERN stack provides a
detailed overview of the proposed system's requirements, functionalities, and features.
The specification highlights the importance of a responsive design, intuitive user
interface, secure payment gateway, and fast load time to provide a seamless and
satisfactory user experience. By following this specification, businesses can develop a
robust e-commerce website using the MERN stack and expand their operations to reach a
global audience.
SYSYTEM ARCHITECTURE: -
21 | P a g e
Figure 7. Architecture design
DESIGN DIAGRAMS
22 | P a g e
Figure 8. Use Case Diagram
BLOCK DIAGRAM:
23 | P a g e
SEQUENCE DIAGRAM:
24 | P a g e
Figure 11. Client-Side Activity Diagram
25 | P a g e
Figure 11. Admin Side Activity Diagram
26 | P a g e
DATAFLOW DIAGRAM:
27 | P a g e
FLOWCHART:
28 | P a g e
SNAPSHOTS OF FRONTEND AND REPORTS
29 | P a g e
30 | P a g e
31 | P a g e
CODE
HOME PAGE
<!DOCTYPE html>
<html>
<head>
<% if (pageName) { %>
<title>BSSBags | <%= pageName %></title>
<%} else {%>
<title>Shopping Cart</title>
<% } %>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"
></script>
<script
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.
css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRx
T2MZw1T"
crossorigin="anonymous"
/>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js
"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM
+B07jRM"
crossorigin="anonymous"
></script>
<script
src="https://kit.fontawesome.com/91abd10b8f.js"
crossorigin="anonymous"
></script>
<link rel="stylesheet" href="/stylesheets/style.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Mapbox -->
32 | P a g e
<script src="https://api.mapbox.com/mapbox-gl-js/v1.10.0/mapbox-
gl.js"></script>
<link
href="https://api.mapbox.com/mapbox-gl-js/v1.10.0/mapbox-gl.css"
rel="stylesheet"
/>
</head>
<body>
<form class="form-inline" action="/products/search" method="GET">
<input
class="search-input"
type="search"
placeholder="Search"
name="search"
/>
</form>
</div>
</div>
33 | P a g e
INDEX.JS
const express = require("express");
const csrf = require("csurf");
const stripe = require("stripe")
('sk_test_51Ohq4QSCIrVLpeErCfKw5Ibj3ysLmyDC0ao6WNJaEzo2QFNSuqzdfvxkoRmQt1Q1
TF4VzQNB26rwEOpJwTmZffTN00UGuU1mXf');
const Product = require("../models/product");
const Category = require("../models/category");
const Cart = require("../models/cart");
const Order = require("../models/order");
const middleware = require("../middleware");
const router = express.Router();
// GET: add a product to the shopping cart when "Add to cart" button is
pressed
router.get("/add-to-cart/:id", async (req, res) => {
const productId = req.params.id;
try {
// get the correct cart, either from the db, session, or an empty cart.
let user_cart;
if (req.user) {
user_cart = await Cart.findOne({ user: req.user._id });
}
// add the product to the cart
const product = await Product.findById(productId);
const itemIndex = cart.items.findIndex((p) => p.productId ==
productId);
if (itemIndex > -1) {
// if product exists in the cart, update the quantity
cart.items[itemIndex].qty++;
34 | P a g e
cart.items[itemIndex].price = cart.items[itemIndex].qty *
product.price;
cart.totalQty++;
cart.totalCost += product.price;
db
if (req.user) {
cart.user = req.user._id;
await cart.save();
}
console.log(err.message);
res.redirect("/");
}
});
// GET: reduce one from an item in the shopping cart
router.get("/reduce/:id", async function (req, res, next) {
// if a user is logged in, reduce from the user's cart and save
// else reduce from the session's cart
const productId = req.params.id;
let cart;
try {
if (req.user) {
cart = await Cart.findOne({ user: req.user._id });
} else if (req.session.cart) {
cart = await new Cart(req.session.cart);
}
// POST: handle checkout logic and payment using Stripe
router.post("/checkout", middleware.isLoggedIn, async (req, res) => {
try {
// Check if there's a cart in the session
if (!req.session.cart) {
return res.redirect("/shopping-cart");
// Retrieve cart details from the database
const cart = await Cart.findById(req.session.cart._id);
// Create a charge using Stripe
stripe.charges.create(
{
amount: cart.totalCost, // Converting rupees to paisa
currency: "inr",
source: req.body.stripeToken,
description: "Test charge",
},
async (err, charge) => {
if (err) {
req.flash("error", err.message);
console.error(err);
return res.redirect("/checkout");
}
// Create a new order
35 | P a g e
const order = new Order({
user: req.user,
cart: {
totalQty: cart.totalQty,
totalCost: cart.totalCost,
items: cart.items,
},
address: req.body.address,
paymentId: charge.id,
});
// Save the order to the database
await order.save();
// Clear the cart from the session and database
await Cart.findByIdAndDelete(cart._id);
req.session.cart = null;
// Flash success message and redirect to profile page
req.flash("success", "Successfully purchased");
res.redirect("/user/profile");
);
});
// create products array to store the info of each product in the cart
async function productsFromCart(cart) {
let products = []; // array of objects
for (const item of cart.items) {
let foundProduct = (
await Product.findById(item.productId).populate("category")
).toObject();
foundProduct["qty"] = item.qty;
foundProduct["totalPrice"] = item.price;
products.push(foundProduct);
}
return products;
}
module.exports = router;
VALIDATOR.JS
const { check, validationResult,sanitize } = require("express-
validator");
const userSignUpValidationRules = () => {
const allowedDomains = ['gmail.com', 'outlook.com',
'protonmail.com'];
const emailValidator = (value) => {
const emailParts = value.split('@');
const domain = emailParts[emailParts.length - 1];
if (!allowedDomains.includes(domain)) {
throw new Error('Email domain should be Gmail, Outlook, or
Protonmail');
36 | P a g e
}
return true;
};
return [
check("name", "Name is required").not().isEmpty(),
check("email", "Invalid
email").not().isEmpty().isEmail().custom(emailValidator),
check("password", "Password must contain at least one uppercase
letter, one lowercase letter, one number, and one special character")
.not()
.isEmpty()
.isLength({ min: 4 })
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\
d!@#$%^&*]{4,}$/),
];
};
37 | P a g e
next();
};
const validateContactUs = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
var messages = [];
errors.array().forEach((error) => {
messages.push(error.msg);
});
next();
};
module.exports = {
userSignUpValidationRules,
userSignInValidationRules,
userContactUsValidationRules,
validateSignup,
validateSignin,
validateContactUs,
};
MONGODB.JS
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const uri = process.env.MONGO_URI || "mongodb://localhost/bags-
ecommerce";
await mongoose
.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
.catch((error) => console.log(error));
const connection = mongoose.connection;
console.log("MONGODB CONNECTED SUCCESSFULLY!");
} catch (error) {
}
};
module.exports = connectDB;
STYLE.CSS
:root {
--dark-blue: #478ba2;
--light-blue: #b9d4db;
--green: #18a558;
--ivory: #f9f7f4;
38 | P a g e
--black: #202020;
--dark-gray: #474747;
}
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
font-family: 9px "Poppins", sans-serif;
}
html {
scroll-behavior: smooth;
}
/* NAVBAR STYLE */
a,
.logo-container a,
.right-nav a {
color: var(--black);
text-decoration: none !important;
}
a:hover,
.logo-container a:hover,
.right-nav a:hover {
color: var(--dark-gray) !important;
text-decoration: none;
}
.nav-container {
margin: auto;
padding: 0.5em 1em;
display: flex;
justify-content: center;
color: var(--black);
}
.search-container {
width: 70%;
}
.logo-container a {
display: flex;
flex-direction: row;
justify-content: center;
}
.logo-title {
font-weight: 600;
margin: 4px 1px;
}
.logo-img {
max height: 3em;
39 | P a g e
}
/* HOME PAGE */
.circle-img {
object-fit: cover;
width: 200px;
height: 200px;
border-radius: 50%;
cursor: pointer;
transition: all 0.2s linear;
-webkit-transition: all 0.2s linear;
}
.fa-chevron-circle-right:hover {
transform: scale(1.4);
}
hr.gradient-style {
border: 0;
height: 1px;
background-image: linear-gradient(
to right,
rgba(0, 0, 0, 0),
rgba(0, 0, 0, 0.75),
rgba(0, 0, 0, 0)
);
margin: 1em auto;
}
/* PAGINATION STYLE */
.pagination .active .page-link {
color: var(--ivory);
background-color: var(--dark-blue);
}
.pagination .page-link {
color: var(--dark-blue);
}
/* SHOPPING CART STYLES */
.container.cart {
margin: 1em auto;
}
.img-small {
max-height: 50px; /* Adjust image height */
margin: 2px;
}
.qty-display {
padding: 3px;
border: 1px solid rgb(54, 54, 54);
border-radius: 5px;
40 | P a g e
font-size: 12px; /* Adjust font size */
}
.table {
margin-bottom: 0; /* Remove bottom margin to reduce spacing */
}
.table th,
.table td {
padding: 0.5em; /* Adjust cell padding */
}
CHECKOUT.JS
<%- include ../partials/header %> <%- include ../partials/categories-navbar
%>
<div class="container mt-4 mb-5">
<!-- Flash messages -->
<div class="row mt-3 mb-3">
<div class="col-md-8 m-auto">
<% if (errorMsg) { %>
<div id="error" class="alert alert-danger">
<%= errorMsg %>
</div>
<% } else { %>
<div id="error" class="alert alert-danger d-none"></div>
<% } %>
</div>
</div>
<div class="col-md-8 m-auto">
<! -- Checkout form -->
<form action="/checkout" method="POST" id="checkout-form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="card-name">Card Holder Name</label>
<input type="text" id="card-name" class="form-control" required
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="address">Address</label>
<input
type="text"
id="address"
41 | P a g e
class="form-control"
required
name="address"
/>
</div>
</div>
CONCLUSION
In conclusion, our voyage through the development lifecycle of our E-shop ecommerce
project, powered by the versatile MERN stack, has been a profound journey characterized by
discovery, innovation, and collaboration. By adhering to meticulous planning, embracing
agile methodologies, and fostering a culture of teamwork, we have not only crafted a resilient
and scalable platform but also honed our skills and forged lasting partnerships.
The amalgamation of MongoDB, Express.js, React.js, and Node.js within the MERN stack
has bestowed upon us a formidable arsenal of tools to construct a dynamic and responsive
web application that seamlessly integrates frontend and backend technologies. Leveraging
MongoDB's prowess for flexible and efficient data storage, harnessing Express.js to erect
scalable and secure server-side applications, utilizing React.js to fashion engaging and
interactive user interfaces, and tapping into Node.js for swift and event-driven backend
development, we have erected a harmonious and high-performing system that transcends
conventional boundaries.
Looking towards the horizon, we acknowledge that our journey is far from over. In an era
characterized by rapid technological evolution and shifting user paradigms, our commitment
to excellence remains unwavering. We are steadfast in our dedication to nurturing and
enhancing our bags ecommerce platform, with a keen ear to the ground for user feedback and
a proactive stance towards integrating emerging technologies, ensuring its sustained
relevance and success in the ever-evolving landscape of ecommerce.
42 | P a g e
In bidding farewell to this phase of our journey, we extend our heartfelt gratitude to all those
who have contributed to the realization of this endeavor - our esteemed team members,
supportive stakeholders, and insightful mentors. It is through the synergy of our collective
efforts that we have achieved this significant milestone, and it is with boundless optimism
and unwavering enthusiasm that we eagerly anticipate the adventures that lie
ahead.
43 | P a g e