Home
Softono
modern-shop-platform

modern-shop-platform

Open source MIT TypeScript
46
Stars
16
Forks
1
Issues
3
Watchers
7 months
Last Commit

About modern-shop-platform

Open-source modern e-commerce platform built with Next.js 15, TypeScript and GraphQL on PostgreSQL (Knex.js), Apollo Server and Redis. Features secure auth (NextAuth, JWT, 2FA), rate-limiting, admin dashboard, Stripe payments, Cloudinary, and a clean layered architecture with docs to help developers extend and deploy.

Platforms

Web Self-hosted Cloud Docker

Languages

TypeScript

πŸ›οΈ Modern E-Commerce Platform

A production-ready, full-stack e-commerce application built with Next.js 15, GraphQL, and PostgreSQL. This project showcases enterprise-level architecture with advanced security features, real-time capabilities, and a scalable microservice-inspired structure.

Next.js TypeScript GraphQL PostgreSQL Apollo License

πŸ“‹ Table of Contents

✨ Key Features

πŸ” Advanced Security

  • Two-Factor Authentication (2FA): TOTP-based authentication with QR code generation using Speakeasy
  • JWT with Refresh Tokens: Secure token-based authentication with automatic token refresh
  • Rate Limiting: Intelligent rate limiting with Redis for auth, API, GraphQL, and critical operations
  • Session Management: Device tracking, suspicious activity detection, and multi-session support
  • Security Audit Logs: Comprehensive logging of all security-related events
  • Password Encryption: Bcrypt-based password hashing with salt rounds

🎯 E-Commerce Features

  • Product catalog with advanced filtering and search
  • Shopping cart with real-time updates
  • Wishlist functionality
  • Order management system
  • Review and rating system
  • Multi-address support
  • Refund and return processing
  • Stripe payment integration

πŸ“Š Admin Dashboard

  • User management with security analytics
  • Product management (CRUD operations)
  • Order tracking and fulfillment
  • Revenue analytics and reporting
  • Security monitoring dashboard
  • Device management per user

πŸš€ Performance & Scalability

  • Server-side rendering (SSR) with Next.js 15
  • GraphQL API with Apollo Server
  • Redis caching for rate limiting and sessions
  • Database query optimization with Knex.js
  • Image optimization with Sharp and Cloudinary
  • Response compression and caching headers

πŸ—οΈ Architecture

This project follows a clean, layered architecture inspired by Domain-Driven Design (DDD) and microservices patterns:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Client Layer                         β”‚
β”‚         (Next.js App Router + React 19)                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    API Gateway Layer                     β”‚
β”‚              (GraphQL + Apollo Server)                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   Middleware Layer                       β”‚
β”‚        (Auth, Rate Limiting, Error Handling)            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   Controller Layer                       β”‚
β”‚          (Request Validation & Response)                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Service Layer                         β”‚
β”‚              (Business Logic & Orchestration)            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   Repository Layer                       β”‚
β”‚            (Data Access & Query Building)                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Database Layer                        β”‚
β”‚              (PostgreSQL + Knex.js ORM)                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Layer Responsibilities

Controller Layer (app/server/controllers/)

  • Request validation using Zod schemas
  • Input sanitization and transformation
  • Response formatting
  • Error handling and HTTP status codes
  • GraphQL resolver coordination

Service Layer (app/server/services/)

  • Core business logic implementation
  • Transaction management
  • Cross-domain orchestration
  • External API integration (Stripe, Cloudinary, Email)
  • Security operations (2FA, token management)

Repository Layer (app/server/repositories/)

  • Database query construction
  • Data mapping and transformation
  • Query optimization
  • Base repository pattern for code reuse
  • Complex joins and aggregations

GraphQL Layer (app/server/graphql/)

  • Schema definitions (Type-safe GraphQL schemas)
  • Resolvers implementation
  • Custom scalar types (DateTime, EmailAddress)
  • Query optimization with DataLoader pattern
  • Error formatting and handling

πŸ› οΈ Tech Stack

