Live Demo: Explore the live website. π₯
A comprehensive feature-rich e-commerce website developed as a server-client React application, powered by the MERN (MongoDB, Express.js, React.js, Node.js) stack.
This project showcases proficiency in full-stack development, including frontend UI/UX design, backend API development, database management, and integration with external services.
Please try to experience full purchase on the website:) Register, choose products, pay with this demo PayPal user, and review your order.
Demo PayPal User:
β½ Username: sb-gt6zp25024137@personal.example.com
β½ Password: W=Flx8z1
- dynamic shopping cart
- π Interactive review system
- ποΈ Organized product listings
- π³Paypal payment process
- π User authentication and authorization
- π οΈ User functionalities, such as order history, and admin functionalities such as real-time metrics (registered users, order count, total money orders), creation, editing, and deletion of products.
The frontend is built using React.js, using React features such as hooks (useState
, useEffect
), and state management using Redux. It includes components and routing to create an interactive user experience.
- React Components: Utilizes functional components and hooks to manage state and side effects, promoting code reusability and simplification.
- Redux State Management: Manages the global state of the application, including user authentication, product listing, and shopping cart state. Redux Thunk is used for asynchronous operations.
- Routing with React Router: Implements dynamic routing for different parts of the application, including product pages, user login, and the shopping cart.
- State Management with useState and useEffect: Manages local component state and side effects, ensuring components respond to changes in application state efficiently.
- Asynchronous Operations with Redux Thunk: Handles asynchronous logic such as fetching data from the backend.
The backend of this e-commerce website is built using Node.js and Express.js, connecting to MongoDB Atlas for database management. It includes secure user authentication with Firebase and implements API endpoints to handle various functionalities such as product management, user management, and order processing.
-
Database Management with MongoDB Atlas: π
MongoDB Atlas
is a cloud-based NoSQL database used to manage the application's data efficiently. The database is designed to handle collections forproducts, and orders
.- Orders Collection: Stores order details including items, shipping address, payment method, and user information.
- Products Collection: Contains product information such as name, category, price, stock status, and reviews.
Example Order Document (MongoDB)
{ "_id": {"$oid": "666020f1c3dfea5c9ceef0e5"}, "orderItems": [ { "slug": "adidas-fit-pant", "name": "Adidas Fit Pant", "quantity": {"$numberInt": "1"}, "image": "/images/p4.jpg", "price": {"$numberInt": "65"}, "product": {"$oid": "63e3a5730d4c13163688a505"}, "_id": {"$oid": "63e3a5730d4c13163688a505"} } ], "shippingAddress": { "fullName": "Shani Bider", "address": "Hapardes Harishon 1", "city": "Rishon LeZion", "postalCode": "7520901", "country": "Israel" }, "paymentMethod": "PayPal", "itemsPrice": {"$numberInt": "65"}, "shippingPrice": {"$numberInt": "10"}, "taxPrice": {"$numberDouble": "9.75"}, "totalPrice": {"$numberDouble": "84.75"}, "user": {"$oid": "63e3a5730d4c13163688a508"}, "isPaid": false, "isDelivered": false, "createdAt": {"$date": {"$numberLong": "1675865100712"}}, "updatedAt": {"$date": {"$numberLong": "1675865100712"}}, "__v": {"$numberInt": "0"} }
Example Product Document (MongoDB)
{
"_id": {"$oid": "66602124c3dfea5c9ceef0e6"},
"name": "Gray T-shirt",
"slug": "T-shirt",
"image": "/images/i1.jpg",
"brand": "H&M",
"category": "Shirts",
"description": "High-quality T-shirt made from organic cotton.",
"price": {"$numberInt": "20"},
"countInStock": {"$numberInt": "50"},
"rating": {"$numberDouble": "4.5"},
"numReviews": {"$numberInt": "12"}
}
- Express.js for API Development: π
Express.js
is used to create a RESTful API to handleHTTP requests
and responses, ensuring efficient communication between the frontend and the backend. The API endpoints are designed to perform CRUD operations on user, product, and order data.
Example API Route (orderRoutes.js)
orderRouter.get(
'/',
isAuth,
isAdmin,
expressAsyncHandler(async (req, res) => {
const orders = await Order.find().populate('user', 'name');
res.send(orders);
})
);
orderRouter.post(
'/',
isAuth,
expressAsyncHandler(async (req, res) => {
//create an order
const newOrder = new Order({
//for each order item we need to get the product id (for OrderModel). By map function we convert _id to product
orderItems: req.body.orderItems.map ( (x) => ({ ...x, product: x._id })),
shippingAddress: req.body.shippingAddress,
paymentMethod: req.body.paymentMethod,
itemsPrice: req.body.itemsPrice,
shippingPrice: req.body.shippingPrice,
taxPrice: req.body.taxPrice,
totalPrice: req.body.totalPrice,
user: req.user._id, //in the end of isAuth we have req.user
});
//save the order in db
const order = await newOrder.save();
res.status(201).send({ message: 'New Order Created', order });
})
);
- User Authentication with Firebase: π
Firebase
Authentication is integrated to manage usersign-up, login, and secure sessions
.
Example Firebase Authentication (auth.js)
import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth';
import { getFirestore } from '@firebase/firestore';
const firebaseConfig = {
apiKey: "AIzaSyDzdc6B_R5qfZ0sxsphZVYsx3wbIzqBJwQ",
authDomain: "fir-final-project-9a40c.firebaseapp.com",
databaseURL: "https://fir-final-project-9a40c-default-rtdb.firebaseio.com",
projectId: "fir-final-project-9a40c",
storageBucket: "fir-final-project-9a40c.appspot.com",
messagingSenderId: "980757971098",
appId: "1:980757971098:web:0da87ecab4ab961d98df23"
};
export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);
- Hosting on Render: βοΈ The website is hosted on Render, including connection to environment variables such as JWT_SECRET and MONGODB_URI. Render offers a deployment process, automatic SSL, and global CDN, ensuring high availability and performance.
- Paypal API - Using Demo Payment via . To experience the payment process with PayPal, you can use the demo feature. Follow these steps to make a demo paymentπ°:
- Visit the Demo Payment Page: Navigate to the payment page.
- Login with Demo Credentials: Use the provided demo username and password to access the demo environment.
- Initiate Payment: Enter the demo payment section and select PayPal as the payment method.
- Complete Payment: Follow the instructions to proceed with the demo payment through PayPal.
- Username:
sb-gt6zp25024137@personal.example.com
- Password:
W=Flx8z1
- MongoDB: Efficient and scalable NoSQL database, ensuring robust data storage and retrieval capabilities.
- Express.js: Fast and minimalist web framework for Node.js, facilitating the creation of powerful APIs and web applications.
- React.js: Dynamic and responsive JavaScript library for building modern and engaging user interfaces, utilizing:
- useState: React hook for managing state in functional components, enhancing component interactivity and reactivity. βοΈ
- useContext: React hook for accessing and consuming context values across components, facilitating efficient data sharing. π
- useReducer: React hook for managing complex state logic with reducer functions, offering a more organized approach to state management. π΄
- Node.js: Lightweight and efficient JavaScript runtime environment, enabling scalable and high-performance server-side execution.
- Authentication: Firebase authentication services for secure user authentication and authorization management.
- Real-time Database: Firebase real-time database for seamless and synchronized data updates across clients in real-time.
- Axios: Promise-based HTTP client for making asynchronous requests to the server, enhancing data fetching and manipulation.
- AJAX: Asynchronous JavaScript and XML for making seamless requests to the server without refreshing the entire page.
- Fetch API: Modern browser API for fetching resources asynchronously across the network, improving data retrieval efficiency.
- PayPal API: Integration of PayPal API for secure and reliable payment processing, ensuring seamless transactions for users.
- HTML, CSS, JavaScript: Foundational technologies for building the frontend interface, providing structure, style, and interactivity to web applications.
- Bootstrap: Frontend framework for developing responsive and mobile-first web projects, streamlining the design and layout process and ensuring compatibility across various devices. π
-
π Home Page:
- Lists products to browse and explore.
-
π Detailed Product View:
- Provides in-depth information about a selected product.
-
π Product Categories:
- Categorizes products for easy navigation.
-
π Shopping Cart:
- Allows users to add and manage items in their cart.
-
π³ Order Processing with PayPal:
- Securely handles payment processing using the PayPal API for demo purposes.
-
π Secure User Registration and Login:
- Ensures a safe and secure user authentication system.
-
π©βπΌπ¨βπΌ Admin Functionalities:
- Manages 'Products' and 'Orders' lists
- Features a dashboard displaying real-time metrics: registered users, order count, and financial performance through total money orders.
- Enables the creation, editing, and deletion of products.
-
π©βπΌ User Functionalities:
- Accesses order history.
- Edits user profile.
-
π©π»βπ€βπ§π» About The Team Page:
- Provides information about the development team.
This repository contains the main files and folder structure for the MERN (MongoDB, Express.js, React.js, Node.js) project. The app follows a typical MERN architecture where React is used for the front-end, Node.js and Express for the back-end, MongoDB for the database, and JWT for authentication. These components work together to provide a seamless shopping experience for users while allowing for easy management of products, orders, and user accounts.
MERN-project/
βββ frontend/
β βββ components/
β β βββ AdminRoute.js
β β βββ CheckoutSteps.js
β β βββ LoadingBox.js
β β βββ MessageBox.js
β β βββ Product.js
β β βββ ProtectedRoute.js
β β βββ Rating.js
β β βββ SearchBox.js
β βββ screens/
β β βββ AboutUsScreen.js
β β βββ CartScreen.js
β β βββ DashboardScreen.js
β β βββ HomeScreen.js
β β βββ HowToScreen.js
β β βββ OrderHistoryScreen.js
β β βββ OrderListScreen.js
β β βββ OrderScreen.js
β β βββ PaymentMethodScreen.js
β β βββ PlaceOrderScreen.js
β β βββ ProductEditScreen.js
β β βββ ProductListScreen.js
β β βββ ProductScreen.js
β β βββ ProfileScreen.js
β β βββ SearchScreen.js
β β βββ ShippingAddressScreen.js
β β βββ SigninScreen.js
β β βββ SignupScreen.js
β βββ App.js
β βββ Store.js
β βββ index.js
β βββ utils.js
βββ Backend/
β βββ routes/
β β βββ orderRoutes.js
β β βββ productRoutes.js
β β βββ seedRoutes.js
β β βββ userRoutes.js
β βββ models/
β β βββ orderModel.js
β β βββ productModel.js
β β βββ userModel.js
β βββ server.js
β βββ firebase.js
β βββ utils.js
β βββ data.js
β βββ cloths.json
βββ ...
- backend: Contains the backend files and resources, following a RESTful architecture.
- frontend: Houses the frontend files and components developed with React.js.
- config: Stores configuration files for the project, such as database configurations or environment variables.
- models: Defines the database models and schemas used in the application.
- routes: Contains the route definitions for the API endpoints.
- controllers: Includes the controller functions responsible for handling requests and responses.
- middlewares: Houses custom middleware functions used in the API.
- utils: Stores utility functions and helper modules used throughout the project.
- public: Stores any static assets or files served by the backend.
- views: Contains server-side views if any, typically used in server-side rendering applications.
-
server.js
: This is the main entry point for the Node.js backend. It initializes Express, connects to MongoDB using Mongoose, defines API routes, and serves the React frontend. It also includes logic for seeding initial data and serving static files.
-
orderRoutes.js
,productRoutes.js
,seedRoutes.js
,userRoutes.js
: These files define the API endpoints and route handlers for managing orders, products, user authentication, and seeding initial data.
-
Order.js
,Product.js
,User.js
: These files define the data models using Mongoose, which allow you to interact with MongoDB collections.
-
firebase.js
: This file sets up Firebase for authentication and database management in the application. It ensures that the Firebase app is properly configured and ready to use authentication and Firestore services.
-
utils.js
: This file provides essential utility functions and middleware for user authentication and authorization in the application. It ensures that only authenticated users with the appropriate permissions can access certain routes or perform specific actions.
-
AdminRoute.js
,CheckoutSteps.js
,LoadingBox.js
,MessageBox.js
,Product.js
,ProtectedRoute.js
,Rating.js
,SearchBox.js
.
-
CartScreen.js
,DashboardScreen.js
,HomeScreen.js
,HowToScreen.js
,OrderHistoryScreen.js
,OrderListScreen.js
,OrderScreen.js
,PaymentMethodScreen.js
,PlaceOrderScreen.js
,ProductEditScreen.js
,ProductListScreen.js
,ProductScreen.js
,ProfileScreen.js
,SearchScreen.js
,ShippingAddressScreen.js
,SigninScreen.js
,SignupScreen.js
,AboutUsScreen.js
.
App.js
: This file is the entry point for your React frontend application- controls the frontend structure and behavior. It defines routes usingreact-router-dom
for different pages/screens of the application and orchestrates the structure and behavior of your frontend application.
-
store.js
: This file defines and manages the application's global state management using React context and reducers. It essentially manages the global state of the application, handling user authentication, cart management, and related operations.
-
index.js
: This file serves as the entry point for the React application. It wraps the<App />
component with providers such asStoreProvider
,HelmetProvider
, andPayPalScriptProvider
.
Here's an example of how HelmetProvider and react-helmet might be use in the app:
// Import necessary dependencies
import { Helmet, HelmetProvider } from 'react-helmet-async';
// Wrap your entire application with HelmetProvider in index.js
ReactDOM.render(
<HelmetProvider>
<App />
</HelmetProvider>,
document.getElementById('root')
);
// In any component where you want to dynamically change document head elements, use Helmet component
const MyComponent = () => {
return (
<div>
{/* Use Helmet component to set document title */}
<Helmet>
<title>My Page Title</title>
{/* Add other head elements like meta tags */}
<meta name="description" content="This is my page description" />
</Helmet>
{/* Your component JSX */}
<h1>Hello, World!</h1>
</div>
);
};
Components are reusable building blocks that encapsulate a piece of UI functionality. They promote code reusability and maintainability by allowing you to create modular pieces of code that can be used across different parts of your application.
Screens are typically higher-level components that represent entire pages or views within your application. They often contain multiple components and handle more complex logic related to rendering and managing UI state.
THe architecture focuses on structured state management, components, and effective handling of side effects and navigation in a React app.
-
πState Management:
- Uses
useReducer
for organized state management.
- Uses
-
πGlobal State:
- Manages global state for properties like
cart
,userInfo
,loading
, anderror
.
- Manages global state for properties like
-
πSide Effects:
- Handles side effects, such as data fetching, with
useEffect
.
- Handles side effects, such as data fetching, with
-
πComponent Structure:
- Organizes the app into modular components, promoting a component-based architecture.
-
πReact Router:
- Implements React Router for navigation.
-
πConditional Rendering:
- Conditionally displays UI elements based on the application's state.
-
πAuthentication Handling:
- Manages user authentication through global state.
-
πMiddleware (
logger
):- Uses a middleware function (
logger
) for state change logging.
- Uses a middleware function (
-
πRESTful API Calls:
- Utilizes Axios for making API calls to a backend server.
π Demo :
React.demo.mp4
Admin dashboard displaying real-time metrics: registered users, order count, and financial performance through total money orders
- Clone the repository:
git clone [repository_url]
- Set up the MongoDB database and Firebase authentication.
- Configure environment variables.
- Run Backend-
$ cd our-website
$ cd backend
$ npm i
$ npm start
- Run Frontend-
open new terminal
$ cd our-website
$ cd frontend
$ npm i
$ npm start
Seed Users and Products (backend)- Run this on browser: http://localhost:5000/api/seed (Will returns admin email, password and sample products).
Admin Login- Run http://localhost:3000/signin
Copyright Β© Shani Bider, 2024
This project is licensed under the MIT License.