Architecture and Tech Stack - Jashan-randhawa/AI-FitnessTracker1 GitHub Wiki

🏗️ Architecture & Tech Stack

FitTrack AI is engineered as a decoupled modern web application with a high-performance React 19 single-page client and an Express.js REST API backed by MongoDB.


💻 Full Stack Overview

Frontend Architecture (client/)

  • Core Library: React 19.2
  • Language: TypeScript ~5.9
  • Build Engine: Vite 7.x
  • Design System: Tailwind CSS v4 (using modernized @theme syntax)
  • Routing: React Router v7 (react-router-dom 7.18+)
  • Motion & Micro-interactions: Framer Motion 12.x
  • Data Visualization: Recharts 3.x (Goal rings, calorie balance charts, macro breakdowns)
  • Heatmap Visualization: Custom SVG/Tailwind CalendarHeatmap (90-day activity & nutrition visual grid)
  • Icons: Lucide React
  • Toast Notifications: React Hot Toast

Backend Architecture (server/)

  • Runtime: Node.js >=20.0.0
  • Application Framework: Express.js 4.19
  • Database & ODM: MongoDB with Mongoose 8.x
  • Authentication: Stateless JSON Web Tokens (JWT) signed with HS256 + bcryptjs password hashing
  • Rate Limiting: Multi-tier IP rate limiting plus per-user AI rate limiting (aiUserLimiter keyed on req.user.id) via express-rate-limit
  • AI Resilience & Fallback: Exponential backoff retry (1–2 attempts), automated fallback model failover (OPENROUTER_FALLBACK_MODEL), in-memory 5-minute TTL query cache, and structured JSON repair for Activity Planner
  • File Ingestion: Multer 2.4.x (in-memory buffer handling for vision image uploads)
  • Structured Logging & Tracing: Structured JSON Logger (LOG_LEVEL), secret scrubber (passwords, tokens, API keys), request ID correlation middleware (X-Request-Id), and HTTP access logging
  • Health & Monitoring: Production health check endpoint (GET /api/health) reporting live MongoDB connection state, uptime, and timestamp
  • Security Middleware: Helmet (HTTP security headers), CORS whitelist, environment-gated error handlers, production database error masking
  • Testing: Built-in Node.js test runner (node --test test/*.test.js) with 139 passing unit tests across 37 suites

External Cloud & AI Services

  • OpenRouter AI: Multi-model gateway for GPT-4o / Claude 3.5 / open-source vision and LLMs for food recognition and conversational coaching.
  • Open-Meteo: Free, real-time meteorological API providing temperature, humidity, wind, and Air Quality Index (AQI) without API key requirements.
  • RapidAPI (YouTube138): Workout video discovery and embedded in-app video streaming via authenticated backend proxy.
  • Brevo API: High-deliverability transactional HTTPS email API for expiring password reset tokens.
  • NewsAPI: Live health and fitness news feeds.

CI/CD Pipeline

  • Continuous Integration: GitHub Actions (.github/workflows/ci.yml)
    • Client Job: npm ci ➔ ESLint (npm run lint) ➔ TypeScript Typecheck & Vite Build (npm run build)
    • Server Job: npm ci ➔ Syntax verification (node -c) ➔ App module loading check ➔ Unit tests (npm test)

📦 Modular Packages Layer (GitHub Packages)

Core domain logic, rate limiting, and interaction hooks are decoupled into standalone packages published under @jashan-randhawa/*:

  • @jashan-randhawa/openrouter-resilient-client: Resilient OpenRouter LLM client with automatic fallback failover, jittered retry, and clean JSON extraction.
  • @jashan-randhawa/express-ai-guard: Dual-tier rate limiting (IP + authenticated user ID), request ID correlation, secret scrubbing, and production error masking.
  • @jashan-randhawa/react-calendar-heatmap-streaks: Generic <Heatmap<T>> with 4-level color themes, local timezone calculation, and streak tracking.
  • @jashan-randhawa/react-workout-tracker: Headless useWorkoutSession hook, rest countdown timers, and live workout modal UI.
  • @jashan-randhawa/react-motion-presets: Accessible Framer Motion presets, AnimatedNumber, StreamingWordReveal, and CollapsibleCard.
  • @jashan-randhawa/fitness-utils: Multi-entrypoint fitness math (.), React audio/speech hooks (./react), and PDF report export (./pdf).
  • @jashan-randhawa/ai-nutrition-estimator: Multimodal nutrition intelligence engine with 5-minute TTL caching and medical disclaimers.

📂 Repository Layout

AI-FitnessTracker1/
├── .github/
│   └── workflows/
│       └── ci.yml                       # GitHub Actions CI workflow (lint, build, test)
├── client/                              # React 19 + Vite Client
│   ├── public/                          # Favicons and static assets
│   ├── src/
│   │   ├── Pages/                       # Application Views
│   │   │   ├── Dashboard.tsx            # Analytics, dynamic rings, streak, water
│   │   │   ├── FoodLog.tsx              # Nutrition logging, AI food snap & heatmap
│   │   │   ├── ActivityLog.tsx          # Exercise & calorie burn tracker & heatmap
│   │   │   ├── AIAssistant.tsx          # FitBot AI chat interface
│   │   │   ├── Workouts.tsx             # Video library & Punjabi playlists
│   │   │   ├── MealPlanner.tsx          # Multi-day AI meal plan generator
│   │   │   ├── ActivityPlanner.tsx      # Multi-day AI workout routine generator
│   │   │   ├── Weather.tsx              # Live forecast & AQI monitoring
│   │   │   ├── Blog.tsx / BlogPost.tsx  # Fitness articles & news feed
│   │   │   ├── Profile.tsx              # User metrics, PDF & CSV export
│   │   │   ├── Login.tsx                # Auth form (Sign in / Sign up)
│   │   │   ├── GoogleCallback.tsx       # Secure fragment-based OAuth handler
│   │   │   ├── ForgotPassword.tsx       # Password reset request view
│   │   │   ├── ResetPassword.tsx        # Password update view
│   │   │   └── Onboarding.tsx           # Initial setup questionnaire
│   │   ├── components/                  # Reusable UI Components
│   │   │   ├── BottomNav.tsx            # Mobile fixed bottom navigation dock
│   │   │   ├── Sidebar.tsx              # Responsive sidebar & mobile slide-drawer
│   │   │   ├── CalendarHeatmap.tsx      # 90-day activity & nutrition visual heatmap
│   │   │   ├── Logo.tsx                 # Dynamic SVG animated logo
│   │   │   ├── DateDropdown.tsx         # Date picker dropdown
│   │   │   └── ui/                      # Buttons, inputs, modals, cards
│   │   ├── Context/                     # React Context State Providers
│   │   │   ├── AppContext.tsx           # Global user profile, food, activity state
│   │   │   └── Themecontext.tsx         # Dark / Light theme toggle state
│   │   └── configs/api.ts               # Axios client instance with Bearer interceptor
│   ├── index.html                       # Viewport-fit HTML entry
│   └── vite.config.ts                   # Vite build configuration
│
├── server/                              # Node.js + Express API Server
│   ├── server.js                        # Server entry point
│   ├── test/                            # Automated unit tests (node --test)
│   │   ├── aiAssistant.test.js          # AI payload caps validation tests
│   │   ├── auth.test.js                 # Auth & JWT unit tests
│   │   ├── errorHandler.test.js         # Error handling & production masking tests
│   │   ├── estimates.test.js            # Calorie & food estimate tests
│   │   └── passwordReset.test.js        # Password reset validation tests
│   └── src/
│       ├── app.js                       # Express app configuration & middleware
│       ├── config/db.js                 # MongoDB connection logic
│       ├── models/                      # Mongoose schemas (User, Food, Activity, Water, Blog, Chat)
│       ├── controllers/                 # Request handlers (auth, food, activity, ai, user)
│       ├── routes/                      # Express route definitions
│       ├── middleware/                  # JWT auth, rateLimiter, multer, error handling
│       └── services/                    # OpenRouter AI & Brevo email dispatchers
│
├── IMPLEMENTATION_GUIDE.md              # Architecture and deployment guide
└── LICENSE                              # MIT License
⚠️ **GitHub.com Fallback** ⚠️