Skip to content

Repository files navigation

πŸ›’ Veloce β€” Premium E-Commerce Platform

A full-stack, production-grade e-commerce application built with modern web technologies.

Next.js FastAPI Python MySQL Clerk Docker Razorpay


πŸ“‹ Table of Contents


🌟 Overview

Veloce is a premium, full-stack e-commerce platform designed for real-world production use. It features a stunning glassmorphic dark-mode storefront, a comprehensive admin analytics dashboard, concurrency-safe checkout with row-level database locking, Razorpay payment integration (INR β‚Ή), and externalized authentication via Clerk.

This project was built as part of the BITS Pilani coursework, demonstrating enterprise-grade patterns including idempotent APIs, inventory auditing, multi-status order lifecycle management, and Docker-based deployment. The backend was recently modernized and fully rewritten in Python using FastAPI and MySQL.


✨ Key Features

πŸ›οΈ Customer Experience

  • Product Catalog β€” Browse, search, filter by category/price, and sort products with pagination
  • Product Variants β€” Size, color, and material options per product with independent stock tracking
  • Shopping Cart β€” Persistent server-side cart with animated mini-cart slide-out panel
  • Wishlist β€” Save products for later with one-click add-to-cart
  • Order Management β€” Full order history with real-time status tracking (pending β†’ processing β†’ shipped β†’ delivered)
  • Reviews & Ratings β€” 1–5 star reviews tied to purchased order items
  • Coupon System β€” Percentage or fixed-amount discount codes with usage limits and expiration dates
  • User Profile β€” Manage multiple shipping/billing addresses

πŸ” Security & Auth

  • Clerk Authentication β€” Externalized sign-up, sign-in, and session management
  • Role-Based Access Control β€” CUSTOMER and ADMIN roles stored in the database
  • Auto User Provisioning β€” First-time Clerk users are automatically synced to the local MySQL database with a shopping cart created on the fly
  • Manual JWT Verification β€” Uses python-jose to fetch JWKS public keys and manually verify tokens for zero-trust security

πŸ“Š Admin Dashboard

  • Revenue Analytics β€” Interactive charts powered by Recharts showing revenue trends over time
  • Product Management β€” Full CRUD for products, variants, images, and categories
  • Order Management β€” View all orders, update statuses, process refunds
  • Coupon Management β€” Create, disable, and track coupon usage
  • Inventory Logs β€” Complete audit trail of every stock change (checkout, cancellation, manual adjustment)

πŸ’³ Payments

  • Razorpay Integration β€” Supports live and test modes for card payments (INR β‚Ή)
  • Cash on Delivery (COD) β€” Alternative payment method
  • Webhook Processing β€” Idempotent webhook handler with duplicate event protection
  • Refund System β€” Full and partial refund support with automatic stock restoration

⚑ Concurrency & Reliability

  • Row-Level Locking β€” SELECT ... FOR UPDATE on variants and coupons during checkout to prevent overselling
  • Idempotent Checkout β€” X-Idempotency-Key header prevents duplicate orders from double-clicks or network retries
  • Stock Restoration Guards β€” stockRestored flag ensures inventory is restored at most once per order (cancel/refund)
  • Order Expiry β€” Unpaid card orders expire after a configurable window, releasing reserved inventory

πŸ› οΈ Tech Stack

Frontend

Technology Version Purpose
Next.js 16.2 React framework with App Router, SSR, and static generation
React 19.2 UI component library
TypeScript 5.x Type-safe development
Tailwind CSS 4.x Utility-first styling with dark mode
Framer Motion 12.x Page transitions, animations, and micro-interactions
Recharts 3.x Admin analytics charts
Clerk Next.js SDK 7.x Authentication components (<SignIn>, <UserButton>)

Backend

Technology Version Purpose
Python 3.12 Core programming language
FastAPI 0.115 Asynchronous REST API framework
SQLAlchemy 2.0 ORM for database modeling and queries
Pydantic 2.11 Data validation and schema generation
MySQL 8.0 Relational database with ACID transactions
Uvicorn 0.34 High-performance ASGI web server
python-jose 3.4 JWT verification and JWKS parsing
Razorpay 1.4 Payment gateway integration

DevOps & Tools

Technology Purpose
Docker & Docker Compose Containerized MySQL and FastAPI backend
Swagger UI Auto-generated interactive API documentation

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚         Frontend (Next.js)      β”‚
β”‚    Port 3000 β€’ App Router       β”‚
β”‚   Clerk Auth β€’ Tailwind CSS     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚  REST API calls
               β”‚  (Authorization: Bearer <Clerk JWT>)
               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚       Backend (FastAPI)         β”‚
