Creating a fully functional eCommerce store involves combining several components—frontend design, backend logic, database management, user authentication, product management, and payment integration. I’ll guide you through generating a complete eCommerce store using the MERN stack (MongoDB, Express.js, React, Node.js), with added Stripe integration for payments.
🔧 Tech Stack
- Frontend: React.js (with React Router)
- Backend: Node.js + Express.js
- Database: MongoDB (via Mongoose ORM)
- Authentication: JWT (JSON Web Tokens)
- Payments: Stripe API
📁 Project Structure
ecommerce-store/
├── backend/
│ ├── models/
│ ├── routes/
│ ├── controllers/
│ ├── middleware/
│ ├── server.js
├── frontend/
│ ├── src/
│ │ ├── components/
│ │ ├── pages/
│ │ ├── App.js
│ │ ├── index.js
│ ├── public/
├── .env
├── package.json (for root and separately for backend & frontend)
🛠️ BACKEND CODE (Node + Express)
1. server.js
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import productRoutes from './routes/productRoutes.js';
import userRoutes from './routes/userRoutes.js';
import orderRoutes from './routes/orderRoutes.js';
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log('MongoDB connected'))
.catch((err) => console.error(err));
app.use('/api/products', productRoutes);
app.use('/api/users', userRoutes);
app.use('/api/orders', orderRoutes);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));
2. Product Model models/Product.js
import mongoose from 'mongoose';
const productSchema = mongoose.Schema({
name: String,
description: String,
price: Number,
imageUrl: String,
category: String,
stock: Number,
}, { timestamps: true });
export default mongoose.model('Product', productSchema);
3. User Model models/User.js
import mongoose from 'mongoose';
import bcrypt from 'bcrypt';
const userSchema = mongoose.Schema({
name: String,
email: { type: String, unique: true },
password: String,
isAdmin: { type: Boolean, default: false },
}, { timestamps: true });
userSchema.pre('save', async function () {
if (!this.isModified('password')) return;
this.password = await bcrypt.hash(this.password, 10);
});
export default mongoose.model('User', userSchema);
4. Product Routes routes/productRoutes.js
import express from 'express';
import Product from '../models/Product.js';
const router = express.Router();
// Get all products
router.get('/', async (req, res) => {
const products = await Product.find();
res.json(products);
});
// Get single product
router.get('/:id', async (req, res) => {
const product = await Product.findById(req.params.id);
res.json(product);
});
export default router;
5. User Authentication Routes routes/userRoutes.js
(Simplified - login/register)
import express from 'express';
import User from '../models/User.js';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
const router = express.Router();
router.post('/register', async (req, res) => {
const { name, email, password } = req.body;
try {
const exists = await User.findOne({ email });
if (exists) return res.status(400).json({ message: 'Email in use' });
const user = await User.create({ name, email, password });
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
res.json({ user, token });
} catch (err) {
res.status(500).json({ message: err.message });
}
});
router.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
res.json({ user, token });
});
export default router;
6. Order Routes routes/orderRoutes.js
import express from 'express';
const router = express.Router();
// Dummy route for checkout
router.post('/checkout', (req, res) => {
const { items } = req.body;
// In production: validate items, process order, integrate with Stripe
res.json({ message: 'Order placed successfully', items });
});
export default router;
7. .env Example
MONGO_URI=mongodb://localhost:27017/ecommerce
JWT_SECRET=your_jwt_secret
STRIPE_SECRET_KEY=your_stripe_key
🖼️ FRONTEND CODE (React)
1. App.js
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import Cart from './pages/Cart';
import ProductDetail from './pages/ProductDetail';
import Login from './pages/Login';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/product/:id" element={<ProductDetail />} />
<Route path="/cart" element={<Cart />} />
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
);
}
export default App;
2. Home.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
const Home = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
axios.get('/api/products').then(res => setProducts(res.data));
}, []);
return (
<div>
<h2>Products</h2>
<div>
{products.map((product) => (
<div key={product._id}>
<Link to={`/product/${product._id}`}>
<img src={product.imageUrl} alt={product.name} width="150" />
<h3>{product.name}</h3>
<p>${product.price}</p>
</Link>
</div>
))}
</div>
</div>
);
};
export default Home;
3. ProductDetail.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';
const ProductDetail = () => {
const { id } = useParams();
const [product, setProduct] = useState(null);
useEffect(() => {
axios.get(`/api/products/${id}`).then(res => setProduct(res.data));
}, [id]);
if (!product) return <p>Loading...</p>;
return (
<div>
<img src={product.imageUrl} alt={product.name} width="200" />
<h2>{product.name}</h2>
<p>${product.price}</p>
<p>{product.description}</p>
<button>Add to Cart</button>
</div>
);
};
export default ProductDetail;
4. Add to Cart, Checkout, and Stripe Integration
In the Stripe integration phase, use Stripe Checkout or Stripe Elements. Here’s a very basic example (you need Stripe API keys):
npm install @stripe/stripe-js react-stripe-checkout
Then in products or cart component:
import StripeCheckout from 'react-stripe-checkout';
const handleToken = (token, addresses) => {
// Send token and cart data to server
};
<StripeCheckout
stripeKey="your-stripe-public-key"
token={handleToken}
amount={product.price * 100}
name="E-Shop Checkout"
/>
Then in your backend, use Stripe Node SDK to process the payment on the /checkout endpoint.
✅ Final Touches
- Add cart context to handle cart globally
- Add admin dashboard (CRUD for products)
- Add auth protection
- Add shipping info and order history
🚀 Deployment
- Frontend: Deploy on Vercel, Netlify, or Firebase Hosting
- Backend: Deploy on Render, Railway, Heroku, or VPS
- Database: MongoDB Atlas (cloud-hosted MongoDB)
💾 Starter Code Repository
If you'd like a starter repo to work with, I can generate a GitHub Gist or link you to a GitHub template. Let me know!
Would you like this entire project zipped and downloadable? Or deployed live?