Elite Events - System Architecture
Complete technical architecture documentation for Elite Events.
Last Updated: December 27, 2025 Version: 1.2.0
Table of Contents
- Overview
- High-Level Architecture
- Technology Stack
- Directory Structure
- Data Flow
- Database Schema
- API Architecture
- Authentication Flow
- State Management
- Image Processing Pipeline
- Security Architecture
Overview
Elite Events is a full-stack e-commerce platform built with Next.js 14, utilizing the App Router, React Server Components, and a MySQL database via Prisma ORM.
Architecture Principles
- Server-First: Leverage React Server Components for optimal performance
- Type-Safe: End-to-end TypeScript for reliability
- API-Driven: RESTful APIs for clear separation of concerns
- Secure by Default: Role-based access control and input validation
- Scalable: Designed for growth from MVP to enterprise
- Centralized Organization: Types and hooks follow single source of truth pattern
Type & Hook Organization Strategy
The application follows a centralized type and hook organization pattern for improved maintainability and developer experience:
Dependency Flow:
Types Layer (src/types/*)
↓
Hooks Layer (src/hooks/*)
↓
Components Layer (src/components/*)
Key Benefits:
- Single source of truth for all shared types
- Clear, one-way dependency graph
- Improved type safety and discoverability
- Better code reusability across features
- Reduced duplication and maintenance burden
Type Categories:
- Domain Types (
user.ts,product.ts,payment.ts): Business logic and data models - UI Types (
ui.ts,layout.ts): Component prop definitions - Feature Types (
shop.ts,forms.ts): Feature-specific types - Hook Types: Included in respective domain type files
See TYPES_GUIDE.md for comprehensive documentation.
High-Level Architecture
┌─────────────────────────────────────────────────────────────┐
│ Client Layer │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ Browser │ │ Mobile │ │ Desktop │ │
│ │ (React) │ │ (Future) │ │ (Future) │ │
│ └─────┬──────┘ └──────┬─────┘ └──────┬─────┘ │
└────────┼─────────────────┼────────────────┼────────────────┘
│ │ │
└─────────────────┴────────────────┘
│
┌────────────────▼────────────────┐
│ Next.js App Router │
│ (Server + Client Components) │
└────────────────┬────────────────┘
│
┌────────────────┴────────────────┐
│ │
┌────▼─────┐ ┌──────▼────┐
│ API │ │ Pages │
│ Routes │ │ (SSR/RSC)│
└────┬─────┘ └──────┬────┘
│ │
├──────────────┬───────────────────┤
│ │ │
┌────▼─────┐ ┌────▼──────┐ ┌──────▼─────┐
│NextAuth │ │ Business │ │ Redux │
│ (Auth) │ │ Logic │ │ (State) │
└────┬─────┘ └────┬──────┘ └────────────┘
│ │
└──────┬───────┘
│
┌──────▼──────┐
│ Prisma │
│ ORM │
└──────┬──────┘
│
┌──────▼──────┐
│ MySQL │
│ Database │
└─────────────┘
Technology Stack
Frontend
Framework: Next.js 14.x (App Router)
UI Library: React 18.x
Language: TypeScript 5.x
Styling: Tailwind CSS + CSS Modules
State Management: Redux Toolkit
Forms: React Hook Form (planned)
Validation: Zod
Testing: Jest + React Testing Library
Backend
Runtime: Node.js 18+
Framework: Next.js API Routes
ORM: Prisma
Database: MySQL 8.0+
Authentication: NextAuth.js
Password Hashing: bcryptjs
Image Processing: Sharp
File Upload: Next.js FormData
DevOps
Hosting: Vercel
Database Host: AWS RDS (MySQL)
CI/CD: GitHub Actions
Version Control: Git/GitHub
Package Manager: npm
Directory Structure
elite_events_nextjs/
│
├── src/
│ ├── app/ # Next.js App Router
│ │ ├── (auth)/ # Auth route group
│ │ │ ├── signin/
│ │ │ └── signup/
│ │ ├── admin/ # Admin panel
│ │ │ ├── products/
│ │ │ ├── categories/
│ │ │ └── images/
│ │ ├── api/ # API routes
│ │ │ ├── auth/
│ │ │ ├── products/
│ │ │ ├── cart/
│ │ │ ├── wishlist/
│ │ │ ├── user/
│ │ │ └── admin/
│ │ ├── shop/ # Shop pages
│ │ ├── layout.tsx # Root layout
│ │ └── page.tsx # Homepage
│ │
│ ├── components/ # React components
│ │ ├── layout/ # Layout components
│ │ │ ├── Header/
│ │ │ ├── Footer/
│ │ │ └── Navigation/
│ │ └── features/ # Feature components
│ │ ├── shop/
│ │ ├── cart/
│ │ └── admin/
│ │
│ ├── redux/ # Redux store
│ │ ├── store.ts
│ │ └── features/
│ │ ├── cart-slice.ts
│ │ └── wishlist-slice.ts
│ │
│ ├── lib/ # Utilities & helpers
│ │ ├── prisma.ts # Prisma client
│ │ ├── validation-schemas.ts
│ │ ├── image-processing.ts
│ │ └── file-naming.ts
│ │
│ ├── types/ # TypeScript types (centralized)
│ │ ├── product.ts # Product & inventory types
│ │ ├── category.ts # Category & taxonomy types
│ │ ├── blogItem.ts # Blog post types
│ │ ├── user.ts # User, profile, address, auth types
│ │ ├── payment.ts # Payment, checkout, transaction types
│ │ ├── forms.ts # Form field & validation types
│ │ ├── ui.ts # UI component prop types
│ │ ├── layout.ts # Layout component types
│ │ └── shop.ts # Shop feature types
│ │
│ ├── hooks/ # Custom React hooks (centralized)
│ │ ├── useProducts.ts # Product data hooks
│ │ ├── useCategories.ts # Category data hooks
│ │ ├── useBlogPosts.ts # Blog data hooks
│ │ ├── useToast.ts # Toast notifications
│ │ ├── useUserProfile.ts # User profile management
│ │ ├── useAddresses.ts # Address management
│ │ ├── usePasswordChange.ts # Password change logic
│ │ ├── useProductActions.ts # Product actions (cart/wishlist)
│ │ ├── useTheme.ts # Theme management
│ │ ├── useDebounce.ts # Debounce utility
│ │ ├── useScrollAnimation.ts # Scroll animations
│ │ └── useConfirm.ts # Confirmation dialogs
│ │
│ └── middleware.ts # Next.js middleware
│
├── prisma/
│ ├── schema.prisma # Database schema
│ └── seed.ts # Seed script
│
├── public/
│ └── images/ # Static images
│ └── products/
│
├── docs/ # Documentation
│
└── __tests__/ # Tests
Data Flow
Request Flow (SSR Page)
User Request
│
▼
Next.js App Router
│
├──> Server Component (RSC)
│ │
│ ▼
│ Prisma Query
│ │
│ ▼
│ MySQL Database
│ │
│ ▼
│ Render on Server
│ │
│ ▼
│ Send HTML to Client
│
└──> Client Component
│
▼
Hydrate in Browser
│
▼
Interactive UI
API Request Flow
Client Request (fetch/axios)
│
▼
API Route (/api/*)
│
├──> Authentication Check
│ │
│ ├──> ✅ Authenticated → Continue
│ └──> ❌ Not Authenticated → 401
│
├──> Authorization Check (RBAC)
│ │
│ ├──> ✅ Authorized → Continue
│ └──> ❌ Not Authorized → 403
│
├──> Input Validation (Zod)
│ │
│ ├──> ✅ Valid → Continue
│ └──> ❌ Invalid → 400
│
├──> Business Logic
│ │
│ ▼
│ Prisma ORM
│ │
│ ▼
│ MySQL Database
│ │
│ ▼
│ Return Data
│
└──> Response (JSON)
Database Schema
Entity Relationship Diagram
┌──────────┐ ┌──────────┐ ┌──────────┐
│ User │ │ Order │ │ Product │
│──────────│ │──────────│ │──────────│
│ id │◄────────│ userId │ │ id │
│ email │ │ total │ │ title │
│ password │ │ status │ │ price │
│ role │ │ ... │ │ stock │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
│ │ │
│ │ │
│ ┌────▼──────┐ │
│ │OrderItem │ │
│ │───────────│ │
│ │ orderId │ │
│ │ productId │◄─────────────┘
│ │ quantity │
│ └───────────┘
│
├────────┬─────────────┬──────────┐
│ │ │ │
┌────▼────┐ ┌▼─────────┐ ┌─▼──────┐ ┌▼────────┐
│ Cart │ │ Wishlist │ │Address │ │ Review │
│─────────│ │──────────│ │────────│ │─────────│
│ userId │ │ userId │ │userId │ │userId │
│productId│ │productId │ │type │ │productId│
│quantity │ │addedAt │ │address │ │rating │
└─────────┘ └──────────┘ └────────┘ └─────────┘
Core Models
User (Authentication & Profiles)
- Stores user credentials (hashed passwords)
- Role-based access (ADMIN, CUSTOMER)
- Links to addresses, orders, cart, wishlist
Product (Catalog)
- Product information and pricing
- Links to category, images, reviews
- Stock tracking
Category (Hierarchy)
- Parent-child relationships
- Supports nested categories
- Product organization
Order (Transactions)
- Order tracking and status
- Links to user, items, addresses
- Payment information
See prisma/schema.prisma for complete schema.
API Architecture
RESTful Design
Resource-Based URLs:
GET /api/products → List products
GET /api/products/:id → Get product
POST /api/products → Create product (admin)
PUT /api/products/:id → Update product (admin)
DELETE /api/products/:id → Delete product (admin)
Nested Resources:
GET /api/products/:id/reviews → Product reviews
POST /api/products/:id/reviews → Add review
Query Parameters:
/api/products?page=1&limit=20&categoryId=5&search=tent
Response Format
Success:
{
"data": {...},
"pagination": {...} // if applicable
}
Error:
{
"error": "Error message",
"details": "Additional info",
"code": "ERROR_CODE"
}
Status Codes
200- Success201- Created400- Bad Request401- Unauthorized403- Forbidden404- Not Found500- Internal Error
Authentication Flow
┌─────────┐ ┌────────────┐
│ Client │ │ Server │
└────┬────┘ └─────┬──────┘
│ │
│ 1. POST /api/auth/signup │
│──────────────────────────────────► │
│ { email, password, name } │
│ │
│ 2. Hash password (bcrypt)
│ │
│ 3. Store in database
│ │
│ 4. Response (success) │
│◄────────────────────────────────────│
│ │
│ 5. POST /api/auth/signin │
│──────────────────────────────────► │
│ { email, password } │
│ │
│ 6. Verify password
│ │
│ 7. Create JWT session
│ │
│ 8. Set session cookie + redirect │
│◄────────────────────────────────────│
│ │
│ 9. Subsequent requests │
│ (include session cookie) │
│──────────────────────────────────► │
│ │
│ 10. Verify JWT
│ │
│ 11. Check role (RBAC)
│ │
│ 12. Response (authorized) │
│◄────────────────────────────────────│
Session Management
- Provider: NextAuth.js
- Strategy: JWT (JSON Web Tokens)
- Storage: HTTP-only cookies
- Expiration: 30 days (configurable)
- CSRF Protection: Built-in
State Management
Redux Store Structure
Store
├── cart
│ ├── items: CartItem[]
│ └── total: number
│
└── wishlist
└── items: WishlistItem[]
Slices:
- cart-slice.ts
- addItemToCart
- removeItemFromCart
- updateQuantity
- clearCart
- wishlist-slice.ts
- addToWishlist
- removeFromWishlist
When to Use Redux vs Server State
Redux (Client State):
- Cart items
- Wishlist
- UI state (modals, filters)
- Temporary data
Server State (Database):
- Products
- User profile
- Orders
- Reviews
Image Processing Pipeline
1. Upload
User selects image file
│
▼
2. Validation
- File type (JPEG, PNG, WebP, GIF)
- File size (<10MB)
- MIME type check
│
▼
3. Processing (Sharp)
├─► Resize to dimensions
│ - Thumbnail: 200x200
│ - Preview: 800x800
│
├─► Center crop
│
├─► Convert to WebP
│
└─► Optimize quality (80%)
│
▼
4. Save
Generate filename:
product-{id}-{type}-{index}.webp
│
▼
5. Database
Store in ProductImage table:
- URL
- Type (THUMBNAIL/PREVIEW)
- Order
│
▼
6. Serve
/images/products/product-1-bg-1.webp
Security Architecture
Layers of Security
1. Input Validation
// Zod schemas validate all inputs
const schema = z.object({
email: z.string().email(),
password: z.string().min(6)
});
2. Authentication
// NextAuth.js session verification
const session = await getServerSession();
if (!session) return unauthorized();
3. Authorization
// Role-based access control
if (session.user.role !== 'ADMIN') {
return forbidden();
}
4. Password Security
// bcrypt hashing (10 salt rounds)
const hashedPassword = await bcrypt.hash(password, 10);
5. SQL Injection Prevention
// Prisma parameterized queries
await prisma.user.findUnique({
where: { email } // Safe from injection
});
6. XSS Prevention
- React automatic escaping
- Content Security Policy headers
- Input sanitization
7. CSRF Protection
- NextAuth.js CSRF tokens
- Same-origin policy
8. Rate Limiting (Planned)
- API endpoint throttling
- Login attempt limits
Deployment Architecture
┌────────────────────────────────────────┐
│ Vercel Edge │
│ (CDN + Edge Functions) │
└────────────────┬───────────────────────┘
│
┌──────────┴──────────┐
│ │
┌─────▼──────┐ ┌───────▼────────┐
│ Static │ │ Server-Side │
│ Assets │ │ Rendering │
│ (Images) │ │ (Next.js) │
└────────────┘ └───────┬────────┘
│
┌───────▼────────┐
│ AWS RDS │
│ (MySQL) │
└────────────────┘
Hosting Strategy
- Frontend: Vercel (automatic deployments)
- Database: AWS RDS (MySQL)
- Images: Vercel CDN
- CI/CD: GitHub Actions → Vercel
Performance Optimizations
Current
- React Server Components (RSC)
- Image optimization (next/image)
- Code splitting (automatic)
- Database indexes
- WebP image format
Planned (Plan 6)
- Redis caching
- CDN for static assets
- Database query optimization
- Lazy loading
- Bundle size reduction
Scalability Considerations
Horizontal Scaling
- Stateless API design
- Session storage (cookies, not server memory)
- Database connection pooling
Vertical Scaling
- Database indexes
- Query optimization
- Caching layers
Future (Plan 6)
- Microservices architecture
- Message queues
- Load balancing
- Database replication
See Also
- Development Guide
- API Reference
- Database Schema
- Plans Roadmap
Library Layer Architecture
The src/lib/ directory contains all shared utilities organized by domain:
src/lib/
├── api/ # API utilities
│ ├── errors.ts # ApiError class, error handling
│ ├── middleware.ts # withAuth, withAdmin, withValidation
│ └── responses.ts # successResponse, errorResponse helpers
│
├── core/ # Core utilities
│ ├── cache.ts # Application-level caching
│ ├── http-cache.ts # HTTP response caching
│ └── ...
│
├── database/ # Database utilities (Plan 169)
│ ├── selects.ts # Standardized Prisma select configs
│ ├── cache.ts # Query caching with Next.js
│ ├── monitor.ts # Query timing & slow query detection
│ ├── dataLoaders.ts # DataLoader for N+1 prevention
│ ├── batch.ts # Batch operations
│ └── pagination.ts # Cursor pagination
│
├── validation/ # Input validation (Plan 165)
│ ├── schemas/
│ │ ├── auth.ts # Login, signup, password schemas
│ │ ├── user.ts # Profile, address schemas
│ │ ├── product.ts # Product, review schemas
│ │ └── order.ts # Cart, checkout schemas
│ ├── errors.ts # ValidationError types
│ └── middleware.ts # withValidation HOC
│
├── security/ # Security utilities
│ ├── rate-limit.ts # Rate limiting
│ └── headers.ts # Security headers
│
├── logging/ # Logging infrastructure
│ ├── logger.ts # Server-side logger
│ └── client-logger.ts # Client-side logger
│
└── ecommerce/ # E-commerce utilities
├── transforms.ts # Data transformation
└── ...
Import Patterns
// API utilities
import { withErrorHandling, ApiError, successResponse } from '@/lib/api';
// Validation
import { loginSchema, signupSchema } from '@/lib/validation';
// Database utilities
import {
productListSelect,
getCachedCategories,
timedQuery,
} from '@/lib/database';
// Security
import { checkRateLimit, addSecurityHeaders } from '@/lib/security';
Query Caching Architecture
Next.js unstable_cache integration for database queries:
Request → Cache Check → Hit? → Return Cached
↓
Miss
↓
Prisma Query
↓
Store in Cache
↓
Return Response
Cache Durations
- STATIC (1 hour): Categories, rarely changing data
- SEMI_STATIC (15 min): Product counts, aggregations
- DYNAMIC (1 min): Product details, user-specific data
- SHORT (15 sec): Real-time data
Cache Invalidation
import { invalidateProductCache } from '@/lib/database';
// After product update
await invalidateProductCache();
Development Tooling
Generators
Scaffold new code with consistent patterns:
# Component with tests & Storybook story
npm run generate:component Button --ui
# API route with tests & docs
npm run generate:api products
Setup Script
Automated development environment setup:
npm run setup # Full setup with prompts
npm run setup:fresh # Clean reinstall
See Also
- Development Guide
- API Reference
- Database Schema
- Hook Development
- Redux Patterns
- API Route Checklist
- Validation Guide
- Query Optimization
Architecture Version: 1.2 Last Updated: December 27, 2025 Next Review: Ongoing with major feature additions