Frontend

  • Framework: Next.js 15 (App Router)
  • UI Library: React 19
  • Styling: TailwindCSS 4.0 with PostCSS
  • State Management: Zustand
  • Forms: React Hook Form + Zod validation
  • HTTP Client: Apollo Client (GraphQL)
  • Animations: Framer Motion, Lottie React
  • UI Components: Headless UI, Swiper
  • Notifications: React Hot Toast

Backend

  • Runtime: Node.js with TypeScript
  • GraphQL Server: Apollo Server 4
  • Database ORM: Knex.js
  • Database: PostgreSQL
  • Caching: Redis (Upstash)
  • Authentication: NextAuth.js + JWT
  • Security:
    • Speakeasy (2FA/TOTP)
    • Bcrypt (Password hashing)
    • Rate limiting (Custom Redis-based)
  • Payment: Stripe
  • Email: Nodemailer
  • File Upload: Cloudinary
  • Logging: Winston with daily log rotation
  • Validation: Zod

DevOps & Tools

  • Containerization: Docker + Docker Compose
  • Code Quality: ESLint, Prettier
  • Git Hooks: Husky + Lint-staged
  • SSL Certificates: mkcert (local development)
  • Type Checking: TypeScript strict mode

πŸ“ Project Structure

shop/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ (auth)/                      # Protected auth routes
β”‚   β”‚   β”œβ”€β”€ (admin)/                 # Admin dashboard
β”‚   β”‚   β”œβ”€β”€ account/                 # User account management
β”‚   β”‚   β”œβ”€β”€ checkout/                # Checkout process
β”‚   β”‚   └── verify-email/            # Email verification
β”‚   β”œβ”€β”€ (public)/                    # Public routes
β”‚   β”‚   β”œβ”€β”€ shop/                    # Product listings
β”‚   β”‚   β”œβ”€β”€ auth/                    # Login/Register
β”‚   β”‚   └── about-us/                # Static pages
β”‚   β”œβ”€β”€ api/v1/                      # REST API endpoints (if any)
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ actions/                 # Server actions
β”‚   β”‚   β”œβ”€β”€ config/                  # Configuration files
β”‚   β”‚   β”œβ”€β”€ graphql/                 # Client GraphQL queries
β”‚   β”‚   β”œβ”€β”€ types/                   # TypeScript types
β”‚   β”‚   └── utilities/               # Helper functions
β”‚   └── server/
β”‚       β”œβ”€β”€ controllers/             # Request handlers
β”‚       β”œβ”€β”€ services/                # Business logic
β”‚       β”‚   β”œβ”€β”€ 2fa.service.ts
β”‚       β”‚   β”œβ”€β”€ tokens.service.ts
β”‚       β”‚   β”œβ”€β”€ user.service.ts
β”‚       β”‚   β”œβ”€β”€ security.service.ts
β”‚       β”‚   β”œβ”€β”€ stripe.service.ts
β”‚       β”‚   └── ...
β”‚       β”œβ”€β”€ repositories/            # Data access layer
β”‚       β”‚   β”œβ”€β”€ BaseRepository.ts
β”‚       β”‚   β”œβ”€β”€ user.repository.ts
β”‚       β”‚   β”œβ”€β”€ product.repository.ts
β”‚       β”‚   └── ...
β”‚       β”œβ”€β”€ graphql/
β”‚       β”‚   β”œβ”€β”€ schema/              # GraphQL type definitions
β”‚       β”‚   β”œβ”€β”€ resolvers/           # GraphQL resolvers
β”‚       β”‚   └── apollo-server.ts     # Apollo Server setup
β”‚       β”œβ”€β”€ middlewares/
β”‚       β”‚   β”œβ”€β”€ auth.middleware.ts
β”‚       β”‚   β”œβ”€β”€ security.middleware.ts
β”‚       β”‚   └── error.middleware.ts
β”‚       β”œβ”€β”€ validators/              # Zod validation schemas
β”‚       β”œβ”€β”€ dtos/                    # Data Transfer Objects
β”‚       β”œβ”€β”€ db/
β”‚       β”‚   β”œβ”€β”€ migrations/          # Database migrations
β”‚       β”‚   └── seeds/               # Database seeds
β”‚       └── utils/                   # Server utilities
β”œβ”€β”€ components/                      # React components
β”‚   β”œβ”€β”€ 2fa/                         # 2FA UI components
β”‚   β”œβ”€β”€ authentication/              # Auth forms
β”‚   β”œβ”€β”€ (admin)/dashboard/           # Admin components
β”‚   β”œβ”€β”€ customers/                   # Customer dashboard
β”‚   └── ...
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ locales/                     # i18n translations
β”‚   └── ...
β”œβ”€β”€ @types/                          # TypeScript declarations
β”œβ”€β”€ certificates/                    # SSL certificates (dev)
β”œβ”€β”€ docker-compose.yml               # Docker configuration
β”œβ”€β”€ knexfile.ts                      # Knex configuration
β”œβ”€β”€ middleware.ts                    # Next.js middleware
└── tsconfig.json                    # TypeScript config

πŸ”’ Security Features

1. Two-Factor Authentication (2FA)

// Located in: app/server/services/2fa.service.ts
- QR Code generation for authenticator apps
- Backup codes (8 codes, single-use)
- TOTP verification with 30-second window
- Device trust management
- Audit logging for 2FA events

2. Rate Limiting Strategy

// Located in: app/lib/utilities/rate-limiter.ts
Rate Limit Configurations:
- Auth endpoints: 10 requests per 5 minutes
- API endpoints: 30 requests per minute
- GraphQL: 20 queries per minute
- Critical operations: 5 attempts per hour

Features:
- Redis-based atomic operations (Lua scripts)
- Per-user and per-IP tracking
- Automatic TTL management
- Custom headers (X-RateLimit-*)

3. JWT & Refresh Token System

// Located in: app/server/services/tokens.service.ts
Access Token:
- Short-lived (15 minutes)
- Contains user ID, email, role
- Used for API authentication

Refresh Token:
- Long-lived (7 days)
- Stored in HTTP-only cookies
- Automatic rotation on refresh
- Device-bound tokens
- Revocation support

4. Session Management

// Located in: app/server/services/session.service.ts
Features:
- Device fingerprinting
- IP address tracking
- Geographic location detection
- Suspicious activity alerts
- Session termination (single/all devices)
- Last activity tracking

5. Security Middleware

// Located in: app/server/middlewares/security.middleware.ts
- CSRF protection
- XSS prevention
- SQL injection protection
- Request sanitization
- Security headers (HSTS, CSP, etc.)

πŸš€ Getting Started

Prerequisites

  • Node.js 18+
  • PostgreSQL 14+
  • Redis (or Upstash account)
  • Stripe account (for payments)
  • Cloudinary account (for images)

Installation

  1. Clone the repository
git clone https://github.com/Saif-Mohammed1/modern-shop-platform.git
cd modern-shop-platform
  1. Install dependencies
npm install
  1. Set up SSL certificates for local development
mkcert -install
mkcert localhost
  1. Configure environment variables
cp .env.example .env
# Edit .env with your configurations
  1. Set up the database
# Run migrations
npm run migrate:latest

# Seed the database (optional)
npm run seed:run
  1. Start development server
npm run dev

The application will be available at https://localhost:3000

Using Docker

# Development
docker-compose -f docker-compose-dev.yml up

# Production
docker-compose -f docker-compose-prod.yml up

πŸ”‘ Environment Variables

Create a .env file in the root directory:

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/shop_db"
DB_HOST=localhost
DB_PORT=5432
DB_USER=your_db_user
DB_PASSWORD=your_db_password
DB_NAME=shop_db

# Redis (Upstash or local)
UPSTASH_REDIS_REST_URL=your_redis_url
UPSTASH_REDIS_REST_TOKEN=your_redis_token

# NextAuth
NEXTAUTH_SECRET=your_nextauth_secret
NEXTAUTH_URL=https://localhost:3000

# JWT
JWT_SECRET=your_jwt_secret
JWT_REFRESH_SECRET=your_jwt_refresh_secret
JWT_EXPIRES_IN=15m
JWT_REFRESH_EXPIRES_IN=7d

# Stripe
STRIPE_SECRET=sk_test_your_stripe_secret
STRIPE_PUBLIC_KEY=pk_test_your_stripe_public
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# Cloudinary
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

# Email (SMTP)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
[email protected]
EMAIL_PASSWORD=your_app_password
[email protected]

# Logging
LOG_LEVEL=debug
LOGTAIL_SOURCE_TOKEN=your_logtail_token

# App
NODE_ENV=development
NEXT_PUBLIC_APP_URL=https://localhost:3000

πŸ—„οΈ Database Management

Migrations

# Create a new migration
npm run migrate:make migration_name

# Run pending migrations
npm run migrate:latest

# Rollback last migration
npm run migrate:rollback

# Run migration script
npm run migrate

Seeds

# Create a new seed file
npm run seed:make seed_name

# Run all seeds
npm run seed:run

Database Schema Overview

Key Tables:
- users (with 2FA fields)
- sessions (device tracking)
- refresh_tokens
- products
- categories
- orders
- order_items
- cart
- reviews
- addresses
- wishlists
- audit_logs
- security_events

πŸ“‘ API Documentation

GraphQL Endpoint

Development: https://localhost:3000/api/graphql
Production: https://your-domain.com/api/graphql

GraphQL Playground

Access the interactive GraphQL playground at:

https://localhost:3000/api/graphql

Key GraphQL Queries

Authentication

mutation Login($email: EmailAddress!, $password: String!) {
  login(email: $email, password: $password) {
    user {
      id
      email
      firstName
      lastName
      role
    }
    requires2FA
    message
  }
}

mutation Verify2FA($token: String!) {
  verify2FA(token: $token) {
    success
    message
  }
}

User Management

query GetCurrentUser {
  currentUser {
    id
    email
    firstName
    lastName
    role
    twoFactorEnabled
    emailVerified
  }
}

query GetUserSessions {
  userSessions {
    id
    deviceInfo
    ipAddress
    location
    lastActivity
    isCurrent
  }
}

Products

query GetProducts($page: Int, $limit: Int, $category: String) {
  products(page: $page, limit: $limit, category: $category) {
    products {
      id
      name
      description
      price
      images
      stock
      category
      rating
    }
    totalPages
    currentPage
  }
}

Cart & Orders

mutation AddToCart($productId: ID!, $quantity: Int!) {
  addToCart(productId: $productId, quantity: $quantity) {
    id
    items {
      product {
        id
        name
        price
      }
      quantity
    }
    total
  }
}

mutation CreateOrder($shippingAddressId: ID!, $paymentMethod: String!) {
  createOrder(
    shippingAddressId: $shippingAddressId
    paymentMethod: $paymentMethod
  ) {
    id
    orderNumber
    total
    status
  }
}

Rate Limit Headers

All API responses include rate limit information:

X-RateLimit-Limit: 30
X-RateLimit-Remaining: 25
X-RateLimit-Reset: 1699564800

πŸ’» Development

Code Quality

# Run ESLint
npm run lint

# Type checking
npm run check-types

# Format code
npm run format

# Check formatting
npm run format:check

Pre-commit Hooks

This project uses Husky and lint-staged to ensure code quality:

  • Automatic ESLint fixes on staged files
  • Type checking before commit
  • Prettier formatting

Building for Production

# Create production build
npm run build

# Start production server
npm start

Bundle Analysis

# Analyze bundle size
ANALYZE=true npm run build

πŸ“Š Monitoring & Logging

Winston Logger

  • Structured JSON logging
  • Daily log rotation
  • Multiple log levels (error, warn, info, debug)
  • Logtail integration for production

Log Locations

logs/
β”œβ”€β”€ error/           # Error logs
β”œβ”€β”€ combined/        # All logs
└── exceptions/      # Uncaught exceptions

Audit Logs

All security-sensitive operations are logged:

  • Login attempts
  • 2FA verifications
  • Password changes
  • Session terminations
  • Admin actions

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ‘₯ Authors

πŸ™ Acknowledgments

  • Next.js team for the amazing framework
  • Apollo GraphQL for the robust GraphQL implementation
  • Vercel for deployment platform
  • All open-source contributors

License

License: MIT

This project is licensed under the MIT License β€” see the LICENSE file in the project root for details.

Note: This is a production-ready template showcasing enterprise-level patterns and security best practices. Feel free to use it as a foundation for your e-commerce projects.

For questions or support, please open an issue on GitHub.