E-Commerce Platform
Using React.js, Node.js
with MySQL
database
Project
Overview
The E-Commerce Platform is
a full-fledged online shopping application built using React.js for the
frontend and Node.js for the backend, with MySQL as the database.
This platform is designed to facilitate a seamless shopping experience for
users while providing robust management capabilities for administrators.
Features and Functionalities
User Features
- User
Authentication:
- Registration
and login functionality.
- Password
reset option.
- Product
Browsing:
- Display
a list of products with filtering options (by category, price, etc.).
- View
detailed product information including images, descriptions, and prices.
- Shopping
Cart:
- Add
products to the shopping cart.
- Update
item quantities or remove items from the cart.
- View
total cart value.
- Checkout
Process:
- Enter
shipping and billing information.
- View
order summary before confirmation.
- Integrate
payment gateways for secure transactions.
- Order
History:
- Users
can view their past orders and details of each order.
- Track
the status of current orders.
- User
Profile Management:
- View
and update personal information.
- Change
passwords and manage account settings.
- Search
Functionality:
- Search
for products by name, category, or keywords.
- Reviews
and Ratings:
- Leave
reviews and ratings for purchased products.
Admin Features
- Admin
Dashboard:
- Overview
of key metrics (total sales, number of users, etc.).
- Quick
access to management features.
- Product
Management:
- Add,
edit, or delete products from the inventory.
- Manage
product categories and attributes (size, color, etc.).
- Upload
product images.
- User
Management:
- View
and manage user accounts.
- Approve
or block user accounts as needed.
- Order
Management:
- View
all orders placed by users.
- Update
order status (e.g., pending, shipped, delivered).
- Process
returns and refunds.
- Analytics
and Reports:
- Generate
reports on sales, user activity, and inventory status.
- Insights
into product performance and user behavior.
- Content
Management:
- Manage
promotional banners, discounts, and announcements.
General Features
- Responsive
Design:
- Ensure
the application is accessible on various devices, including desktops,
tablets, and mobile phones.
- Secure
Payment Processing:
- Utilize
secure payment gateways for transactions, ensuring user data protection.
- Error
Handling and Validation:
- Implement
input validation and error handling throughout the application to enhance
user experience and security.
- Notification
System:
- Notify
users about order status updates, promotional offers, and other relevant
information via email or in-app notifications.
- Performance
Optimization:
- Optimize
the application for speed and performance, ensuring a smooth user
experience even under heavy load.
Conclusion
The E-Commerce Platform provides
a comprehensive solution for online shopping, catering to both users and
administrators. By integrating essential features and functionalities, it aims
to create a user-friendly environment that promotes seamless interactions,
efficient product management, and robust order processing. The structure and
design ensure that the application is scalable, maintainable, and capable of
evolving with future needs and trends in the e-commerce landscape.
Project Structure with
Required Files
ecommerce-platform/
│
├── backend/
# Node.js backend
│ ├── config/
│ │ ├──
db.js # Database connection
setup
│ │
└── config.js #
Configuration variables (e.g., JWT secret)
│ ├── controllers/
│ │ ├──
authController.js # User
authentication logic
│ │ ├──
productController.js # Product
management logic
│ │ ├──
userController.js # User management
logic
│ │
└── orderController.js # Order
management logic
│ ├── middleware/
│ │ ├──
authMiddleware.js # JWT authentication
middleware
│ │
└── errorMiddleware.js # Error
handling middleware
│ ├── models/
│ │ ├──
userModel.js # User model/schema
│ │ ├──
productModel.js # Product
model/schema
│ │
└── orderModel.js # Order
model/schema
│ ├── routes/
│ │ ├──
authRoutes.js # Authentication
routes
│ │ ├──
productRoutes.js # Product routes
│ │ ├──
userRoutes.js # User routes
│ │
└── orderRoutes.js # Order
routes
│ ├── utils/
│ │
└── validation.js # Input
validation logic
│ ├── uploads/ #
Directory for storing uploaded files (e.g., product images)
│ ├── .env #
Environment variables (e.g., database credentials)
│ ├── server.js #
Main server file
│ └── package.json # Backend dependencies
│
└── frontend/ # React.js frontend
├── public/
│ ├──
index.html # Main HTML file
│
└── favicon.ico # Favicon
├── src/
│ ├── api/
│
│ └── api.js # API request functions
│ ├──
components/
│
│ ├── common/
│
│ │ ├── Button.js # Reusable
button component
│
│ │ ├── Modal.js # Reusable
modal component
│
│ ├── User/
│
│ │ ├── UserDashboard.js # User
dashboard component
│
│ │ ├── ProductList.js #
Product listing component
│
│ │ ├── Cart.js #
Shopping cart component
│
│ │ └── OrderHistory.js # User's order history component
│
│ ├── Admin/
│
│ │ ├── AdminDashboard.js #
Admin dashboard component
│
│ │ ├── ManageProducts.js #
Product management component
│
│ │ ├── ManageUsers.js #
User management component
│
│ │ └── OrderManagement.js # Order management component
│
│ └── Navbar.js # Navigation bar component
│ ├──
contexts/
│
│ ├── AuthContext.js #
Context for authentication state
│
│ └── CartContext.js # Context for cart state
│ ├── hooks/
│
│ └── useAuth.js # Hook for authentication
│ ├── pages/
│
│ ├── Login.js # Login
page
│
│ ├── Register.js #
Registration page
│
│ ├── Home.js #
Homepage
│
│ ├── Products.js #
Products page
│
│ └── NotFound.js # 404 Not Found page
│ ├── styles/
│
│ └── App.css # Main app styles
│ ├──
App.js # Main app component
│ ├──
index.js # Main entry point
│
└── package.json #
Frontend dependencies
Detailed File Descriptions
Backend
- config/db.js:
Configures the database connection using a library like Sequelize or Knex.
- config/config.js:
Contains application configuration variables, such as JWT secrets and
database credentials.
- controllers/:
- authController.js:
Functions for user authentication (register, login, logout).
- productController.js:
Functions for managing products (CRUD operations).
- userController.js:
Functions for managing user accounts (view, edit, delete).
- orderController.js:
Functions for managing orders (place, view, update).
- middleware/:
- authMiddleware.js:
Middleware to verify JWT and protect routes.
- errorMiddleware.js:
Middleware for centralized error handling.
- models/:
- userModel.js:
Defines the user schema and methods for user-related operations.
- productModel.js:
Defines the product schema and methods for product-related operations.
- orderModel.js:
Defines the order schema and methods for order-related operations.
- routes/:
- authRoutes.js:
Defines routes for authentication-related endpoints.
- productRoutes.js:
Defines routes for product-related endpoints.
- userRoutes.js:
Defines routes for user-related endpoints.
- orderRoutes.js:
Defines routes for order-related endpoints.
- utils/validation.js:
Contains functions for validating user input (e.g., registration and
product data).
- uploads/:
Directory for storing product images or other uploaded files.
- .env:
File to store environment variables, ensuring sensitive information is not
hard-coded.
- server.js:
Main server file that initializes the Express app, middleware, and routes.
- package.json:
Lists the dependencies and scripts for the backend.
Frontend
- public/index.html:
The main HTML file that serves the React application.
- public/favicon.ico:
The favicon for the application.
- src/api/api.js:
Contains functions to make API requests to the backend.
- src/components/:
- common/:
Contains reusable components like buttons and modals.
- User/:
User-specific components (dashboard, product list, cart, order history).
- Admin/:
Admin-specific components (dashboard, product management, user
management, order management).
- Navbar.js:
Component for the navigation bar.
- src/contexts/:
- AuthContext.js:
Context for managing authentication state across the app.
- CartContext.js:
Context for managing the shopping cart state.
- src/hooks/useAuth.js:
Custom hook to handle authentication-related logic.
- src/pages/:
- Login.js:
Page component for user login.
- Register.js:
Page component for user registration.
- Home.js:
Homepage component.
- Products.js:
Component to display a list of products.
- NotFound.js:
Component for 404 Not Found pages.
- src/styles/App.css:
Main CSS file for styling the application.
- src/App.js:
Main component that renders the application layout and includes routing.
- src/index.js:
Entry point for the React application, rendering the App component.
- src/package.json:
Lists the dependencies and scripts for the frontend.
Conclusion
This project structure provides a
comprehensive outline of the files required for a full-fledged e-commerce
platform with both user and admin functionalities. Each file has a specific
purpose, and together they form the backbone of the application.
Step-by-Step Guide to
Developing an E-Commerce Platform
Step 1: Setting Up Your
Development Environment
- Install
Node.js:
- Download
and install Node.js from nodejs.org.
Node.js includes npm (Node Package Manager), which is essential for
managing dependencies.
- Install
MySQL:
- Download
and install MySQL from mysql.com.
Follow the installation instructions and create a new database for your
project.
- Install
a Code Editor:
- Use
a code editor like Visual
Studio Code for writing your code. It provides a good environment for
JavaScript development.
- Set
Up Git (optional but recommended):
- Install
Git from git-scm.com to
manage version control. Create a repository on GitHub or GitLab to store
your project.
Step 2: Initializing the
Project Structure
- Create
Project Directory:
- Open
your terminal and create a new directory for your project:
mkdir ecommerce-platform
cd ecommerce-platform
- Create
Backend and Frontend Folders:
- Inside
your project directory, create folders for the backend and frontend:
mkdir backend frontend
Step 3: Setting Up the Backend
- Navigate
to Backend Folder:
cd backend
- Initialize
Node.js Project:
- Run
the following command to create a package.json file:
npm init -y
- Install
Required Packages:
- Install
Express, MySQL, and other necessary packages:
npm install express mysql2 dotenv
cors bcryptjs jsonwebtoken body-parser
- Create
Basic Server:
- Create
a file named server.js:
// backend/server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('E-Commerce API is running');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- Set
Up Database Connection:
- Create
a folder named config and a file named db.js inside it:
// backend/config/db.js
const mysql = require('mysql2');
const db = mysql.createConnection({
host: 'localhost',
user: 'your_mysql_user', // replace with your MySQL username
password: 'your_mysql_password', // replace with your MySQL password
database: 'ecommerce_db' // replace with your database name
});
db.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
});
module.exports = db;
- Create
User, Product, and Order Models:
- Create
a models folder and add files for user, product, and order schemas. For
simplicity, you can create these as simple JavaScript objects that
interact with the database.
- Implement
User Authentication:
- Create
a controllers folder and add an authController.js to handle user
registration and login. Use bcrypt for password hashing and jsonwebtoken
for token generation.
- Create
API Routes:
- Set
up routes for user authentication, product management, and order
processing in the routes folder.
Step 4: Setting Up the
Frontend
- Navigate
to Frontend Folder:
cd ../frontend
- Create
React App:
- Use
Create React App to initialize your frontend:
npx create-react-app .
- Install
Axios:
- Install
Axios to handle API requests:
npm install axios
react-router-dom
- Set
Up Routing:
- In
your src/App.js, set up routing using React Router. This will allow you
to navigate between different pages (e.g., Home, Login, Products):
import React from 'react';
import { BrowserRouter as Router,
Route, Switch } from 'react-router-dom';
import Home from './pages/Home';
import Login from './pages/Login';
import Products from './pages/Products';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home}
/>
<Route path="/login" component={Login}
/>
<Route path="/products" component={Products}
/>
</Switch>
</Router>
);
}
export default App;
- Create
Components:
- Create
components for the Navbar, User Dashboard, Product Listings, Shopping
Cart, and Admin Dashboard.
- Manage
State with Context or Redux:
- For
managing global state (like user authentication and cart items), consider
using Context API or Redux.
- Connect
to Backend:
- Use
Axios to send API requests from your React components to your Node.js
backend.
Step 5: Implementing Features
- User
Authentication:
- Implement
user registration and login forms in your React app. Store the JWT token
in local storage or context for authenticated routes.
- Product
Management:
- Create
pages to display products, filter and sort them, and allow users to add
them to their shopping cart.
- Shopping
Cart Functionality:
- Implement
the shopping cart feature where users can view, add, update, and remove
items.
- Checkout
Process:
- Create
a checkout page where users can enter their shipping information and
payment details.
- Admin
Panel:
- Implement
an admin panel where administrators can add, edit, or remove products and
manage orders and users.
- Order
History:
- Allow
users to view their order history and track their orders.
Step 6: Testing the
Application
- Test
API Endpoints:
- Use
tools like Postman to test your API endpoints for user registration,
product management, and order processing.
- Test
Frontend Functionality:
- Ensure
all components are functioning as expected, including navigation, forms,
and API integrations.
- Debug
and Fix Issues:
- Use
console logs and error messages to debug any issues that arise during
testing.
Step 7: Deploying the
Application
- Choose
a Hosting Platform:
- For
the backend, consider using platforms like Heroku, DigitalOcean, or AWS.
For the frontend, use services like Vercel or Netlify.
- Configure
Environment Variables:
- Make
sure to set up environment variables for your database connection and JWT
secret in your hosting platform.
- Deploy:
- Follow
the deployment instructions for your chosen platform to deploy both the
backend and frontend.
Step 8: Maintenance and
Iteration
- Monitor
Performance:
- After
deployment, monitor the application for any performance issues or bugs.
- Gather
User Feedback:
- Ask
users for feedback to identify areas for improvement.
- Iterate
on Features:
- Continuously
improve your application by adding new features, optimizing performance,
and fixing bugs.
Conclusion
Building an e-commerce platform
is a challenging yet rewarding project for beginners. Following these steps
will give you a solid foundation in full-stack development using React.js,
Node.js, and MySQL.
Database tables:
1. Users Table
Stores user information.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
name |
VARCHAR(100) |
User's full name |
email |
VARCHAR(100) |
User's email address (unique) |
password |
VARCHAR(255) |
Hashed password |
role |
ENUM |
User role (e.g., 'user',
'admin') |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
2. Products Table
Stores product details.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
name |
VARCHAR(100) |
Product name |
description |
TEXT |
Product description |
price |
DECIMAL(10, 2) |
Product price |
quantity |
INT |
Available stock quantity |
image_url |
VARCHAR(255) |
URL of the product image |
category_id |
INT |
Foreign key to categories table |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
3. Categories Table
Stores product categories.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
name |
VARCHAR(100) |
Category name |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
4. Orders Table
Stores order details.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
user_id |
INT |
Foreign key to users table |
total_amount |
DECIMAL(10, 2) |
Total order amount |
status |
ENUM |
Order status (e.g., 'pending',
'shipped', 'completed') |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
5. Order_Items Table
Stores items in each order.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
order_id |
INT |
Foreign key to orders table |
product_id |
INT |
Foreign key to products table |
quantity |
INT |
Quantity of the product ordered |
price |
DECIMAL(10, 2) |
Price at the time of order |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
6. Shopping_Cart Table
Stores items that users have
added to their shopping cart.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
user_id |
INT |
Foreign key to users table |
product_id |
INT |
Foreign key to products table |
quantity |
INT |
Quantity of the product in cart |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
7. Reviews Table
Stores user reviews for products.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
product_id |
INT |
Foreign key to products table |
user_id |
INT |
Foreign key to users table |
rating |
INT |
Rating (e.g., 1 to 5) |
comment |
TEXT |
Review comment |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
8. Addresses Table
Stores user addresses for
shipping.
Field Name |
Data Type |
Description |
id |
INT |
Primary key, auto-incrementing |
user_id |
INT |
Foreign key to users table |
address_line1 |
VARCHAR(255) |
First line of the address |
address_line2 |
VARCHAR(255) |
Second line of the address |
city |
VARCHAR(100) |
City name |
state |
VARCHAR(100) |
State name |
postal_code |
VARCHAR(20) |
Postal/ZIP code |
country |
VARCHAR(100) |
Country name |
created_at |
TIMESTAMP |
Record creation timestamp |
updated_at |
TIMESTAMP |
Record update timestamp |
Database Relationships
- Users
can have multiple Orders and multiple Addresses.
- Products
belong to a Category.
- Each
Order can contain multiple Order_Items, each linked to a Product.
- Users
can add multiple Products to their Shopping_Cart.
- Users
can leave multiple Reviews for multiple Products.
Conclusion
This structure provides a
comprehensive framework for your e-commerce platform, allowing you to manage
users, products, orders, and more. Adjust the schema based on your specific
application requirements, and ensure to create the necessary foreign key constraints
to maintain data integrity.