Enterprise-Grade Next.js Frontend Application with Real-time Features
A comprehensive, production-ready Next.js 15 frontend application built with React 19, featuring JWT authentication, real-time WebSocket communication, advanced media management, role-based access control, internationalization, and a beautiful modern UI with shadcn/ui components.
- ✨ Features
- 🏗️ Architecture
- 🛠️ Tech Stack
- 📦 Installation & Setup
- 🚀 Quick Start
- 📚 Project Structure
- 🎨 Key Features Explained
- 🔌 API Integration
- 🌐 Internationalization
- 📱 Real-time Features
- 🎯 Usage Examples
- 🐳 Docker Deployment
- 📄 License
-
🔐 Advanced Authentication System
- Multi-token JWT authentication (Access, Session, Refresh tokens)
- OTP verification via Email, SMS, and WhatsApp
- Password management (set, change, reset)
- Email/Phone verification
- Session management with token rotation
- Secure logout with token blacklisting
-
👥 User Management
- Comprehensive user profiles with rich metadata
- User status management (active, inactive, suspended, verified)
- User type classification
- Profile picture upload with MediaPicker integration
- User search and filtering
- Bulk operations support
-
🔑 Role-Based Access Control (RBAC)
- Flexible permission system with groups and permissions
- Permission-based route guards
- Component-level permission checks
- User group management
- Permission analytics and statistics
-
📊 Real-time Dashboard
- Live statistics with WebSocket updates
- Interactive charts (Line, Bar, Pie, Area)
- User growth tracking
- Analytics by status, type, country, language, auth type
- Recent sign-ins monitoring
- Real-time data refresh
-
📁 Advanced Media Management
- Google Cloud Storage & Local Storage support
- MediaPicker component for easy media selection
- Folder organization system
- Public/Private media with access keys
- Image caching and optimization
- Bulk upload and delete operations
- Media statistics and analytics
- Thumbnail generation
- File type detection and organization
-
📝 Activity Logging
- Comprehensive audit trail
- Real-time activity updates via WebSocket
- User action tracking
- Filtering and search capabilities
- Activity statistics (INFO, WARNING, ERROR)
- Detailed activity metadata
-
🌍 Internationalization (i18n)
- Full English and Arabic support
- RTL (Right-to-Left) layout support
- Dynamic language switching
- Module-based translation system
- Automatic locale detection
-
🎨 Modern UI/UX
- Beautiful, responsive design with Tailwind CSS
- shadcn/ui component library
- Dark/Light/System theme support
- Collapsible sidebar navigation
- Advanced search functionality
- Toast notifications
- Confirmation dialogs
- Loading states and skeletons
-
⚡ Real-time Communication
- WebSocket integration with Socket.io
- Real-time dashboard updates
- Live activity log updates
- Instant media library updates
- Notification system
- Room-based subscriptions
-
💾 Caching & Performance
- Redis caching layer
- Client-side image caching
- Media list caching
- Cache invalidation strategies
- Optimized API calls
- Lazy loading and code splitting
-
🔔 Notification System
- Real-time notifications
- Unread count tracking
- Notification dropdown
- Mark as read functionality
-
⚙️ Project Settings
- Logo management (Main, Header, Footer)
- Social media links configuration
- SEO & Meta tags management
- Contact & support information
- General project information
-
📈 System Analytics
- System health monitoring
- Error tracking and logging
- Cache statistics
- Docker status
- Top processes monitoring
- Log viewer with filtering
-
👥 Account Sharing
- Share account access with other users
- Send and receive access invitations
- Request access to other accounts
- Manage shared access permissions
- View account sharing activity
- Access level control (view, edit, full)
- Real-time notifications for sharing events
- Next.js 15.1+: App Router, Server Components, API Routes
- React 19.2: Latest React features with concurrent rendering
- TypeScript 5.0: Full type safety across the application
- Prisma ORM: Type-safe database access with PostgreSQL
- Socket.io: Real-time bidirectional communication
- Tailwind CSS 3.4: Utility-first CSS framework
- shadcn/ui: Beautiful, accessible component library
- Redis: Caching and session management
- Winston: Professional logging system
- Recharts: Beautiful chart library
- Axios: HTTP client for API calls
- ioredis: Redis client for Node.js
- Layout Components: Navbar, Sidebar, Footer, MainLayout
- Form Components: Input, Textarea, Select, OTP Input, Country Selector
- Data Display: Card, Badge, Avatar, Tabs, Charts
- Feedback: Toast, Dialog, Confirm Dialog, Loading States
- Media: MediaPicker, FolderManager, CachedImage
- Navigation: Side Panel, Dropdown Menu
- Authentication: PageGuard, StatusGuard, PermissionGuard
┌───────────────────────────────────────────────────────────────┐
│ Client Browser │
│ (React 19 + Next.js 15) │
└────────────────────────────┬──────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────┐
│ Next.js Application │
│ (Port 3000) │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Client-Side Features: │ │
│ │ - React Components (Client Components) │ │
│ │ - Context Providers (Auth, Theme, i18n, WebSocket) │ │
│ │ - Hooks (useApiCall, usePermissions, useToast) │ │
│ │ - Real-time WebSocket Client │ │
│ │ - Client-side Caching (Media, Images) │ │
│ └──────────────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Server-Side Features: │ │
│ │ - API Routes (Next.js API Routes) │ │
│ │ - Server Components │ │
│ │ - Database Access (Prisma) │ │
│ │ - Redis Caching │ │
│ │ - WebSocket Server (Socket.io) │ │
│ │ - Authentication Middleware │ │
│ │ - Permission Checking │ │
│ └──────────────────────────────────────────────────────────┘ │
└────────────────────────────┬───────────────────────────────────┘
│
┌─────────────┴─────────────┐
▼ ▼
┌──────────────────────────┐ ┌──────────────────────────┐
│ PostgreSQL Database │ │ Redis Cache │
│ (Port 5432) │ │ (Port 6379) │
│ - User Data │ │ - Session Storage │
│ - Permissions │ │ - Media Cache │
│ - Activity Logs │ │ - API Response Cache │
│ - Groups │ │ - Token Blacklist │
│ - Media │ │ - Rate Limiting │
│ - Notifications │ │ │
│ - Account Sharing │ │ │
└──────────────────────────┘ └──────────────────────────┘
│
▼
┌──────────────────────────┐
│ pgAdmin │
│ (Port 5050) │
│ - Database Management │
│ - Query Interface │
│ - Visual Schema Editor │
└──────────────────────────┘
│
▼
┌──────────────────────────┐
│ Google Cloud Storage │
│ (Media & Static Files) │
│ - User Uploads │
│ - Generated Content │
│ - Static Assets │
└──────────────────────────┘
1. User Action (Click, Form Submit, etc.)
│
├─► Client Component
│ ├─► Context (Auth, Theme, i18n)
│ ├─► Custom Hooks (useApiCall, usePermissions)
│ └─► API Service Call
│
├─► Next.js API Route (/api/*)
│ ├─► Authentication Middleware
│ ├─► Permission Check
│ ├─► Request Validation
│ ├─► Business Logic
│ ├─► Database Operations (Prisma)
│ ├─► Cache Management (Redis)
│ ├─► WebSocket Event Emission
│ └─► Response Formatting
│
├─► WebSocket Update (Real-time)
│ └─► Client Receives Update
│ └─► UI Updates Automatically
│
└─► Response
├─► Success/Error Handling
├─► Toast Notification
└─► UI State Update
App Layout
├── Providers (Auth, Theme, i18n, WebSocket, Toast)
├── MainLayout
│ ├── Navbar (Collapsible, Search, Theme Toggle)
│ ├── Sidebar (Navigation, Appearance Settings)
│ ├── TopNav (User Menu, Notifications)
│ └── Content Area
│ ├── PageGuard (Authentication Check)
│ ├── PermissionGuard (Permission Check)
│ └── Page Content
│ ├── Dashboard (Charts, Statistics)
│ ├── Users (List, Create, Edit, Delete)
│ ├── Media (Library, Upload, Manage)
│ ├── Activity (Logs, Filtering)
│ ├── Settings (Profile, Project, System)
│ └── Admin (Access Control, Analytics)
└── Footer
- Next.js 15.1.5: React framework with App Router
- React 19.2.0: UI library with concurrent features
- TypeScript 5.0: Type-safe JavaScript
- Tailwind CSS 3.4: Utility-first CSS framework
- shadcn/ui: High-quality React components
- Lucide React: Beautiful icon library
- Recharts 3.5: Charting library
- React Context API: Global state management
- React Hooks: Custom hooks for data fetching
- Axios: HTTP client
- Prisma Client: Database ORM
- Socket.io Client 4.8: Real-time WebSocket communication
- Socket.io Server: WebSocket server integration
- Redis 7 (ioredis): Server-side caching (included in Docker setup)
- Client-side Cache: Media and image caching
- localStorage: Client-side persistence
- Docker Volumes: Persistent data storage for database and cache
- JWT (jsonwebtoken): Token-based authentication
- bcryptjs: Password hashing
- Session Management: Secure session handling
- PostgreSQL 16: Relational database (included in Docker setup)
- Prisma 7.0: Next-generation ORM
- Prisma Client: Type-safe database access
- pgAdmin 4: Database management UI (included in Docker setup)
- Winston: Logging system
- UUID: Unique identifier generation
- Class Variance Authority: Component variants
- clsx & tailwind-merge: Conditional class names
System Requirements:
- OS: Linux (Ubuntu 20.04+), macOS, or Windows with WSL2
- Docker: 20.10+ (recommended for easy setup)
- Docker Compose: 2.0+ (for multi-container orchestration)
- Node.js: 18.0 or higher (for local development without Docker)
- npm: 9.0 or higher (for local development without Docker)
- PostgreSQL: 16+ (included in Docker setup)
- Redis: 7+ (included in Docker setup)
Development Tools:
- Git 2.30+
- Code editor (VS Code recommended)
- Postman or similar API testing tool
- Make (optional, for convenient commands)
Step 1: Clone Repository
git clone <repository-url>
cd nextjs-frontend-starterStep 2: Setup Environment
# Copy example environment file
cp example.env .env
# Edit .env file with your configuration (optional - defaults work)
nano .envStep 3: Start All Services with Docker Compose
# Using Make (recommended)
make up
# Or using Docker Compose directly
docker compose up -dThis will automatically:
- ✅ Start PostgreSQL database
- ✅ Start Redis cache
- ✅ Start Next.js application
- ✅ Start pgAdmin (database management UI)
- ✅ Run database migrations
- ✅ Seed database with default data
Step 4: Access Application
- Application: http://localhost:3000
- pgAdmin: http://localhost:5050
- Email:
admin@example.com(or yourPGADMIN_EMAIL) - Password:
admin@123(or yourPGADMIN_PASSWORD)
- Email:
- Database:
localhost:5432 - Redis:
localhost:6379 - API Routes: http://localhost:3000/api/*
- Health Check: http://localhost:3000/api/health
Useful Commands:
make help # Show all available commands
make logs # View all service logs
make logs-app # View app logs only
make db-shell # Open PostgreSQL shell
make db-migrate # Run Prisma migrations
make db-seed # Seed the database
make shell # Open app container shell
make down # Stop all services
make clean # Stop and remove volumesStep 1: Clone Repository
git clone <repository-url>
cd nextjs-frontend-starterStep 2: Install Dependencies
npm installStep 3: Setup Environment
# Copy example environment file
cp example.env .env
# Edit .env file with your configuration
nano .envRequired Environment Variables:
# Application
APP_MODE=development
APP_INTERNAL_PORT=3000
# API Configuration
NEXT_PUBLIC_API_URL=http://localhost:3000
API_INTERNAL_URL=http://localhost:3000
# Database (PostgreSQL)
DATABASE_HOST=localhost
DATABASE_NAME=postgres
DATABASE_USER=nextjs_db
DATABASE_PASSWORD=postgres123
DATABASE_PORT=5432
DATABASE_URL=postgresql://nextjs_db:postgres123@localhost:5432/postgres?schema=public
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_URL=redis://localhost:6379
REDIS_CACHE_ENABLED=true
# JWT
JWT_SECRET=your-secret-key
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRY_MINUTES=60
SESSION_TOKEN_EXPIRY_MINUTES=10080
REFRESH_TOKEN_EXPIRY_MINUTES=43200
# Storage (Optional - for media uploads)
GOOGLE_STORAGE_BUCKET_NAME=your-bucket-name
STORAGE_BUCKET=your-bucket-name
# Media Access
MEDIA_ENABLE_ACCESS_KEY=true
MEDIA_ACCESS_KEY_LENGTH=32
MEDIA_REQUIRE_ACCESS_KEY_FOR_PUBLIC=false
MEDIA_ALLOW_ADMIN_ACCESS_WITHOUT_KEY=true
# pgAdmin (for Docker setup)
PGADMIN_EMAIL=admin@example.com
PGADMIN_PASSWORD=admin@123
PGADMIN_PORT=5050Step 4: Setup Database
# Generate Prisma Client
npm run db:generate
# Push schema to database
npm run db:push
# Seed database with default data
npm run db:seedStep 5: Start Development Server
# Development mode with hot reload
npm run dev
# Or start production build
npm run build
npm startStep 6: Access Application
- Application: http://localhost:3000
- API Routes: http://localhost:3000/api/*
- Health Check: http://localhost:3000/api/health
Start All Services:
# Using Make (recommended)
make up
# Or using Docker Compose directly
docker compose up -dView Logs:
# All services
make logs
# Specific service
make logs-app
make logs-db
make logs-redis
make logs-pgadmin
# Or using Docker Compose
docker compose logs -f
docker compose logs -f appDatabase Management:
# Open PostgreSQL shell
make db-shell
# Run migrations
make db-migrate
# Seed database
make db-seed
# Open Prisma Studio
make db-studio
# Reset database
make db-resetStop Services:
# Stop all services
make down
# Stop and remove volumes
make clean
# Or using Docker Compose
docker compose down
docker compose down -vAccess Points:
- App: http://localhost:3000
- pgAdmin: http://localhost:5050
- Database: localhost:5432
- Redis: localhost:6379
Development Mode:
# Install dependencies
npm install
# Setup environment
cp example.env .env
# Edit .env with your configuration
# Setup database (requires PostgreSQL running)
npm run db:generate
npm run db:push
npm run db:seed
# Start development server
npm run devProduction Build:
# Build application
npm run build
# Start production server
npm start
# Or use PM2
npm run pm2:startStart in Development Mode:
# Start with development overrides
docker compose -f docker-compose.yaml -f docker-compose.dev.yaml up -d
# Or using Make
make up-devThis enables:
- Hot-reload for code changes
- Development optimizations
- Easier debugging
nextjs-frontend-starter/
├── 📁 src/
│ ├── 📁 app/ # Next.js App Router
│ │ ├── 📁 (auth)/ # Authentication pages
│ │ │ ├── login/ # Login page
│ │ │ ├── signup/ # Signup page
│ │ │ ├── verify/ # Email/Phone verification
│ │ │ ├── set-password/ # Set password
│ │ │ └── forgot-password/ # Password recovery
│ │ ├── 📁 api/ # API Routes
│ │ │ ├── auth/ # Authentication endpoints
│ │ │ ├── users/ # User management
│ │ │ ├── dashboard/ # Dashboard statistics
│ │ │ ├── media/ # Media management
│ │ │ ├── activity/ # Activity logs
│ │ │ ├── permissions/ # Permissions & groups
│ │ │ ├── settings/ # User settings
│ │ │ └── notifications/ # Notifications
│ │ ├── 📁 admin/ # Admin pages
│ │ │ ├── users/ # User management
│ │ │ ├── access-control/ # Permissions & groups
│ │ │ ├── project-settings/ # Project configuration
│ │ │ └── system-analytics/ # System monitoring
│ │ ├── dashboard/ # Dashboard page
│ │ ├── media/ # Media library
│ │ ├── activity/ # Activity logs
│ │ ├── profile-settings/ # User profile settings
│ │ ├── notifications/ # Notifications page
│ │ ├── layout.tsx # Root layout
│ │ └── page.tsx # Home page
│ │
│ ├── 📁 components/ # React Components
│ │ ├── 📁 auth/ # Authentication components
│ │ │ ├── PageGuard.tsx # Route protection
│ │ │ └── StatusGuard.tsx # User status check
│ │ ├── 📁 layout/ # Layout components
│ │ │ ├── MainLayout.tsx # Main app layout
│ │ │ ├── Navbar.tsx # Sidebar navigation
│ │ │ └── TopNav.tsx # Top navigation bar
│ │ ├── 📁 dashboard/ # Dashboard components
│ │ │ ├── ChartCard.tsx # Chart container
│ │ │ ├── LineChart.tsx # Line chart
│ │ │ ├── BarChart.tsx # Bar chart
│ │ │ ├── PieChart.tsx # Pie chart
│ │ │ └── AreaChart.tsx # Area chart
│ │ ├── 📁 media/ # Media components
│ │ │ ├── MediaPicker.tsx # Media selection component
│ │ │ ├── FolderManager.tsx # Folder management
│ │ │ └── CachedImage.tsx # Optimized image component
│ │ ├── 📁 ui/ # shadcn/ui components
│ │ │ ├── button.tsx # Button component
│ │ │ ├── card.tsx # Card component
│ │ │ ├── input.tsx # Input component
│ │ │ ├── dialog.tsx # Dialog component
│ │ │ └── ... # More UI components
│ │ └── 📁 permissions/ # Permission components
│ │ ├── PermissionGuard.tsx # Permission check
│ │ └── PermissionButton.tsx # Permission-based button
│ │
│ ├── 📁 context/ # React Context Providers
│ │ ├── AuthContext.tsx # Authentication context
│ │ ├── ThemeContext.tsx # Theme management
│ │ ├── I18nContext.tsx # Internationalization
│ │ ├── WebSocketContext.tsx # WebSocket connection
│ │ └── Provider.tsx # Combined providers
│ │
│ ├── 📁 hooks/ # Custom React Hooks
│ │ ├── useApiCall.ts # API call hook
│ │ ├── useAuth.ts # Authentication hook
│ │ ├── usePermissions.ts # Permission checking
│ │ ├── useToast.ts # Toast notifications
│ │ └── useDebounce.ts # Debounce utility
│ │
│ ├── 📁 services/ # API Service Layer
│ │ ├── auth.service.ts # Authentication service
│ │ ├── user.service.ts # User service
│ │ ├── media.service.ts # Media service
│ │ ├── dashboard.service.ts # Dashboard service
│ │ ├── permission.service.ts # Permission service
│ │ └── websocket.service.ts # WebSocket service
│ │
│ ├── 📁 lib/ # Utility Libraries
│ │ ├── 📁 api/ # API utilities
│ │ │ ├── ApiService.ts # API service class
│ │ │ └── ApiServiceFactory.ts # API factory
│ │ ├── 📁 cache/ # Caching utilities
│ │ │ ├── cache.ts # Redis cache
│ │ │ ├── mediaCache.ts # Media cache
│ │ │ └── imageCache.ts # Image cache
│ │ ├── 📁 authenticate/ # Auth utilities
│ │ │ ├── helpers.ts # Auth helpers
│ │ │ └── session-manager.ts # Session management
│ │ ├── 📁 middleware/ # Middleware
│ │ │ ├── auth.ts # Auth middleware
│ │ │ └── permission-check.ts # Permission middleware
│ │ └── 📁 multilingual/ # i18n utilities
│ │ └── i18n.ts # Translation loader
│ │
│ ├── 📁 models/ # TypeScript Models
│ │ ├── user.model.ts # User types
│ │ ├── media.model.ts # Media types
│ │ ├── permission.model.ts # Permission types
│ │ └── api.model.ts # API response types
│ │
│ ├── 📁 locales/ # Translation Files
│ │ ├── 📁 en/ # English translations
│ │ │ ├── general.json # General terms
│ │ │ ├── auth.json # Auth terms
│ │ │ ├── dashboard.json # Dashboard terms
│ │ │ └── ... # More modules
│ │ └── 📁 ar/ # Arabic translations
│ │ └── ... # Same structure
│ │
│ └── 📁 types/ # TypeScript Types
│ ├── axios.ts # Axios types
│ └── cache.d.ts # Cache types
│
├── 📁 prisma/ # Prisma ORM
│ ├── schema.prisma # Database schema
│ ├── seed-defaults.js # Seed data
│ └── migrations/ # Database migrations
│
├── 📁 scripts/ # Helper Scripts
│ ├── init-db.sql # PostgreSQL initialization
│ └── pgadmin-servers.json # pgAdmin server config
│
├── 📁 public/ # Static Assets
│ └── uploads/ # Uploaded media (local)
│
├── 📄 server.js # Custom Next.js server
├── 📄 start.sh # Startup script (auto migrations)
├── 📄 Makefile # Docker management commands
├── 📄 next.config.ts # Next.js configuration
├── 📄 tailwind.config.js # Tailwind configuration
├── 📄 tsconfig.json # TypeScript configuration
├── 📄 package.json # Dependencies
├── 📄 docker-compose.yaml # Docker Compose config
├── 📄 docker-compose.dev.yaml # Development override
├── 📄 Dockerfile # Docker image
├── 📄 example.env # Environment variables template
└── 📄 README.md # This file
Multi-Token Architecture:
- Access Token: Short-lived (1 hour) for API authentication
- Session Token: Medium-lived (7 days) with full user data
- Refresh Token: Long-lived (30 days) for token renewal
Features:
- Login with password or OTP
- Email/Phone verification
- Password management (set, change, reset)
- Secure session management
- Token rotation on refresh
Usage Example:
import { useAuth } from "@context/AuthContext"
function MyComponent() {
const { user, login, logout, isAuthenticated } = useAuth()
if (!isAuthenticated) {
return <LoginForm onLogin={login} />
}
return <div>Welcome, {user?.email}</div>
}Features:
- Live statistics with WebSocket updates
- Interactive charts (Line, Bar, Pie, Area)
- User growth tracking
- Analytics by multiple dimensions
- Real-time data refresh
WebSocket Integration:
import { useWebSocket } from "@context/WebSocketContext"
function Dashboard() {
const { onUserCreated, onUserUpdated, onDashboardStatsUpdate } = useWebSocket()
useEffect(() => {
onUserCreated(() => {
// Refresh dashboard data
refreshDashboard()
})
}, [])
}Features:
- Google Cloud Storage & Local Storage support
- MediaPicker component for easy selection
- Folder organization
- Public/Private media with access keys
- Image caching and optimization
- Bulk operations
MediaPicker Usage:
import { MediaPicker } from "@components/media/MediaPicker"
function MyComponent() {
const [pickerOpen, setPickerOpen] = useState(false)
return (
<>
<Button onClick={() => setPickerOpen(true)}>
Select Media
</Button>
<MediaPicker
open={pickerOpen}
onClose={() => setPickerOpen(false)}
onSelect={(media) => {
// Handle selected media
console.log(media)
}}
mode="image"
allowUrl={true}
allowUpload={true}
/>
</>
)
}Features:
- English and Arabic support
- RTL layout support
- Dynamic language switching
- Module-based translations
Usage:
import { useModuleI18n } from "@context/I18nContext"
function MyComponent() {
const { t } = useModuleI18n("general")
const { t: tAuth } = useModuleI18n("auth")
return (
<div>
<h1>{t("welcome")}</h1>
<button>{tAuth("login")}</button>
</div>
)
}Features:
- Permission-based route guards
- Component-level permission checks
- User group management
- Permission analytics
Usage:
import { PermissionGuard } from "@components/permissions/PermissionGuard"
import { usePermissions } from "@hooks/usePermissions"
function MyComponent() {
const { hasPermission } = usePermissions()
return (
<PermissionGuard requirePermission="manage_users">
<UserManagementPanel />
</PermissionGuard>
)
}The application uses a centralized API service for all HTTP requests:
import { createPublicApiService } from "@lib/api/ApiServiceFactory"
const apiService = createPublicApiService()
// GET request
const response = await apiService.get("/api/users")
// POST request
const response = await apiService.post("/api/users", { name: "John" })
// With authentication
const authApi = createPublicApiService({
"X-Session-Token": sessionToken
})import { useApiCall } from "@hooks/useApiCall"
function MyComponent() {
const fetchUsers = useApiCall(
async () => {
return await userService.getUsers()
},
{
onSuccess: (data) => {
console.log("Users loaded:", data)
},
onError: (error) => {
console.error("Error:", error)
},
showErrorToast: true,
}
)
useEffect(() => {
fetchUsers.execute()
}, [])
return (
<div>
{fetchUsers.loading && <Loader />}
{fetchUsers.data && <UserList users={fetchUsers.data} />}
</div>
)
}Connection:
import { useWebSocket } from "@context/WebSocketContext"
function MyComponent() {
const {
connected,
subscribeToDashboard,
onUserCreated,
onMediaUpdated
} = useWebSocket()
useEffect(() => {
subscribeToDashboard()
onUserCreated((user) => {
console.log("New user created:", user)
})
onMediaUpdated((media) => {
console.log("Media updated:", media)
})
}, [])
}Available Events:
user:created- New user registereduser:updated- User profile updateduser:deleted- User deletedmedia:created- New media uploadedmedia:updated- Media updatedmedia:deleted- Media deletedfolder:created- Folder createdfolder:updated- Folder updatedfolder:deleted- Folder deletedactivity:new- New activity logdashboard:stats:update- Dashboard statistics updated
"use client"
import { MainLayout } from "@components/layout/MainLayout"
import { PageGuard } from "@components/auth/PageGuard"
import { PermissionGuard } from "@components/permissions/PermissionGuard"
export default function MyPage() {
return (
<PageGuard requireAuth>
<PermissionGuard requirePermission="view_my_feature">
<MainLayout
title="My Page"
description="Page description"
>
<div>
{/* Your page content */}
</div>
</MainLayout>
</PermissionGuard>
</PageGuard>
)
}import { MediaPicker } from "@components/media/MediaPicker"
import { useState } from "react"
function ProfileForm() {
const [mediaPickerOpen, setMediaPickerOpen] = useState(false)
const [logoUrl, setLogoUrl] = useState("")
return (
<>
<Input
value={logoUrl}
placeholder="Logo URL"
/>
<Button onClick={() => setMediaPickerOpen(true)}>
Select Logo
</Button>
<MediaPicker
open={mediaPickerOpen}
onClose={() => setMediaPickerOpen(false)}
onSelect={(media) => {
const url = typeof media === 'string'
? media
: media.public_url
setLogoUrl(url)
setMediaPickerOpen(false)
}}
mode="image"
/>
</>
)
}import { useToast } from "@hooks/useToast"
function MyComponent() {
const { showSuccess, showError, showInfo } = useToast()
const handleSave = async () => {
try {
await saveData()
showSuccess("Data saved successfully!")
} catch (error) {
showError("Failed to save data")
}
}
}The project includes a complete Docker Compose setup with all required services:
Services:
- app: Next.js application (Port 3000)
- postgres: PostgreSQL 16 database (Port 5432)
- redis: Redis 7 cache (Port 6379)
- pgadmin: Database management UI (Port 5050)
- nginx: Reverse proxy (Port 9080, optional)
# Start all services
make up
# or
docker compose up -d
# View logs
make logs
# or
docker compose logs -f
# Stop services
make down
# or
docker compose downThe docker-compose.yaml includes:
- Automatic database migrations on startup
- Database seeding with default data
- Health checks for all services
- Volume persistence for data
- Network isolation for security
- Resource limits for production
Key environment variables for Docker:
# Database (auto-configured for Docker)
DATABASE_HOST=postgres
DATABASE_NAME=postgres
DATABASE_USER=nextjs_db
DATABASE_PASSWORD=postgres123
DATABASE_PORT=5432
DATABASE_URL=postgresql://nextjs_db:postgres123@postgres:5432/postgres?schema=public
# Redis (auto-configured for Docker)
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_URL=redis://redis:6379
# pgAdmin
PGADMIN_EMAIL=admin@example.com
PGADMIN_PASSWORD=admin@123
PGADMIN_PORT=5050
# Migration & Seed settings
WAIT_FOR_DB=true
DB_WAIT_TIMEOUT=60
SKIP_MIGRATIONS=false
SKIP_SEED=falseAccess pgAdmin:
- Open http://localhost:5050
- Login with:
- Email:
admin@example.com(or yourPGADMIN_EMAIL) - Password:
admin@123(or yourPGADMIN_PASSWORD)
- Email:
Connect to Database:
- The database server is pre-configured in pgAdmin
- Server name: "Next.js Frontend DB"
- Host:
postgres(internal Docker network) - Port:
5432 - Username:
nextjs_db(or yourDATABASE_USER) - Password:
postgres123(or yourDATABASE_PASSWORD)
Build Docker Image:
# Build image
make build
# or
docker compose build
# Build for production (no cache)
make prod-buildDeploy to Production:
# Pull latest images and deploy
make prod-deploy
# or
docker compose pull
docker compose up -d --build
docker compose exec app npx prisma migrate deployView Service Status:
# Check container status
make status
# or
docker compose ps
# Check health
make healthStart in Development Mode:
# With hot-reload and development optimizations
make up-dev
# or
docker compose -f docker-compose.yaml -f docker-compose.dev.yaml up -dAccess Container Shell:
# App container
make shell
# or
docker compose exec app sh
# PostgreSQL container
make shell-postgres
# or
docker compose exec postgres sh
# Redis container
make shell-redis
# or
docker compose exec redis shRun Migrations:
# Production migrations
make db-migrate
# or
docker compose exec app npx prisma migrate deploy
# Development migrations
make db-migrate-dev
# or
docker compose exec app npx prisma migrate devSeed Database:
make db-seed
# or
docker compose exec app npx prisma db seedOpen Prisma Studio:
make db-studio
# or
docker compose exec app npx prisma studioReset Database:
make db-reset
# or
docker compose exec app npx prisma migrate reset --forceStop and Remove:
# Stop services
make down
# Stop and remove volumes (clean slate)
make clean
# Remove images
make clean-images
# Full cleanup (prune everything)
make pruneThe start.sh script automatically handles database setup on container startup:
Features:
- ✅ Waits for database to be ready (configurable timeout)
- ✅ Runs Prisma migrations automatically
- ✅ Seeds database with default data (if empty)
- ✅ Generates Prisma Client if needed
- ✅ Handles errors gracefully with retries
Environment Variables:
# Database wait settings
WAIT_FOR_DB=true # Wait for database (default: true)
DB_WAIT_TIMEOUT=60 # Wait timeout in seconds (default: 60)
# Migration & seed settings
SKIP_MIGRATIONS=false # Skip migrations (default: false)
SKIP_SEED=false # Skip seeding (default: false)
FORCE_SEED=false # Force seed even if data exists (default: false)Manual Control:
# Skip migrations on startup
SKIP_MIGRATIONS=true docker compose up -d
# Skip seeding on startup
SKIP_SEED=true docker compose up -d
# Force seed even if data exists
FORCE_SEED=true docker compose up -dRecommended Production Setup:
- Use external PostgreSQL (managed database service)
- Use external Redis (managed cache service)
- Configure environment variables for production
- Enable Nginx reverse proxy (optional)
- Set up SSL/TLS certificates
- Configure backups for database
- Set up monitoring and logging
Start with Nginx:
make up-nginx
# or
docker compose --profile with-nginx up -dFrom Host Machine:
# Connect to PostgreSQL
psql -h localhost -p 5432 -U nextjs_db -d postgres
# Or using Docker
docker compose exec postgres psql -U nextjs_db -d postgresConnection String:
postgresql://nextjs_db:postgres123@localhost:5432/postgres
From Application (Docker Network):
postgresql://nextjs_db:postgres123@postgres:5432/postgres
# Development
npm run dev # Start development server
npm run build # Build for production
npm start # Start production server
# Database
npm run db:generate # Generate Prisma Client
npm run db:push # Push schema to database
npm run db:seed # Seed database
npm run db:studio # Open Prisma Studio
npm run db:migrate # Run migrations
# PM2 (Process Manager)
npm run pm2:start # Start with PM2
npm run pm2:stop # Stop PM2 process
npm run pm2:restart # Restart PM2 process
npm run pm2:logs # View PM2 logs
# Linting & Formatting
npm run lint # Run ESLint
npm run format # Format code with PrettierThe project includes a comprehensive Makefile for convenient Docker management:
# Docker Commands
make build # Build Docker images
make up # Start all services
make up-dev # Start in development mode
make up-nginx # Start with Nginx reverse proxy
make down # Stop all services
make restart # Restart all services
make logs # View all service logs
make logs-app # View app logs only
make logs-db # View database logs only
make logs-redis # View Redis logs only
make logs-pgadmin # View pgAdmin logs only
# Database Commands
make db-shell # Open PostgreSQL shell
make db-migrate # Run Prisma migrations
make db-migrate-dev # Run development migrations
make db-seed # Seed the database
make db-reset # Reset database (migrate + seed)
make db-studio # Open Prisma Studio
make db-generate # Generate Prisma Client
make db-push # Push schema to database
# Utility Commands
make shell # Open bash shell in app container
make shell-postgres # Open shell in postgres container
make shell-redis # Open shell in redis container
make status # Show container status
make health # Check service health
# Cleanup Commands
make clean # Stop services and remove volumes
make clean-images # Remove Docker images
make prune # Clean up all Docker resources
# Development Commands
make dev # Start local development server
make install # Install dependencies
make lint # Run linter
make format # Format code
# Production Commands
make prod-build # Build for production (no cache)
make prod-up # Start production services
make prod-deploy # Deploy to production
# Help
make help # Show all available commandsQuick Reference:
| Command | Description |
|---|---|
make up |
Start all services |
make down |
Stop all services |
make logs |
View logs |
make db-shell |
Open database shell |
make db-migrate |
Run migrations |
make shell |
Open app container |
make clean |
Clean up everything |
- JWT Authentication: Secure token-based authentication
- Password Hashing: bcrypt with configurable salt rounds
- Token Blacklisting: Redis-based token invalidation
- Permission Guards: Route and component-level protection
- Input Validation: Server-side validation for all inputs
- CORS Protection: Configurable CORS origins
- Rate Limiting: Request throttling (via backend)
- Secure Headers: Helmet.js security headers
- Media Access Control: Access keys for private media
The application supports three theme modes:
- Light Mode: Bright, clean interface
- Dark Mode: Dark, eye-friendly interface
- System Mode: Automatically follows system preference
Theme Switching:
import { useTheme } from "@context/ThemeContext"
function ThemeToggle() {
const { theme, setTheme } = useTheme()
return (
<select value={theme} onChange={(e) => setTheme(e.target.value)}>
<option value="light">Light</option>
<option value="dark">Dark</option>
<option value="dynamic">System</option>
</select>
)
}- Image Optimization: Next.js Image component with caching
- Code Splitting: Automatic route-based code splitting
- Lazy Loading: Dynamic imports for heavy components
- Client-side Caching: Media and image caching
- Server-side Caching: Redis caching for API responses
- Optimistic Updates: Immediate UI updates with background sync
- Debouncing: Debounced search and input handlers
- Memoization: React.memo and useMemo for expensive computations
# Run tests (when implemented)
npm test
# Run tests in watch mode
npm test:watch
# Run tests with coverage
npm test:coverageServices won't start:
# Check if ports are already in use
netstat -tulpn | grep -E '3000|5432|6379|5050'
# Stop conflicting services or change ports in .envDatabase connection errors:
# Check if database is ready
make health
# or
docker compose exec postgres pg_isready -U postgres
# View database logs
make logs-dbMigrations failing:
# Reset database and try again
make db-reset
# Or manually run migrations
make db-migrateVolume permission issues:
# Fix permissions
sudo chown -R $USER:$USER ./volumesContainer won't start:
# Check logs
make logs
# Rebuild containers
make clean
make build
make upCan't connect to database:
- Check if PostgreSQL container is running:
docker compose ps - Verify environment variables in
.env - Check database logs:
make logs-db - Try connecting manually:
make db-shell
Migrations not running:
- Check
SKIP_MIGRATIONSenvironment variable - Manually run:
make db-migrate - Check Prisma schema:
npx prisma validate
Seed data not loading:
- Check if database is empty:
make db-shellthenSELECT COUNT(*) FROM "User"; - Force seed:
FORCE_SEED=true docker compose up -d - Manually seed:
make db-seed
Can't access pgAdmin:
- Check if pgAdmin is running:
docker compose ps pgadmin - Verify port 5050 is not in use
- Check logs:
make logs-pgadmin - Verify credentials in
.envfile
Can't connect to database in pgAdmin:
- Use
postgresas hostname (Docker network) - Port:
5432 - Username:
postgres(or yourDATABASE_USER) - Password:
postgres123(or yourDATABASE_PASSWORD)
Redis connection errors:
# Check if Redis is running
docker compose ps redis
# Test Redis connection
docker compose exec redis redis-cli ping
# View Redis logs
make logs-redisApp won't start:
- Check logs:
make logs-app - Verify environment variables
- Check database connection
- Rebuild:
make clean && make build && make up
Build errors:
# Clean build
make clean
make build
# Check for TypeScript errors
npm run lintThis project is licensed under the MIT License - see the LICENSE file for details.
Built with amazing open-source technologies:
- Next.js - React framework
- React - UI library
- TypeScript - Type safety
- Prisma - Database ORM
- PostgreSQL - Relational database
- Redis - In-memory data store
- Docker - Containerization platform
- Tailwind CSS - CSS framework
- shadcn/ui - Component library
- Socket.io - Real-time communication
- Recharts - Chart library
Made with ❤️ using modern web technologies
This project is free to use, modify, and distribute for any purpose without restrictions.