β”‚    Port 8000 β€’ REST API         β”‚
β”‚   Manual JWT Verification       β”‚
β”‚   SQLAlchemy ORM β€’ Pydantic     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚  PyMySQL
               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚        MySQL 8.0 (Docker)       β”‚
β”‚    Port 3306 β€’ ACID Txns        β”‚
β”‚   Row-level locks (FOR UPDATE)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key Architectural Decisions:

  • Externalized Auth: Clerk handles all user registration, login, MFA, and session management. The FastAPI backend validates Clerk JWTs manually (fetching public keys dynamically) and syncs users to the local database.
  • Financial Precision: All monetary values use Numeric(10,2) in MySQL to avoid floating-point rounding errors.
  • Concurrency Control: Complex transactions like checkout utilize SQLAlchemy raw queries for SELECT ... FOR UPDATE to lock inventory rows temporarily.
  • Address Snapshots: Orders store JSON snapshots of shipping/billing addresses at checkout time, so address edits don't retroactively change order records.

πŸ“ Project Structure

ecommerce-project/
β”œβ”€β”€ frontend/                          # Next.js 16 Application
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app/                       # App Router pages
β”‚   β”‚   β”œβ”€β”€ components/                # Reusable UI components
β”‚   β”‚   └── lib/                       # Utilities and API client
β”‚   └── package.json
β”‚
β”œβ”€β”€ backend-fastapi/                   # FastAPI Backend
β”‚   β”œβ”€β”€ main.py                        # App entry point, CORS, startup events
β”‚   β”œβ”€β”€ database.py                    # SQLAlchemy engine & session maker
β”‚   β”œβ”€β”€ models.py                      # SQLAlchemy declarative database models
β”‚   β”œβ”€β”€ schemas.py                     # Pydantic schemas (Request/Response)
β”‚   β”œβ”€β”€ dependencies.py                # JWT Auth, User sync, DB injection
β”‚   β”œβ”€β”€ make_admin.py                  # CLI script to promote users to ADMIN
β”‚   β”œβ”€β”€ routers/                       # API Route modules
β”‚   β”‚   β”œβ”€β”€ products.py                # Product CRUD, variants, images
β”‚   β”‚   β”œβ”€β”€ orders.py                  # Checkout logic, idempotency, cancellation
β”‚   β”‚   β”œβ”€β”€ payments.py                # Razorpay order creation, webhooks, refunds
β”‚   β”‚   └── (cart, users, admin, etc.)
β”‚   β”œβ”€β”€ services/                      # Extracted business logic
β”‚   β”‚   β”œβ”€β”€ inventory.py               # Stock tracking and logging
β”‚   β”‚   └── pricing.py                 # Tax, shipping, discount calculations
β”‚   β”œβ”€β”€ Dockerfile                     # Multi-stage production build
β”‚   └── requirements.txt               # Python dependencies
β”‚
β”œβ”€β”€ docker-compose.yml                 # MySQL + FastAPI orchestration
└── README.md                          # ← You are here

πŸš€ Getting Started

Prerequisites

  • Node.js β‰₯ 20 (for frontend)
  • Python β‰₯ 3.12 (if running backend without docker)
  • Docker & Docker Compose (required for MySQL database)
  • Clerk Account β€” Sign up at clerk.com
  • Razorpay Account (optional, for payments) β€” Sign up at razorpay.com

1. Clone the Repository

git clone https://github.com/faizan-7890/ecommerce-project.git
cd ecommerce-project

2. Start Backend & Database via Docker

# Start MySQL and the FastAPI backend in detached mode
docker-compose up -d --build

This spins up:

  • MySQL 8.0 container on port 3306
  • FastAPI container on port 8000

Note: On the first startup, FastAPI will automatically connect to MySQL and create all the necessary database tables.

3. Setup Frontend

cd frontend
npm install

# Create .env.local with your Clerk publishable key
echo "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_..." > .env.local
echo "NEXT_PUBLIC_API_URL=http://localhost:8000/api" >> .env.local

# Start the development server
npm run dev

The storefront will be running at http://localhost:3000.

4. Admin Access

Authentication is handled by Clerk, so there are no default admin credentials.

  1. Sign in to the frontend using your real email/Google via Clerk.
  2. Promote yourself to Admin by running a script in the backend folder:
cd backend-fastapi
python -m venv venv
.\venv\Scripts\activate
pip install -r requirements.txt
python make_admin.py <your-email@example.com>

πŸ”‘ Environment Variables

Backend (backend-fastapi/.env)

