ποΈ 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.
π Table of Contents
- Key Features
- Architecture
- Tech Stack
- Project Structure
- Security Features
- Getting Started
- Environment Variables
- Database Management
- API Documentation
- Development
β¨ 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
- Clone the repository
git clone https://github.com/Saif-Mohammed1/modern-shop-platform.git
cd modern-shop-platform
- Install dependencies
npm install
- Set up SSL certificates for local development
mkcert -install
mkcert localhost
- Configure environment variables
cp .env.example .env
# Edit .env with your configurations
- Set up the database
# Run migrations
npm run migrate:latest
# Seed the database (optional)
npm run seed:run
- 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
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π₯ Authors
- Saif Mohammed - GitHub
π Acknowledgments
- Next.js team for the amazing framework
- Apollo GraphQL for the robust GraphQL implementation
- Vercel for deployment platform
- All open-source contributors
License
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.