Skip to main content
MohitKoli.

React se eCommerce website kaise banaye (step by step)

Mohit Koli

Mohit Koli

Senior Full Stack Developer

April 3, 2026

15 min read

React se eCommerce website kaise banaye (step by step)

React se eCommerce website kaise banaye (step by step)

Aaj kal sab online store bana rahe hain. Koi fashion products bech raha hai, koi electronics, koi handmade gifts. Lekin jab aap khud start karte ho, sabse pehla sawal hota hai: React eCommerce website kaise banaye without getting confused by too many files, tools, and tutorials.

Is guide me hum practical tareeke se ek basic eCommerce website banayenge jisme product listing, cart system, backend API, MongoDB connection, aur frontend-backend integration hoga. Language simple Hinglish rahegi aur focus implementation par hoga, theory overload par nahi.

What You Will Build

Final project ek simple eCommerce website hogi jisme user products dekh sakega, cart me items add kar sakega, aur backend se live product data fetch hoga.

  • Homepage par product listing page
  • Reusable product card component
  • Add to cart button and basic cart counter
  • Remove from cart option
  • Products API from Node.js backend
  • MongoDB database for storing products

Ye foundation same project me later checkout, login, and payment add karne ke kaam aayegi.

Tech Stack Explanation

React

React frontend ke liye use hoga. Ek baar `ProductCard` component ban gaya to aap usko 10 products ke liye bhi use kar sakte ho aur 100 ke liye bhi.

Node.js + Express

Backend me Express routes banayega jahan se products fetch honge. Later yehi backend login, orders, payment callbacks, and admin APIs bhi handle karega.

MongoDB

MongoDB me products store honge. Name, price, image, stock, category jaise fields ko document format me rakhna beginner ke liye easy hota hai.

Payment Gateway (Optional)

Payment ke liye Indian store me Razorpay practical first choice hai, aur use baad me add kiya ja sakta hai. Pehle foundation build karo. Payment tabhi smooth lagegi jab listing aur cart pehle se sahi kaam kar rahe hon.

Versions used in this guide (September 2026)

  • React 19.3 (released 9 September 2026)
  • Vite 8 (released 12 March 2026, Rolldown bundler, Node.js 20.19+ ya 22.12+ chahiye)
  • Node.js 24 'Krypton' LTS install karo. Node.js 26 5 May 2026 se Current hai aur October 2026 me LTS banega.
  • Express 5.2.1 (Node.js 18+)
  • Mongoose 9.10.0 (Node.js 20.19+)
  • react-router 8.3.1 (v8 me react-router-dom package remove ho gaya)

React team ne Create React App ko 14 February 2025 ko sunset kar diya tha, isliye ye guide Vite use karti hai.

Project Setup (Step by Step)

1. Frontend Setup

npm create vite@latest client -- --template react
cd client
npm install
npm install axios react-router

`axios` API calls ke liye aur `react-router` future pages jaise cart, product details, login ke liye helpful rahega. React Router v8 (17 June 2026) me `react-router-dom` package remove ho gaya, isliye import bhi `react-router` se karo, jaise `import { BrowserRouter, Routes, Route } from "react-router"`.

2. Backend Setup

mkdir server
cd server
npm init -y
npm install express mongoose cors

September 2026 me ye command Express 5 (5.2.1) aur Mongoose 9 (9.10.0) install karti hai. Mongoose 9 ke liye Node.js 20.19 ya newer chahiye, isliye pehle `node -v` check karo. `nodemon` aur `dotenv` ab optional hain.

Run the server without nodemon (Node 22+)

"scripts": {
  "dev": "node --watch --env-file=.env server.js"
}

`--watch` file change hone par server restart karta hai (Node 22.0.0 se stable), aur `--env-file` `.env` ko `process.env` me load karta hai (Node 24.10.0 aur 22.21.0 se non-experimental). Is script ke saath `require("dotenv").config()` ki zarurat nahi, isliye neeche `server.js` me wo line comment me hai. Purane Node par nodemon aur dotenv fallback hain.

3. Basic Folder Structure

project/
  client/
    src/
      components/
        ProductCard.jsx
        Navbar.jsx
      pages/
        Home.jsx
        Cart.jsx
      App.jsx
      main.jsx
    index.html
  server/
    models/
      Product.js
    routes/
      productRoutes.js
    server.js
    .env

Vite React project me entry file `src/main.jsx` hoti hai, aur `index.html` `public/` me nahi balki `client/` root par hoti hai. Ye structure beginner-friendly hai aur future scaling ke liye bhi clean base deta hai.

Frontend Development

Product Listing Page

Shuruat me static data se kaam karo. Jab UI ready ho jaye tab API connect karna easy hota hai.

import ProductCard from "../components/ProductCard";