Variable Description Example
PORT Server port 8000
NODE_ENV Environment mode development
DATABASE_URL MySQL connection string mysql+pymysql://root:root@db:3306/ecommerce
FRONTEND_URL Allowed CORS origin http://localhost:3000
CLERK_SECRET_KEY Clerk backend secret key sk_test_...
TAX_RATE Tax rate (decimal) 0.08
FREE_SHIPPING_THRESHOLD Free shipping above this amount 100
FLAT_SHIPPING_FEE Shipping fee when below threshold 10
RAZORPAY_KEY_ID Razorpay API key rzp_test_...
RAZORPAY_KEY_SECRET Razorpay API secret your_secret
RAZORPAY_WEBHOOK_SECRET Webhook signature verification your_webhook_secret

Frontend (frontend/.env.local)

Variable Description Example
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY Clerk frontend key pk_test_...
NEXT_PUBLIC_API_URL Backend API base URL http://localhost:8000/api

πŸ“‘ API Documentation

FastAPI automatically generates interactive OpenAPI documentation based on Pydantic schemas.

Once the backend is running, visit:

Base URL: http://localhost:8000/api

The API includes 11 main routers:

  • /products β€” Product catalog, variants, images
  • /cart β€” User shopping cart
  • /orders β€” Checkout, order history, cancellation
  • /payments β€” Razorpay generation, validation, webhooks
  • /users β€” Profile, addresses
  • /wishlist β€” Product wishlists
  • /reviews β€” Product ratings
  • /coupons β€” Validation and admin management
  • /admin β€” Revenue dashboard, overarching CRUD operations

πŸ—„οΈ Database Schema

The database consists of 20 tables mapped via SQLAlchemy models:

User ─┬─ Cart ── CartItem ─┬─ Product ── ProductVariant
      β”‚                     β”‚             ProductImage
      β”œβ”€ Order ── OrderItem β”˜
      β”‚    β”œβ”€β”€ Payment ── Refund
      β”‚    └── InventoryLog
      β”œβ”€ Review
      β”œβ”€ WishlistItem
      β”œβ”€ Address
      └─ AuditLog

Category ── Product
Coupon ── CouponUsage
Role ── User
ProcessedWebhookEvent (idempotency)

Key Design Decisions:

  • Numeric(10,2) for all financial fields β€” no floating-point money bugs
  • Unique Constraints β€” prevents duplicate cart entries and wishlist duplication
  • ondelete="CASCADE" β€” Enforces referential integrity at the database level
  • JSON columns β€” Stores immutable snapshots of shipping/billing addresses on Orders

πŸ” Authentication

Authentication is fully externalized to Clerk:

  1. Frontend: The <ClerkProvider> wraps the app. <SignIn>, <SignUp>, and <UserButton> components handle all auth UI.
  2. Backend: The get_current_user FastAPI dependency validates the JWT on protected endpoints using python-jose by fetching Clerk's JWKS public keys.
  3. User Sync: During authentication, the dependency automatically:
    • Looks up the Clerk user in MySQL by clerk_id
    • If not found, fetches the user's email from Clerk and either links an existing account or creates a new one
    • Assigns the CUSTOMER role and provisions an empty shopping cart
  4. Role Management: Admin roles are managed natively in the MySQL database (Role table).

πŸ’³ Payment Integration

Veloce integrates with Razorpay for INR (β‚Ή) payments:

  1. Create Order β†’ Frontend calls /payments/create-order β†’ Backend creates a Razorpay order
  2. Checkout Modal β†’ Razorpay's client-side SDK opens the payment modal
  3. Verify Signature β†’ After payment, /payments/verify validates the Razorpay signature using Python's hmac-sha256
  4. Webhook Fallback β†’ Razorpay sends webhook events to /payments/webhook for server-to-server confirmation
  5. Idempotency β†’ The ProcessedWebhookEvent model prevents duplicate webhook processing

Mock Mode: In development, if Razorpay keys are placeholder values, the FastAPI server automatically falls back to mock payment responses and validates mock signatures for local testing.


🐳 Deployment

Docker Compose (Recommended)

# Build and start all services
docker-compose up --build -d

# View logs
docker-compose logs -f backend

This starts:

  • MySQL 8.0 on port 3306 with a health check
  • FastAPI Backend on port 8000 (waits for DB to be healthy)

Production Checklist

  • Use real Clerk production keys (sk_live_... / pk_live_...)
  • Use real Razorpay production keys (rzp_live_...)
  • Configure FRONTEND_URL to your production domain for CORS
  • Disable Uvicorn reload mode in production
  • Configure Razorpay webhook URL to your production endpoint

πŸ‘¨β€πŸ’» Author

Faizan J Developer


πŸ“„ License

This project is licensed under the ISC License.


Built with ❀️ using Next.js, FastAPI, MySQL, Clerk, and Razorpay

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages