Full‑Stack E‑Commerce Store with Stripe Payments, Coupons, Redis Authentication, and React Front‑End
Overview
- Complete guide to building a production‑ready e‑commerce platform using Node.js, Express, MongoDB, Redis, Stripe, and React.
- Covers backend architecture, authentication, admin dashboard, cart & coupon logic, payment flow, analytics, state management, UI components, and deployment on Render.
Project Setup & Folder Structure
- Root folder
e‑commerce-storewith sub‑foldersbackend(API) andfrontend(React client). - Initialize with
npm init -y; settype: "module"for ES6 imports. - Install core dependencies: express, mongoose, jsonwebtoken, stripe, cookie‑parser, bcryptjs, dotenv, cors, ioredis; dev dependency nodemon.
- Add scripts:
dev(nodemon backend/server.js) andstart(node backend/server.js).
Environment Variables
Create a .env file containing:
- PORT, MONGODB_URI, JWT_ACCESS_SECRET, JWT_REFRESH_SECRET
- STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY
- UPSTASH_REDIS_URL, CLOUDINARY_NAME, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET
- CLIENT_URL (frontend URL) and optional SERVER_URL
Load with dotenv.config().
Database Models (MongoDB & Mongoose)
- User: name, email (unique, lowercase), hashed password, role (
customer/admin),cartItems(productId + qty), timestamps. - Product: name, description, price, image URL, category,
isFeatured, timestamps. - Coupon: unique code,
discountPercentage,expirationDate,activeflag, optional user reference. - Order: user reference, array of purchased items (productId, qty, price),
totalAmount, StripesessionId, timestamps.
Authentication Workflow
- Sign‑up – Validate email, hash password, create user, issue short‑lived access token (15 min) and long‑lived refresh token (7 days). Store refresh token in Upstash Redis and set both as HttpOnly cookies.
- Login – Verify password, issue new tokens, store refresh token in Redis.
- Refresh Token Endpoint – Reads cookie, validates token against Redis, issues fresh access token.
- Logout – Deletes Redis entry and clears cookies.
- Protect Middleware – Verifies access token, attaches
req.user. - Admin Middleware – Ensures
req.user.role === 'admin'.
Admin Dashboard (API)
- Create Product – Admin‑only POST; uploads image to Cloudinary, saves product.
- Read All Products – Admin‑only GET.
- Update Product – PATCH for fields like
isFeatured. - Delete Product – Removes DB record and Cloudinary image.
- Featured Products Cache – Cached in Redis; refreshed on toggle.
Cart Functionality (Protected Routes)
- Add to Cart – Increment quantity if item exists, otherwise push new entry.
- Remove All – Clears
cartItemsarray. - Update Quantity – Adjusts or removes when quantity hits zero.
- Get Cart Items – Populates product details and merges quantity.
Coupon System (Protected Routes)
- Get Current Coupon – Returns active coupon for the logged‑in user.
- Validate Coupon – Checks code existence, active flag, expiration, and ownership; returns discount percent.
Stripe Payment Integration
- Create Checkout Session – Build line items (
price * qty), apply coupon discount, callstripe.checkout.sessions.createwithpayment_method_types:['card'],mode:'payment', dynamicsuccess_url/cancel_url. - Metadata – Attach
userId,couponCode, and serialized product list for post‑payment processing. - Post‑Payment Handling – Retrieve session, verify
payment_intent.status === 'paid', deactivate used coupon, create Order document, respond with confirmation.
Redis Caching (Upstash)
- Store refresh tokens keyed by
refreshToken:{userId}with 7‑day TTL. - Cache featured products under
featuredProductsfor O(1) reads; invalidate on product update. - Use
ioredisforGET,SET,DEL.
Analytics Endpoints
- Cards Data – Total users, products, orders, and revenue (
User.countDocuments(),Product.countDocuments(), order count, sum oftotalAmount). - Weekly Chart – Aggregate orders for last 7 days, group by day, sum sales and revenue, return array for Recharts.
Frontend Setup (React + Vite)
- Initialize with
npm create vite@latest. - Install Tailwind CSS, configure
tailwind.config.jsandindex.css. - Add utility libraries:
axios,framer-motion,lucide-react,react-hot-toast,react-router-dom,recharts,zustand.
State Management with Zustand
- User Store (
useUserStore): holdsuser,loading, actionssignUp,login,logout,checkAuth. - Product Store (
useProductStore): fetches products, creates/updates/deletes, toggles featured flag. - Cart Store (
useCartStore):items,coupon,subtotal,total; actionsgetCartItems,addToCart,removeFromCart,updateQuantity,calculateTotals,clearCart. - Axios instance includes
withCredentials:true; interceptors refresh access token on 401.
UI Components
- Navbar – Shows cart count, admin link, login/logout based on auth state.
- ProductCard – Displays image, name, price, Add to Cart button with toast feedback.
- Cart Page – Lists items with quantity controls, delete icon, and placeholder when empty.
- Order Summary – Shows subtotal, discount (coupon), total, and savings.
- Coupon Component – Loads existing coupon, validates new code, removes coupon.
- Featured Products Slider – Responsive carousel using state for
currentIndexanditemsPerPage. - Analytics Dashboard –
AnalyticsCardcomponents display totals; line chart visualizes daily sales. - Success & Cancel Pages – Success clears cart, shows thank‑you message; Cancel informs user and offers to continue shopping.
Token Refresh Interceptor (Preview)
- Interceptor catches 401, calls
/api/auth/refresh-token, updates stored access token, retries original request; logs out on failure.
Deployment to Render
- Add build script
npm run buildfor React. - Configure Express to serve static files from
frontend/dist(orbuild). - Set environment variables on Render (
PORT,MONGODB_URI,STRIPE_SECRET_KEY,CLIENT_URL, etc.). - Push repo to GitHub, link to Render, deploy.
- Verify live site: authentication, cart, coupon, checkout, analytics.
Best Practices Highlighted
- Environment‑based config – Never hard‑code secrets.
- Token strategy – Short‑lived access + long‑lived server‑side refresh token.
- Password security – Bcrypt hashing with pre‑save hook.
- Cache layer – Redis for tokens and featured products.
- Modular code – Separate routes, controllers, models, middleware.
- Error handling – Consistent try/catch, meaningful HTTP status codes.
- Secure cookies –
httpOnly,securein production,sameSite: 'strict'. - Monorepo – Backend and frontend share a single
package.jsonfor unified scripts.
Final Workflow Recap
- User adds items → cart store updates.
- Checkout request builds Stripe line items, applies coupon, creates session.
- User pays on Stripe; redirected to success URL.
- Backend verifies payment, deactivates coupon, creates order.
- Analytics endpoints aggregate data for admin view.
- Admin manages products, toggles featured items, views metrics.
- Token interceptor keeps sessions alive without manual re‑login.
- Deploy to Render for a live, scalable service.
By following this end‑to‑end guide you can create a secure, scalable e‑commerce application that seamlessly integrates Stripe payments, coupon discounts, Redis‑backed authentication, real‑time analytics, and a polished React UI—ready for production deployment without needing to watch the original tutorial.
Frequently Asked Questions
Who is Codesistency on YouTube?
Codesistency is a YouTube channel that publishes videos on a range of topics. Browse more summaries from this channel below.
Does this page include the full transcript of the video?
Yes, the full transcript for this video is available on this page. Click 'Show transcript' in the sidebar to read it.
Helpful resources related to this video
If you want to practice or explore the concepts discussed in the video, these commonly used tools may help.
Links may be affiliate links. We only include resources that are genuinely relevant to the topic.