Skip to content

ashish7802/Gravity-Shop

Repository files navigation

πŸͺ GRAVITY SHOP

A full-stack 3D e-commerce platform built with Next.js, Three.js, and Stripe.

Next.js 14 React 18 TypeScript MongoDB Stripe Three.js License


Overview

Gravity Shop is a production-grade e-commerce storefront that combines WebGL-powered 3D product visualization with a complete checkout and admin management system. Customers browse products rendered in interactive 3D scenes, add items to a cart, and complete purchases through Stripe Checkout. Administrators manage products, users, orders, inventory, and store settings through a protected dashboard.

The application is server-rendered with Next.js 14 App Router, backed by MongoDB Atlas, and secured with JWT authentication verified cryptographically at the Edge middleware layer.


Features

Customer Experience

  • 3D Product Visualization β€” Interactive product scenes built with React Three Fiber and Drei
  • Product Browsing β€” Grid layout with category filtering and real-time search
  • Search Palette β€” Command-palette-style search with keyboard navigation (Ctrl+K)
  • Shopping Cart β€” Slide-out cart drawer with quantity management and live totals
  • Cart Animations β€” Fly-to-cart micro-animations using Framer Motion
  • Stripe Checkout β€” Secure payment flow via Stripe Checkout Sessions
  • User Accounts β€” Registration, login, and order history
  • Responsive Design β€” Glassmorphism UI with gradient backgrounds and dark theme

Admin Dashboard

  • Product Management β€” Create, edit, and delete products with image and 3D model uploads
  • Inventory Control β€” Real-time stock levels with low-stock alerts
  • Order Management β€” View, filter, and update order statuses
  • User Management β€” Search, paginate, toggle roles, activate/deactivate accounts
  • Analytics β€” Revenue charts, top-selling products, monthly trends (Recharts)
  • Store Settings β€” Business configuration persisted to MongoDB

Security

  • JWT Authentication β€” Issued on login/register, stored as HTTP-only cookies
  • Edge Middleware Protection β€” Cryptographic JWT verification via jose on all /admin routes
  • Webhook Signature Validation β€” Stripe webhook payloads verified with constructEvent()
  • Rate Limiting β€” Sliding-window limiter on sensitive endpoints via Upstash Redis
  • Password Hashing β€” bcrypt with salt rounds

Commerce

  • Stripe Checkout Sessions β€” Server-side session creation with line items from database
  • Webhook Fulfillment β€” Automatic order status transition and inventory decrement on payment
  • Atomic Transactions β€” MongoDB transactions wrap fulfillment to prevent partial updates
  • Idempotent Processing β€” Duplicate webhook deliveries are safely ignored

Tech Stack

Layer Technology Purpose
Framework Next.js 14 (App Router) Server/client rendering, API routes, middleware
Language TypeScript 5 Type safety across the stack
UI Library React 18 Component architecture
3D Engine Three.js + React Three Fiber + Drei WebGL product visualization
Animation Framer Motion + GSAP Page transitions and micro-animations
Styling Tailwind CSS 3 Utility-first CSS
State Zustand Client-side cart and auth state
Database MongoDB Atlas + Mongoose 9 Document storage and ODM
Payments Stripe SDK Checkout sessions and webhook processing
Media Cloudinary Image and 3D model (GLB) hosting
Cache Upstash Redis Rate limiting
Auth jsonwebtoken + jose + bcryptjs Token signing, edge verification, password hashing
Charts Recharts Admin analytics visualization
Icons Lucide React UI iconography

Architecture

graph TB
    subgraph Client
        Browser["Browser"]
        R3F["React Three Fiber"]
        Zustand["Zustand Store"]
    end

    subgraph Edge
        MW["Middleware (jose JWT)"]
    end

    subgraph "Next.js Server"
        Pages["App Router Pages"]
        API["API Routes"]
        Auth["Auth API"]
        Checkout["Checkout API"]
        Webhook["Stripe Webhook"]
        AdminAPI["Admin API"]
    end

    subgraph "External Services"
        MongoDB["MongoDB Atlas"]
        Stripe["Stripe"]
        Cloudinary["Cloudinary"]
        Redis["Upstash Redis"]
    end

    Browser --> MW
    MW --> Pages
    MW --> API
    Browser --> R3F
    Browser --> Zustand

    Auth --> MongoDB
    AdminAPI --> MongoDB
    AdminAPI --> Cloudinary
    Checkout --> Stripe
    Checkout --> MongoDB
    Webhook --> MongoDB
    API --> Redis
Loading

Project Structure

gravity-shop/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ (admin)/                  # Admin route group
β”‚   β”‚   β”œβ”€β”€ analytics/page.tsx    # Revenue & sales dashboard
β”‚   β”‚   β”œβ”€β”€ inventory/page.tsx    # Stock management
β”‚   β”‚   β”œβ”€β”€ orders/page.tsx       # Order management
β”‚   β”‚   β”œβ”€β”€ products/page.tsx     # Product CRUD
β”‚   β”‚   β”œβ”€β”€ settings/page.tsx     # Store configuration
β”‚   β”‚   β”œβ”€β”€ users/page.tsx        # User management
β”‚   β”‚   β”œβ”€β”€ layout.tsx            # Admin sidebar layout
β”‚   β”‚   └── page.tsx              # Admin dashboard home
β”‚   β”œβ”€β”€ (user)/
β”‚   β”‚   β”œβ”€β”€ account/page.tsx      # User profile & orders
β”‚   β”‚   └── layout.tsx
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ admin/
β”‚   β”‚   β”‚   β”œβ”€β”€ analytics/        # GET aggregated stats
β”‚   β”‚   β”‚   β”œβ”€β”€ inventory/        # GET/PATCH stock levels
β”‚   β”‚   β”‚   β”œβ”€β”€ orders/           # GET/PATCH orders
β”‚   β”‚   β”‚   β”œβ”€β”€ products/         # GET/POST products
β”‚   β”‚   β”‚   β”œβ”€β”€ settings/         # GET/PUT store settings
β”‚   β”‚   β”‚   β”œβ”€β”€ upload/           # POST file uploads
β”‚   β”‚   β”‚   └── users/            # GET users, PATCH user by ID
β”‚   β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   β”‚   β”œβ”€β”€ login/            # POST credentials
β”‚   β”‚   β”‚   └── register/         # POST new account
β”‚   β”‚   β”œβ”€β”€ checkout/             # POST Stripe session
β”‚   β”‚   β”œβ”€β”€ health/               # GET service status
β”‚   β”‚   β”œβ”€β”€ products/             # GET public products
β”‚   β”‚   β”œβ”€β”€ search/               # GET search results
β”‚   β”‚   └── webhooks/stripe/      # POST Stripe events
β”‚   β”œβ”€β”€ product/[id]/page.tsx     # Product detail page
β”‚   β”œβ”€β”€ layout.tsx                # Root layout
β”‚   β”œβ”€β”€ page.tsx                  # Homepage
β”‚   β”œβ”€β”€ robots.ts                 # SEO robots
β”‚   └── sitemap.ts                # SEO sitemap
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ admin/                    # AdminSidebar, ProductDataGrid, ProductUploadModal, GlowingChart
β”‚   β”œβ”€β”€ animations/               # CartFlyAnimation
β”‚   β”œβ”€β”€ auth/                     # AuthModal
β”‚   β”œβ”€β”€ canvas/                   # Scene, FloatingProduct, Environment
β”‚   β”œβ”€β”€ cart/                     # CartDrawer, CartItemCard, CartScene, CartSummary
β”‚   β”œβ”€β”€ product/                  # ProductCard3D, ProductGrid, ProductDetails, ProductViewer, etc.
β”‚   └── ui/                       # Navbar, Hero, SearchPalette, GlassPanel, MagneticCursor, FloatingGradientBackground
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ db/connect.ts             # MongoDB connection singleton
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ User.ts               # User schema (name, email, password, role, isActive)
β”‚   β”‚   β”œβ”€β”€ Product.ts            # Product schema (name, slug, price, stock, images, model3d)
β”‚   β”‚   β”œβ”€β”€ Order.ts              # Order schema (items, status, stripeSessionId)
β”‚   β”‚   └── Setting.ts            # Settings schema (key-value store by category)
β”‚   β”œβ”€β”€ api-error.ts              # Structured error handling
β”‚   β”œβ”€β”€ cloudinary.ts             # Upload helper
β”‚   β”œβ”€β”€ env.ts                    # Environment validation
β”‚   β”œβ”€β”€ logger.ts                 # Server-side logger
β”‚   └── rate-limit.ts             # Upstash rate limiter
β”œβ”€β”€ store/
β”‚   └── useAppStore.ts            # Zustand store (cart, auth, UI state)
β”œβ”€β”€ middleware.ts                 # Edge JWT verification for /admin routes
β”œβ”€β”€ next.config.mjs
β”œβ”€β”€ tailwind.config.ts
β”œβ”€β”€ tsconfig.json
└── package.json

