FitBuddyAI is a comprehensive AI-powered fitness web application designed for business use, featuring user authentication, cloud persistence, administrative controls, and intelligent workout generation. The platform provides a complete fitness solution with modern UX/UI patterns inspired by successful apps like Duolingo.
- Complete user registration and sign-in system with JWT authentication
- Cloud-based data persistence using Supabase/PostgreSQL
- Cross-tab synchronization for seamless user experience
- Secure user profile management with avatar customization
- Terms of service and privacy policy acceptance tracking
- Google Gemini AI integration for intelligent workout generation
- Comprehensive questionnaire system (8+ questions) for user profiling
- Personalized 30-day workout plans based on user goals and fitness level
- AI chat interface for real-time workout advice and modifications
- Automatic action application from AI responses (JSON parsing and execution)
- Interactive calendar interface with 30-day workout plans
- Color-coded workout types (Strength, Cardio, Flexibility, Mixed, Rest)
- Batch workout addition and deletion capabilities
- Workout completion tracking with progress indicators
- Alternative workout options and equipment-specific modifications
- Energy point system for user engagement
- In-app shop with purchasable avatars and items
- Streak tracking for workout consistency
- Achievement system for progress milestones
- Inventory management for purchased items
- Complete admin audit system with user management
- Banned username management
- Comprehensive audit logging for all user actions
- Server-side admin API with secure token authentication
- User promotion system (basic → admin conversion)
- Automatic cloud backup with debounced saving
- Cross-device data synchronization
- Chat history persistence across sessions
- Acceptance flag tracking in database columns
- Sanitized data handling to prevent corruption
- Duolingo-inspired design with consistent theming
- Fully responsive design for desktop and mobile
- Modern CSS3 with custom properties and animations
- Accessibility compliance with semantic HTML and ARIA attributes
- Professional loading states and error handling
- React 18 with TypeScript for type-safe development
- Vite for fast build tooling and hot module replacement
- React Router for client-side routing
- CSS3 with custom properties for consistent theming
- Lucide React for professional iconography
- date-fns for date manipulation and formatting
- Supabase/PostgreSQL for cloud database and authentication
- Vercel Serverless Functions for API endpoints
- JWT Authentication with secure token management
- Express.js middleware for request handling
- CORS configuration for secure cross-origin requests
- Google Gemini API for workout plan generation
- Advanced JSON parsing with fenced block extraction
- Automatic action application from AI responses
- Context-aware prompting with user data integration
You can link the latest preview deployment from Vercel here for quick access during development.
If automation is failing or you prefer manual control, change the preview link yourself:
- Edit the markdown link target directly by replacing the URL in the markdown immediately after the badge image in readme.md.
- TypeScript for compile-time type checking
- ESLint for code quality enforcement
- Professional component architecture with CSS modules
- Environment variable management for secure configuration
- AI Integration: Google Gemini API
- Animations: Framer Motion
- Node.js >=20.19.0
- npm or yarn
- Google Gemini API key (optional, for AI features)
- Node.js >=20.19.0 and npm
- Git for version control
- VS Code recommended IDE
- Google Cloud Account for Gemini AI API
- Supabase Account for database services
-
Clone the repository
git clone <your-repo-url> cd fitness-app
-
Install dependencies
npm install
-
Environment Configuration
Create a
.envfile in the project root with the following variables:# Server-side Environment Variables (DO NOT expose these to the client) # Set your GEMINI API key here for server processes and Vercel (no VITE_ prefix): GEMINI_API_KEY=your-gemini-api-key-here # Optional feature flags for the frontend (non-secret values only) VITE_ENABLE_AI=true VITE_SUPABASE_URL=your-supabase-project-url VITE_SUPABASE_ANON_KEY=your-supabase-anon-key # Server Environment Variables (no VITE_ prefix) SUPABASE_URL=your-supabase-project-url SUPABASE_KEY=your-supabase-anon-key SUPABASE_SERVICE_ROLE_KEY=your-supabase-service-role-key JWT_SECRET=your-secure-jwt-secret-here ADMIN_API_TOKEN=your-admin-api-token
-
Generate Secure JWT Secret
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))" -
Start Development Server
npm run dev
-
Access Application
- Development:
http://localhost:5173 - Admin Panel:
http://localhost:5173/admin(requires admin privileges)
- Development:
-
The local server has been updated to NEVER persist user progress to local files. All runtime user-data read/write operations now require Supabase. If
SUPABASE_URLand a valid key (preferablySUPABASE_SERVICE_ROLE_KEY) are not configured, user-data endpoints will return HTTP 500 and log a clear error message. This protects sensitive data from being stored on disk inadvertently. -
Required environment variables for local dev user-data (server):
SUPABASE_URL— your Supabase project URLSUPABASE_SERVICE_ROLE_KEYorSUPABASE_KEY— server key (service role key recommended for local dev)
-
Quick PowerShell example to set env and run dev server:
$env:SUPABASE_URL = "https://your-project.supabase.co"
$env:SUPABASE_SERVICE_ROLE_KEY = "your-service-role-key"
npm run dev-
Migration: If you have existing local JSON under
server/user_data/*.jsonyou can migrate them into Supabase using the included script:scripts/migrate_app_users_to_supabase.js— review and run in a controlled environment; it writes output files only when explicitly invoked and is intended as a migration helper (not used by the running server).
-
Key runtime files changed (enforced Supabase-only behavior):
api/userdata/index.ts— removed filesystem fallbacks; usesfitbuddyai_userdatatable and returns errors when Supabase is missing.src/server/userDataStore.js— removed localserver/user_datapersistence; endpoints now upsert/select fromfitbuddyai_userdata.src/server/authServer.jsandsrc/server/authServer.cjs— localusers.jsonreads/writes disabled; these modules now prefer Supabase for user lookups/updates and refuse to write local files when Supabase is not configured.
-
Note on tools & scripts: Admin/migration scripts that are explicitly invoked (in
/scriptsand.github/scripts) may still write files by design — they are one-off tools. Runtime server endpoints and dev server code will not write user data to disk.
If you want a temporary developer fallback (opt-in) instead of failing when Supabase is missing, tell me and I can add a guarded flag (e.g. ALLOW_LOCAL_USERDATA_FALLBACK=true) that enables the old filesystem fallback only when explicitly set.
- Visit Google AI Studio
- Sign in with your Google account
- Create a new API key
- Copy the key to your
.envfile asGEMINI_API_KEY(server-side only)- Do NOT set a
VITE_prefixed Gemini key; the client must never contain secret API keys. - In production, set
GEMINI_API_KEYin your Vercel project environment variables (Project → Settings → Environment Variables).
- Do NOT set a
- Create a new project at supabase.com
- Navigate to Settings → API
- Copy your project URL and anon key
- Generate a service role key for admin operations
- Configure RLS policies for user data security
The project uses strict TypeScript configuration. Ensure your changes compile without errors:
npm run buildsrc/components/
├── WelcomePage.tsx/css # Landing page with feature showcase
├── Questionnaire.tsx/css # AI questionnaire for user profiling
├── WorkoutCalendar.tsx/css # Main calendar with workout management
├── WorkoutModal.tsx/css # Detailed workout view and editing
├── GeminiChatPage.tsx/css # AI chat interface with action parsing
├── ProfilePage.tsx/css # User profile and settings management
├── ShopPage.tsx/css # In-app purchase system
├── AdminAuditPage.tsx/css # Administrative controls and audit logs
├── SignInPage.tsx/css # User authentication
├── SignUpPage.tsx/css # User registration
├── Header.tsx/css # Navigation and user status
├── Footer.tsx/css # Site footer with links
└── AgreementBanner.tsx # Terms/privacy acceptance banner
src/services/
├── aiService.ts # Google Gemini AI integration
├── authService.ts # User authentication and JWT handling
├── cloudBackupService.ts # Supabase data persistence
├── localStorage.ts # Local storage management
├── adminAuth.ts # Admin authentication helpers
└── supabaseAdminClient.ts # Admin database client
api/
├── userdata/
│ ├── index.ts # User data CRUD operations
│ └── [action].ts # Backup/restore actions
├── admin/
│ └── index.ts # Admin user management
├── ai/
│ └── generate.ts # AI workout generation
├── auth/
│ └── index.ts # Authentication endpoints
└── _health.ts # Health check endpoint
- Welcome Page → Feature introduction with animated cards
- Registration/Sign-in → Account creation with cloud persistence
- Questionnaire → AI-powered fitness assessment (8 questions)
- Workout Calendar → 30-day personalized plan with daily workouts
- AI Chat → Real-time workout advice and plan modifications
- Profile Management → Stats tracking, avatar customization
- Shop System → Energy-based purchases for enhanced experience
- User Management: View all users, modify user data, promote to admin
- Audit Logging: Track all user actions and system changes
- Content Moderation: Manage banned usernames and inappropriate content
- System Health: Monitor application performance and error logs
- Automatic Action Parsing: AI responses can modify user data automatically
- JSON Command Extraction: Supports both fenced code blocks and inline JSON
- Workout Modification: AI can update calendar workouts in real-time
- Context Awareness: AI maintains conversation history across sessions
-
Prepare Environment Variables In your Vercel dashboard, configure all environment variables:
VITE_GEMINI_API_KEY=your-gemini-api-key VITE_ENABLE_AI=true VITE_SUPABASE_URL=your-supabase-url VITE_SUPABASE_ANON_KEY=your-supabase-anon-key SUPABASE_URL=your-supabase-url SUPABASE_KEY=your-supabase-anon-key SUPABASE_SERVICE_ROLE_KEY=your-service-role-key JWT_SECRET=your-secure-jwt-secret ADMIN_API_TOKEN=your-admin-token
-
Deploy via Vercel CLI
npm install -g vercel vercel --prod
-
Deploy via GitHub Integration
- Connect your GitHub repository to Vercel
- Environment variables will be automatically applied
- Automatic deployments on push to main branch
- Netlify: Build and drag-drop the
distfolder - AWS S3 + CloudFront: Static hosting with CDN
- GitHub Pages: Free hosting for public repositories
# Production build
npm run build
# Preview production build locally
npm run preview-
Create Tables Execute the SQL scripts in
/sql/directory:-- Run setup_db.sql first -- Then run migrations in order
-
Configure Row Level Security (RLS)
- Enable RLS on all user data tables
- Set policies for user data access
- Configure admin-only access for audit logs
-
User Data Schema
CREATE TABLE user_data ( user_id UUID PRIMARY KEY, payload JSONB, accepted_terms BOOLEAN DEFAULT FALSE, accepted_privacy BOOLEAN DEFAULT FALSE, chat_history JSONB, created_at TIMESTAMP DEFAULT NOW(), updated_at TIMESTAMP DEFAULT NOW() );
To promote a user to admin status, use the SQL command:
UPDATE user_data
SET payload = jsonb_set(payload, '{isAdmin}', 'true')
WHERE user_id = 'user-uuid-here';- Frontend variables (VITE_ prefix) are public and included in build
- Server variables (no prefix) remain secure on server-side
- JWT_SECRET must be cryptographically secure (64+ character hex)
- Service role keys provide admin database access
- User signs in → JWT token generated
- Token stored in localStorage for persistence
- Server validates JWT for protected endpoints
- Admin endpoints require additional API token authentication
- User chat history stored separately from profile data
- Sensitive data backed up before sign-out
- Sanitized payloads prevent data corruption
- Audit logging for all administrative actions
# TypeScript compilation errors
npm run build
# Clear node modules if dependency issues
rm -rf node_modules package-lock.json
npm install- Ensure VITE_ prefix for frontend variables
- Verify Supabase URL format:
https://xxx.supabase.co - Check JWT_SECRET is properly generated hex string
- Confirm API keys have proper permissions
- Verify Supabase project is active
- Check service role key permissions
- Ensure RLS policies allow appropriate access
- Test connection with health endpoint:
/api/_health
- Verify Gemini API key is valid and active
- Check quota limits on Google Cloud Console
- Ensure AI features are enabled:
VITE_ENABLE_AI=true - Monitor API usage for rate limiting
- Code Splitting: Components lazy-loaded where appropriate
- Image Optimization: Use WebP format for assets
- Caching: Service workers for offline functionality
- Database Indexing: Optimize queries with proper indexes
- Weekly: Review audit logs for unusual activity
- Monthly: Update dependencies and security patches
- Quarterly: Review and update AI prompts for accuracy
- As needed: Moderate banned usernames and user reports
- Error Rates: Track JavaScript errors and failed API calls
- Performance: Monitor page load times and user engagement
- Security: Watch for suspicious authentication attempts
- Usage: Track feature adoption and user retention
- Automated: Daily Supabase backups
- Manual: Export user data before major updates
- Recovery: Test restore procedures quarterly
- Codebase: Well-documented with TypeScript interfaces
- API Documentation: Available at
/api/_healthfor status - Admin Panel: Full user management at
/admin - Error Logs: Available through admin audit system
- Supabase Dashboard: Database management and monitoring
- Google Cloud Console: Gemini AI usage and billing
- Vercel Dashboard: Deployment logs and performance metrics
For technical support or feature requests, contact the development team with specific error messages and reproduction steps. 3. Include screenshots if applicable
- Inspired by Duolingo's excellent UX design
- Icons by Lucide React
- AI powered by Google Gemini
- Built with modern React and TypeScript
Happy exercising! 💪🎯