Creating a full functional eCommerce store is a complex task that involves frontend, backend, database, payment integration, and hosting. Below is a simplified but fully functional example using:
- Frontend: React
- Backend: Node.js with Express
- Database: MongoDB (via Mongoose)
- Payment Integration: Stripe (for payments)
- Hosting Suggestions: Vercel (frontend), Render or Railway (backend), MongoDB Atlas (database)
⚠️ Note: For brevity, this is a minimal version. A production-ready store would require authentication, validation, error handling, admin panel, etc.
🛒 1. Project Structure
ecommerce-store/
├── client/ # React frontend
│ ├── public/
│ └── src/
│ ├── components/
│ ├── pages/
│ ├── App.js
│ └── index.js
├── server/ # Express backend
│ ├── models/
│ ├── routes/
│ ├── controllers/
│ └── server.js
└── README.md
🧑💻 2. Backend Setup (Node.js + Express + MongoDB)
📁 server/server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const productRoutes = require('./routes/productRoutes');
const orderRoutes = require('./routes/orderRoutes');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log("MongoDB connected"))
.catch(err => console.error(err));
// Routes
app.use('/api/products', productRoutes);
app.use('/api/orders', orderRoutes);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
📁 server/models/Product.js
const mongoose = require('mongoose');
const ProductSchema = new mongoose.Schema({
name: String,
price: Number,
description: String,
image: String,
});
module.exports = mongoose.model('Product', ProductSchema);
📁 server/models/Order.js
const mongoose = require('mongoose');
const OrderSchema = new mongoose.Schema({
products: [
{
product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
quantity: Number,
},
],
totalAmount: Number,
user: { name: String, email: String },
});
module.exports = mongoose.model('Order', OrderSchema);
📁 server/routes/productRoutes.js
const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
router.get('/', async (req, res) => {
const products = await Product.find();
res.json(products);
});
module.exports = router;
📁 server/routes/orderRoutes.js
const express = require('express');
const router = express.Router();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const Order = require('../models/Order');
const Product = require('../models/Product');
router.post('/create', async (req, res) => {
const { products, totalAmount, user } = req.body;
// Create Stripe Checkout Session
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: products.map(item => ({
price_data: {
currency: 'usd',
product_data: {
name: item.product.name,
},
unit_amount: item.product.price * 100,
},
quantity: item.quantity,
})),
mode: 'payment',
success_url: 'http://localhost:3000/success',
cancel_url: 'http://localhost:3000/cancel',
metadata: { orderId: Date.now().toString(), user }
});
// Save order in DB (simplified - in prod save after payment success)
const order = new Order({ products, totalAmount, user });
await order.save();
res.json({ id: session.id });
});
module.exports = router;
⚠️ Stripe expects prices in cents. You should ideally fetch real Stripe Product IDs and Prices for production.
💻 3. Frontend Setup (React)
📁 client/src/App.js
import React, { useState, useEffect } from 'react';
import './App.css';
import ProductList from './components/ProductList';
import CheckoutForm from './components/CheckoutForm';
function App() {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState([]);
const [checkout, setCheckout] = useState(false);
useEffect(() => {
fetch('http://localhost:5000/api/products')
.then(res => res.json())
.then(data => setProducts(data));
}, []);
const addToCart = (product) => {
setCart([...cart, { product, quantity: 1 }]);
};
const removeFromCart = (index) => {
const newCart = [...cart];
newCart.splice(index, 1);
setCart(newCart);
};
const updateQuantity = (index, qty) => {
const newCart = [...cart];
newCart[index].quantity = qty;
setCart(newCart);
};
const getTotal = () =>
cart.reduce((sum, item) => sum + item.product.price * item.quantity, 0);
const handleCheckout = async () => {
const orderData = {
products: cart.map(item => ({
product: item.product._id,
quantity: item.quantity,
})),
totalAmount: getTotal(),
user: { name: "Test User", email: "test@example.com" },
};
const res = await fetch('http://localhost:5000/api/orders/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(orderData),
});
const { id } = await res.json();
setCheckout(true);
window.location.href = `https://checkout.stripe.com/pay/${id}`;
};
return (
<div className="App">
<h1>🛍️ Simple Ecommerce Store</h1>
{checkout ? (
<div>Redirecting to checkout...</div>
) : (
<>
<ProductList products={products} onAddToCart={addToCart} />
<CheckoutForm
cart={cart}
onUpdateQuantity={updateQuantity}
onRemove={removeFromCart}
total={getTotal()}
onCheckout={handleCheckout}
/>
</>
)}
</div>
);
}
export default App;
📁 client/src/components/ProductList.js
import React from 'react';
function ProductList({ products, onAddToCart }) {
return (
<div className="product-list">
{products.map(product => (
<div key={product._id} className="card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>${product.price}</p>
<p>{product.description}</p>
<button onClick={() => onAddToCart(product)}>Add to Cart</button>
</div>
))}
</div>
);
}
export default ProductList;
📁 client/src/components/CheckoutForm.js
import React from 'react';
function CheckoutForm({ cart, onUpdateQuantity, onRemove, total, onCheckout }) {
return (
<div className="checkout">
<h2>Your Cart</h2>
{cart.map((item, index) => (
<div key={index} className="cart-item">
<img src={item.product.image} alt={item.product.name} width="50" />
<span>{item.product.name} x {item.quantity}</span>
<input
type="number"
min="1"
value={item.quantity}
onChange={(e) => onUpdateQuantity(index, parseInt(e.target.value))}
/>
<button onClick={() => onRemove(index)}>Remove</button>
</div>
))}
<h3>Total: ${total.toFixed(2)}</h3>
<button onClick={onCheckout}>Proceed to Checkout</button>
</div>
);
}
export default CheckoutForm;
📁 client/src/App.css (basic styles)
.App {
text-align: center;
padding: 20px;
}
.product-list {
display: flex;
gap: 20px;
flex-wrap: wrap;
justify-content: center;
}
.card {
border: 1px solid #ddd;
padding: 10px;
width: 250px;
}
.checkout {
margin-top: 30px;
border-top: 2px solid #333;
padding-top: 20px;
}
.cart-item {
display: flex;
align-items: center;
justify-content: space-between;
margin: 10px 0;
}
🔐 4. Stripe Setup
- Go to https://dashboard.stripe.com/test/apikeys
- Grab your
STRIPE_SECRET_KEY and publishableKey (not used here directly)
- Add to
.env in /server:
MONGO_URI=mongodb+srv://...
STRIPE_SECRET_KEY=sk_test_...
PORT=5000
🚀 5. Running the App
Backend
cd server
npm install
npm start
Frontend
cd client
npm install
npm start
Visit http://localhost:3000
✅ Features Included
- View Products
- Add to Cart
- Update Quantity
- Checkout with Stripe
- Basic Order Logging
🛠️ Next Steps for Production
- Authentication (JWT / OAuth)
- Admin Dashboard
- Payment Success/Failure Webhooks
- Email Receipts (SendGrid, etc.)
- Product Categories, Search, Pagination
- Better Error Handling & Validation
- Persistent Cart (localStorage/sessionStorage or DB)
Would you like me to package this into downloadable GitHub repos or add additional features like user login?