Installation

# Clone the repository
git clone https://github.com/ashish7802/Gravity-Shop.git
cd Gravity-Shop

# Install dependencies
npm install --legacy-peer-deps

Note: The --legacy-peer-deps flag is required due to peer dependency conflicts between React 18 and @react-three/drei.


Environment Variables

Create a .env.local file in the project root with the following variables:

# MongoDB
MONGODB_URI=

# Authentication
JWT_SECRET=

# Stripe
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=

# Cloudinary
CLOUDINARY_CLOUD_NAME=
CLOUDINARY_API_KEY=
CLOUDINARY_API_SECRET=

# Upstash Redis
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=

⚠️ Important: Never commit .env.local to version control. The .gitignore already excludes it.


Running Locally

# Start the development server
npm run dev

Open http://localhost:3000 in your browser.


Production Build

# Build for production
npm run build

# Start the production server
npm start

Stripe Setup

  1. Create a Stripe account.
  2. Copy your Publishable Key and Secret Key from the Stripe Dashboard β†’ Developers β†’ API Keys.
  3. Set up a webhook endpoint pointing to https://your-domain.com/api/webhooks/stripe.
  4. Subscribe to the checkout.session.completed event.
  5. Copy the Webhook Signing Secret and add it to STRIPE_WEBHOOK_SECRET.
# For local testing with Stripe CLI
stripe listen --forward-to localhost:3000/api/webhooks/stripe

Cloudinary Setup

  1. Create a Cloudinary account.
  2. Navigate to Dashboard β†’ Settings β†’ Access Keys.
  3. Copy Cloud Name, API Key, and API Secret into your environment variables.
  4. Product images upload to gravity-shop/images/.
  5. 3D models (GLB files) upload to gravity-shop/models/.

MongoDB Setup

  1. Create a MongoDB Atlas cluster.
  2. Create a database user with read/write permissions.
  3. Whitelist your IP address (or use 0.0.0.0/0 for development).
  4. Copy the connection string into MONGODB_URI.
  5. The application automatically creates these collections on first use:
    • users
    • products
    • orders
    • settings

Admin Dashboard

Access the admin dashboard at /admin after logging in with an admin account.

To create the first admin user, register a normal account and then update the role directly in MongoDB:

db.users.updateOne(
  { email: "your-email@example.com" },
  { $set: { role: "admin" } }
)

Admin Pages

Page Route Functionality
Dashboard /admin Overview with quick stats
Products /admin/products CRUD with image/model uploads
Inventory /admin/inventory Stock levels and low-stock alerts
Orders /admin/orders Status management and filtering
Users /admin/users Search, pagination, role toggle, activation
Analytics /admin/analytics Revenue charts, top products, trends
Settings /admin/settings Store, payment, media, email config

API Routes

Method Endpoint Auth Description
POST /api/auth/register Public Create a new user account
POST /api/auth/login Public Authenticate and receive JWT
GET /api/products Public List all products
GET /api/search Public Full-text product search
POST /api/checkout User Create a Stripe Checkout Session
POST /api/webhooks/stripe Stripe Handle payment webhooks
GET /api/health Public Service connectivity status
GET /api/admin/products Admin List products (admin view)
POST /api/admin/products Admin Create a new product
GET /api/admin/orders Admin List all orders
PATCH /api/admin/orders Admin Update order status
GET /api/admin/inventory Admin Get inventory levels
PATCH /api/admin/inventory Admin Update stock quantities
GET /api/admin/users Admin List users with pagination
PATCH /api/admin/users/[id] Admin Update user role or status
GET /api/admin/analytics Admin Aggregated business metrics
GET /api/admin/settings Admin Read store settings
PUT /api/admin/settings Admin Update store settings
POST /api/admin/upload Admin Upload images or 3D models

