AI Model Tuning with Next.js: A Full-stack Next.js app designed to fine-tune machine learning models
This repository contains a Next.js 15 frontend app for fine-tuning AI models, built with React 19.2, TypeScript, Prisma, and other modern technologies. It is a feature-packed solution designed to handle advanced AI model training workflows, all while providing a sleek and responsive user interface.
- β¨ Features
- ποΈ Architecture
- π οΈ Tech Stack
- π¦ Installation & Setup
- π Quick Start
- π Project Structure
- π¨ Key Features Explained
- π API Integration
- π± Real-time Features
- π License
-
π Advanced Authentication System
- JWT authentication with multi-token support
- OTP verification (Email/SMS/WhatsApp)
- Secure password management
-
π Real-time Dashboard
- Live model training statistics
- Interactive charts and analytics (Line, Bar, Pie)
- Real-time updates via WebSocket
-
π§ Model Tuning & Fine-Tuning
- Intuitive UI for adjusting hyperparameters
- Real-time feedback for training progress
- Easy integration with AI/ML models built in TensorFlow, PyTorch, etc.
-
π Internationalization (i18n)
- Full support for English and Arabic languages
- RTL (Right-to-Left) layout support
- Dynamic language switching
-
βοΈ Advanced Media Management
- Manage datasets and training media
- Google Cloud Storage integration
- File upload, optimization, and caching
-
π Performance & Optimization
- Redis caching for fast API responses
- Lazy loading for media and components
- Code-splitting for optimized loading
-
π¨ Modern UI/UX
- Built with Tailwind CSS for responsive and modern design
- Dynamic theme switching (Dark/Light mode)
- shadcn/ui component library for accessibility
- Next.js 15.1: Server-side rendering, App Router, API Routes
- React 19.2: Concurrent rendering, hooks, and context API
- 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
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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.