E-Commerce Platform Using React.js, Node.js with MySQL database

Rashmi Mishra
0

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

  1. User Authentication:
    • Registration and login functionality.
    • Password reset option.
  2. Product Browsing:
    • Display a list of products with filtering options (by category, price, etc.).
    • View detailed product information including images, descriptions, and prices.
  3. Shopping Cart:
    • Add products to the shopping cart.
    • Update item quantities or remove items from the cart.
    • View total cart value.
  4. Checkout Process:
    • Enter shipping and billing information.
    • View order summary before confirmation.
    • Integrate payment gateways for secure transactions.
  5. Order History:
    • Users can view their past orders and details of each order.
    • Track the status of current orders.
  6. User Profile Management:
    • View and update personal information.
    • Change passwords and manage account settings.
  7. Search Functionality:
    • Search for products by name, category, or keywords.
  8. Reviews and Ratings:
    • Leave reviews and ratings for purchased products.

Admin Features

  1. Admin Dashboard:
    • Overview of key metrics (total sales, number of users, etc.).
    • Quick access to management features.
  2. Product Management:
    • Add, edit, or delete products from the inventory.
    • Manage product categories and attributes (size, color, etc.).
    • Upload product images.
  3. User Management:
    • View and manage user accounts.
    • Approve or block user accounts as needed.
  4. Order Management:
    • View all orders placed by users.
    • Update order status (e.g., pending, shipped, delivered).
    • Process returns and refunds.
  5. Analytics and Reports:
    • Generate reports on sales, user activity, and inventory status.
    • Insights into product performance and user behavior.
  6. Content Management:
    • Manage promotional banners, discounts, and announcements.

General Features

  1. Responsive Design:
    • Ensure the application is accessible on various devices, including desktops, tablets, and mobile phones.
  2. Secure Payment Processing:
    • Utilize secure payment gateways for transactions, ensuring user data protection.
  3. Error Handling and Validation:
    • Implement input validation and error handling throughout the application to enhance user experience and security.
  4. Notification System:
    • Notify users about order status updates, promotional offers, and other relevant information via email or in-app notifications.
  5. 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

  1. config/db.js: Configures the database connection using a library like Sequelize or Knex.
  2. config/config.js: Contains application configuration variables, such as JWT secrets and database credentials.
  3. 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).
  4. middleware/:
    • authMiddleware.js: Middleware to verify JWT and protect routes.
    • errorMiddleware.js: Middleware for centralized error handling.
  5. 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.
  6. 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.
  7. utils/validation.js: Contains functions for validating user input (e.g., registration and product data).
  8. uploads/: Directory for storing product images or other uploaded files.
  9. .env: File to store environment variables, ensuring sensitive information is not hard-coded.
  10. server.js: Main server file that initializes the Express app, middleware, and routes.
  11. package.json: Lists the dependencies and scripts for the backend.

Frontend

  1. public/index.html: The main HTML file that serves the React application.
  2. public/favicon.ico: The favicon for the application.
  3. src/api/api.js: Contains functions to make API requests to the backend.
  4. 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.
  5. src/contexts/:
    • AuthContext.js: Context for managing authentication state across the app.
    • CartContext.js: Context for managing the shopping cart state.
  6. src/hooks/useAuth.js: Custom hook to handle authentication-related logic.
  7. 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.
  8. src/styles/App.css: Main CSS file for styling the application.
  9. src/App.js: Main component that renders the application layout and includes routing.
  10. src/index.js: Entry point for the React application, rendering the App component.
  11. 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

  1. Install Node.js:
    • Download and install Node.js from nodejs.org. Node.js includes npm (Node Package Manager), which is essential for managing dependencies.
  2. Install MySQL:
    • Download and install MySQL from mysql.com. Follow the installation instructions and create a new database for your project.
  3. Install a Code Editor:
    • Use a code editor like Visual Studio Code for writing your code. It provides a good environment for JavaScript development.
  4. 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

  1. Create Project Directory:
    • Open your terminal and create a new directory for your project:

mkdir ecommerce-platform

cd ecommerce-platform

  1. 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

  1. Navigate to Backend Folder:

cd backend

  1. Initialize Node.js Project:
    • Run the following command to create a package.json file:

npm init -y

  1. Install Required Packages:
    • Install Express, MySQL, and other necessary packages:

npm install express mysql2 dotenv cors bcryptjs jsonwebtoken body-parser

  1. 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}`);

});

  1. 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;

  1. 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.
  2. 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.
  3. Create API Routes:
    • Set up routes for user authentication, product management, and order processing in the routes folder.

Step 4: Setting Up the Frontend

  1. Navigate to Frontend Folder:

cd ../frontend

  1. Create React App:
    • Use Create React App to initialize your frontend:

npx create-react-app .

  1. Install Axios:
    • Install Axios to handle API requests:

npm install axios react-router-dom

  1. 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;

  1. Create Components:
    • Create components for the Navbar, User Dashboard, Product Listings, Shopping Cart, and Admin Dashboard.
  2. Manage State with Context or Redux:
    • For managing global state (like user authentication and cart items), consider using Context API or Redux.
  3. Connect to Backend:
    • Use Axios to send API requests from your React components to your Node.js backend.

Step 5: Implementing Features

  1. User Authentication:
    • Implement user registration and login forms in your React app. Store the JWT token in local storage or context for authenticated routes.
  2. Product Management:
    • Create pages to display products, filter and sort them, and allow users to add them to their shopping cart.
  3. Shopping Cart Functionality:
    • Implement the shopping cart feature where users can view, add, update, and remove items.
  4. Checkout Process:
    • Create a checkout page where users can enter their shipping information and payment details.
  5. Admin Panel:
    • Implement an admin panel where administrators can add, edit, or remove products and manage orders and users.
  6. Order History:
    • Allow users to view their order history and track their orders.

Step 6: Testing the Application

  1. Test API Endpoints:
    • Use tools like Postman to test your API endpoints for user registration, product management, and order processing.
  2. Test Frontend Functionality:
    • Ensure all components are functioning as expected, including navigation, forms, and API integrations.
  3. Debug and Fix Issues:
    • Use console logs and error messages to debug any issues that arise during testing.

Step 7: Deploying the Application

  1. Choose a Hosting Platform:
    • For the backend, consider using platforms like Heroku, DigitalOcean, or AWS. For the frontend, use services like Vercel or Netlify.
  2. Configure Environment Variables:
    • Make sure to set up environment variables for your database connection and JWT secret in your hosting platform.
  3. Deploy:
    • Follow the deployment instructions for your chosen platform to deploy both the backend and frontend.

Step 8: Maintenance and Iteration

  1. Monitor Performance:
    • After deployment, monitor the application for any performance issues or bugs.
  2. Gather User Feedback:
    • Ask users for feedback to identify areas for improvement.
  3. 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.

Post a Comment

0Comments

Post a Comment (0)