- Overview
- Key Features
- Tech Stack
- Architecture
- Project Structure
- Getting Started
- Environment Variables
- API Documentation
- Database Schema
- Authentication
- Payment Integration
- Deployment
- License
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.
- 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
- Clerk Authentication β Externalized sign-up, sign-in, and session management
- Role-Based Access Control β
CUSTOMERandADMINroles 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
- 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)
- 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
- Row-Level Locking β
SELECT ... FOR UPDATEon variants and coupons during checkout to prevent overselling - Idempotent Checkout β
X-Idempotency-Keyheader prevents duplicate orders from double-clicks or network retries - Stock Restoration Guards β
stockRestoredflag ensures inventory is restored at most once per order (cancel/refund) - Order Expiry β Unpaid card orders expire after a configurable window, releasing reserved inventory
| 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>) |
| 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 |
| Technology | Purpose |
|---|---|
| Docker & Docker Compose | Containerized MySQL and FastAPI backend |
| Swagger UI | Auto-generated interactive API documentation |
βββββββββββββββββββββββββββββββββββ
β 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 UPDATEto 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.
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
- 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
git clone https://github.com/faizan-7890/ecommerce-project.git
cd ecommerce-project# Start MySQL and the FastAPI backend in detached mode
docker-compose up -d --buildThis 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.
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 devThe storefront will be running at http://localhost:3000.
Authentication is handled by Clerk, so there are no default admin credentials.
- Sign in to the frontend using your real email/Google via Clerk.
- 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>| 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 |
| 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 |
FastAPI automatically generates interactive OpenAPI documentation based on Pydantic schemas.
Once the backend is running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
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
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 is fully externalized to Clerk:
- Frontend: The
<ClerkProvider>wraps the app.<SignIn>,<SignUp>, and<UserButton>components handle all auth UI. - Backend: The
get_current_userFastAPI dependency validates the JWT on protected endpoints usingpython-joseby fetching Clerk's JWKS public keys. - 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
CUSTOMERrole and provisions an empty shopping cart
- Looks up the Clerk user in MySQL by
- Role Management: Admin roles are managed natively in the MySQL database (
Roletable).
Veloce integrates with Razorpay for INR (βΉ) payments:
- Create Order β Frontend calls
/payments/create-orderβ Backend creates a Razorpay order - Checkout Modal β Razorpay's client-side SDK opens the payment modal
- Verify Signature β After payment,
/payments/verifyvalidates the Razorpay signature using Python'shmac-sha256 - Webhook Fallback β Razorpay sends webhook events to
/payments/webhookfor server-to-server confirmation - Idempotency β The
ProcessedWebhookEventmodel 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.
# Build and start all services
docker-compose up --build -d
# View logs
docker-compose logs -f backendThis starts:
- MySQL 8.0 on port
3306with a health check - FastAPI Backend on port
8000(waits for DB to be healthy)
- Use real Clerk production keys (
sk_live_.../pk_live_...) - Use real Razorpay production keys (
rzp_live_...) - Configure
FRONTEND_URLto your production domain for CORS - Disable Uvicorn reload mode in production
- Configure Razorpay webhook URL to your production endpoint
Faizan J Developer
- GitHub: @faizan-7890
This project is licensed under the ISC License.
Built with β€οΈ using Next.js, FastAPI, MySQL, Clerk, and Razorpay