const products = [
  { id: 1, name: "T-Shirt", price: 499, image: "/images/tshirt.jpg" },
  { id: 2, name: "Shoes", price: 1499, image: "/images/shoes.jpg" },
  { id: 3, name: "Watch", price: 1999, image: "/images/watch.jpg" },
];

function Home() {
  return (
    <div className="product-grid">
      {products.map((product) => (
        <ProductCard key={product.id} product={product} />
      ))}
    </div>
  );
}

export default Home;

Product Card Component

function ProductCard({ product, addToCart }) {
  return (
    <div className="card">
      <img src={product.image} alt={product.name} />
      <h3>{product.name}</h3>
      <p>Rs. {product.price}</p>
      <button onClick={() => addToCart(product)}>
        Add to Cart
      </button>
    </div>
  );
}

export default ProductCard;

Basic UI CSS

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  padding: 20px;
}

.card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  background: #ffffff;
}

.card img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
}

.card button {
  margin-top: 10px;
  background: #111827;
  color: #fff;
  border: none;
  padding: 10px 14px;
  border-radius: 6px;
  cursor: pointer;
}

Beginner phase me simple and working UI best hoti hai. Fancy design baad me bhi add ki ja sakti hai.

Backend Development (Node.js)

Create Server

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
// .env ko "npm run dev" (node --watch --env-file=.env) load karega.
// Purane Node par: npm install dotenv, phir yahan require("dotenv").config();

const app = express();

app.use(cors());
app.use(express.json()); // request body ko parse karega

mongoose
  .connect(process.env.MONGO_URI)
  .then(() => console.log("MongoDB connected"))
  .catch((error) => console.log(error));

app.get("/", (req, res) => {
  res.send("API is running");
});

app.listen(5000, () => {
  console.log("Server running on port 5000");
});

Create Product Model

const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true },
  image: { type: String, required: true },
  category: { type: String, required: true },
  stock: { type: Number, default: 0 },
});

module.exports = mongoose.model("Product", productSchema);

Basic Products Route

const express = require("express");
const router = express.Router();
const Product = require("../models/Product");

// Sabhi products bhejne ke liye
router.get("/", async (req, res) => {
  try {
    const products = await Product.find();
    res.json(products);
  } catch (error) {
    res.status(500).json({ message: "Server error" });
  }
});

module.exports = router;

Is route ko `server.js` me import karke use karo:app.use("/api/products", productRoutes);

Express 5 note: async handler me error throw ho ya awaited promise reject ho, to error automatically error-handling middleware tak chala jata hai. Isliye `const products = await Product.find(); res.json(products);` bina try/catch ya `next(err)` ke bhi kaam karta hai.

Connecting Frontend + Backend

Ab hum static data hata kar backend se products fetch karenge. Ye step bohot important hai kyunki isi ke baad aapka frontend real database-driven app ban jata hai.

import { useEffect, useState } from "react";
import axios from "axios";
import ProductCard from "../components/ProductCard";

function Home({ addToCart }) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    axios
      .get("http://localhost:5000/api/products")
      .then((response) => setProducts(response.data))
      .catch((error) => console.log(error));
  }, []);

  return (
    <div className="product-grid">
      {products.map((product) => (
        <ProductCard
          key={product._id}
          product={product}
          addToCart={addToCart}
        />
      ))}
    </div>
  );
}

export default Home;

Yaha full stack flow clear ho jata hai: frontend data ko dikhata hai, backend data ko serve karta hai, aur database data ko store karta hai.

Cart System

Cart functionality core feature hai. Agar refresh ke baad cart empty ho jaye, to site incomplete lagti hai. Isliye state ke saath `localStorage` bhi use karenge.

Add to Cart

import { useEffect, useState } from "react";

function App() {
  const [cart, setCart] = useState(() => {
    const savedCart = localStorage.getItem("cart");
    return savedCart ? JSON.parse(savedCart) : [];
  });

  const addToCart = (product) => {
    const updatedCart = [...cart, product];
    setCart(updatedCart);
    localStorage.setItem("cart", JSON.stringify(updatedCart));
  };

  return <Home addToCart={addToCart} />;
}

Remove from Cart

const removeFromCart = (id) => {
  const updatedCart = cart.filter((item) => item._id !== id);
  setCart(updatedCart);
  localStorage.setItem("cart", JSON.stringify(updatedCart));
};

Beginner level ke liye ye enough hai. Agar aap quantity, subtotal, coupon, ya per-user cart chahte ho, to later Context API ya Redux add kar sakte ho.

Bonus (Optional)

Authentication Basic Idea

Login and signup add karne ke liye aap JWT-based authentication use kar sakte ho. Isse user account, order history, aur saved address manage kar payega.

Payment Integration Overview (Razorpay first)

Payment gateway integrate karte waqt general flow hota hai: cart items lo, backend me total calculate karo, payment session create karo, success callback ke baad order save karo. India audience ke liye Razorpay, ya UPI wala koi aur Indian gateway, practical default hai. Stripe tabhi option hai jab Stripe ne aapke business ko invite kiya ho (focus international expansion par hai), isliye ye beginner path nahi hai.

Razorpay ki standard pricing: har successful domestic transaction par 2% plus 18% GST, koi setup, annual maintenance ya refund fee nahi, aur international cards par up to 3%. Razorpay ke blog ke according, jo merchants 1 July 2026 ya uske baad KYC complete karke activate hote hain, unhe ₹199 plus tax ki one-time KYC fee ke baad domestic payments par ₹5 lakh cumulative volume ya 90 days (jo pehle ho) tak koi platform fee nahi lagti, one redemption per PAN ya bank account, uske baad standard 2% plus GST. Ye offer pricing page par nahi dikhta, isliye dashboard me confirm karo.

Common Errors + Fix

CORS Error Fix

Agar browser me error aaye ki frontend backend se baat nahi kar paa raha, to backend me `cors()` middleware enable karo. Vite dev server `localhost:5173` par chalta hai aur Express API `localhost:5000` par, dono different origins hain, isliye development me bhi `cors()` chahiye (ya Vite ka `server.proxy` `/api` requests ko port 5000 par forward kar sakta hai).

Module Not Found Fix

Ye error tab aata hai jab package install nahi hota ya import path galat hota hai. Quick checklist:

  • `npm install` dobara run karo
  • Import spelling aur file extension check karo
  • Folder structure match karwao
  • Server ya React app restart karo

MongoDB Connection Error

`.env` file me `MONGO_URI` sahi hai ya nahi check karo. Atlas use kar rahe ho to network access aur username-password bhi verify karo.

Express 5 / Mongoose 9 upgrade gotchas

  • Express 5 me route syntax badla hai: wildcards ka naam dena padta hai (`/*` ki jagah `/*splat`), optional `?` ab braces me likhte hain jaise `/:file{.:ext}`, aur paths me regex characters support nahi hote. Async errors automatically error handler tak jaate hain, isliye `.catch(next)` optional hai.
  • Mongoose 9 me pre middleware ko `next()` nahi milta (async functions use karo), `findOneAndUpdate` me `new: true` deprecated hai isliye `returnDocument: 'after'` use karo, aur update pipelines default me blocked hain jab tak `{ updatePipeline: true }` pass na karo.
  • Purana snippet unexplained errors de, to tutorial wale versions pin karo.

Conclusion

Ab aapke paas ek clear roadmap hai ki React eCommerce website kaise banaye step by step. Humne frontend setup, reusable components, backend server, MongoDB model, API routes, aur cart storage tak ka full flow cover kiya.

Sabse important lesson ye hai ki project ko small milestones me build karo: pehle listing, phir API, phir cart, phir auth, phir payment.

Next step ke liye aap single product page, search bar, category filter, order summary, and checkout page add kar sakte ho. Agar React roadmap aur full stack direction aur strong karni hai, to React learning article aur frontend vs backend guide bhi padho. Chhota start karo, but complete build karo. Wahi real progress hoti hai.

FAQs

Kya React se full eCommerce website ban sakti hai?

Haan. React frontend ke liye strong hai, aur Node.js, Express, MongoDB ke saath milkar full eCommerce app easily ban sakta hai.

Kya React eCommerce project me Redux zaroori hai?

Nahi. Small projects me `useState` ya Context API enough hota hai. Redux tab use karo jab app ka state bohot complex ho jaye.

Kya backend ke bina shopping website bana sakte hain?

Demo ya portfolio project ke liye haan, but real eCommerce website ke liye backend almost mandatory hai.

Cart data kaha store karna chahiye?

Beginner project ke liye React state plus localStorage best hai. Logged-in users ke liye backend sync aur bhi better hota hai.

Is project ko deploy kaha kar sakte hain?

Frontend ko Vercel ya Netlify par, backend ko Render, Railway, ya VPS par, aur database ko MongoDB Atlas par deploy kar sakte ho. Kuch caveats: Render free web service 15 minutes bina traffic ke spin down ho jati hai aur wake hone me about a minute lagta hai; Railway ka free plan one-time $5, 30-day trial ke baad $1 credit per month deta hai (Hobby $5/month); Vercel ka $0 Hobby plan personal, non-commercial use ke liye hai, isliye real store ke liye Pro ($20/month) ya apni hosting chahiye; aur Atlas free cluster me 0.5 GB storage milta hai.

Related reading

Further reading from trusted sources

Cross-checked references from primary, authoritative sources — useful if you want to go deeper on this topic.