Security

Authentication Flow

  1. User submits credentials to /api/auth/login.
  2. Server verifies password hash with bcrypt.
  3. Server signs a JWT containing userId, email, and role.
  4. Token is returned and stored as an HTTP-only cookie.

Middleware Protection

All routes matching /admin/* and /api/admin/* are intercepted by Edge Middleware that:

  • Extracts the JWT from cookies
  • Cryptographically verifies the signature using jose (jwtVerify)
  • Validates token expiration
  • Checks that role === "admin"
  • Returns 401 or 403 for unauthorized requests

Webhook Security

Stripe webhook payloads are verified using stripe.webhooks.constructEvent() with the webhook signing secret before any database mutations occur.

Rate Limiting

Sensitive endpoints are protected by a sliding-window rate limiter (10 requests / 10 seconds) powered by Upstash Redis.


Performance Optimizations

  • Dynamic Imports β€” Three.js canvas components are loaded with next/dynamic to avoid blocking initial page render
  • Lazy 3D Engine β€” The WebGL renderer only initializes when 3D components scroll into view
  • MongoDB Connection Pooling β€” Singleton connection pattern prevents connection exhaustion in serverless
  • Aggregation Pipelines β€” Analytics queries use $lookup instead of per-document queries
  • Atomic Transactions β€” Stripe fulfillment uses mongoose.startSession() with withTransaction() to prevent partial writes
  • Image Optimization β€” Product images served through Cloudinary CDN with automatic format selection
  • SEO β€” Auto-generated robots.txt and sitemap.xml routes

Deployment

Vercel (Recommended)

  1. Push the repository to GitHub.
  2. Import the project in Vercel.
  3. Set the Install Command to npm install --legacy-peer-deps.
  4. Add all environment variables in Vercel Project Settings.
  5. Deploy.
graph LR
    A["git push"] --> B["GitHub"]
    B --> C["Vercel Build"]
    C --> D["Edge Network"]
    D --> E["Live Site"]
    E --> F["MongoDB Atlas"]
    E --> G["Stripe"]
    E --> H["Cloudinary"]
    E --> I["Upstash Redis"]
Loading

Post-Deployment

  • Register a Stripe webhook endpoint pointing to https://your-domain.vercel.app/api/webhooks/stripe.
  • Subscribe to checkout.session.completed.
  • Update STRIPE_WEBHOOK_SECRET with the production signing secret.

Screenshots

Screenshots of the storefront, product pages, and admin dashboard can be added here.

View Screenshot
Homepage Coming soon
Product Detail (3D) Coming soon
Cart Drawer Coming soon
Admin Dashboard Coming soon
Admin Products Coming soon
Admin Analytics Coming soon

Known Limitations

  • No Email Notifications β€” Order confirmations and shipping updates are not sent via email. The settings page includes an email configuration section for future integration.
  • No Guest Checkout β€” Users must register or log in before purchasing.
  • No Wishlist β€” There is no saved-items or favorites feature.
  • No Multi-Currency β€” Stripe sessions are created in a single currency.
  • No Image Cropping β€” Uploaded images are stored as-is without client-side cropping.
  • GLB Model Dependency β€” 3D product previews require a GLB model URL in the product record; products without one display a static image fallback.

Roadmap

  • Email notifications via SendGrid or Resend
  • Guest checkout flow
  • Wishlist and saved items
  • Product reviews and ratings
  • Multi-currency support
  • Order tracking with shipping integration
  • Bulk product import (CSV)
  • Client-side image cropping before upload

License

This project is licensed under the MIT License.


Built with Next.js, Three.js, and Stripe

About

πŸͺ A production-grade 3D e-commerce platform built with Next.js, Three.js, Stripe, MongoDB, and TypeScript. Features interactive 3D product visualization, secure payments, admin dashboard, inventory management, analytics, and modern full-stack architecture.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages