Architecture
SparkyFitness is built with a modern, full-stack architecture designed for scalability, maintainability, and performance.
High-Level Overview
The application follows a client-server model, with a clear separation of concerns between the frontend, backend, and database.
┌─────────────────────────────────────────────────────────────────┐
│ SparkyFitness Architecture │
└─────────────────────────────────────────────────────────────────┘
User
│
▼
┌─────────────────────┐
│ React Frontend │
│ (Vite + TypeScript)│
└──────────┬──────────┘
│ HTTP/API
▼
┌─────────────────────┐
│ Node.js/Express API │
│ (Backend) │
└──────────┬──────────┘
│
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────┐ ┌─────────────────┐
│ PostgreSQL │ │ AI Services │ │ External APIs │
│ Database │ │ │ │ │
│ (with RLS) │ │ • OpenAI │ │ • Nutritionix │
└─────────────────┘ │ • Google │ │ • OpenFoodFacts │
│ • Anthropic │ │ • FatSecret │
└─────────────┘ │ • Wger │
└─────────────────┘
Technology Stack
Frontend (src/)
- Framework: React 18 with TypeScript
- Build Tool: Vite for fast development and optimized builds
- UI Components: shadcn/ui built on Tailwind CSS
- State Management: React Context + TanStack Query
- Routing: React Router v6
- HTTP Client: Fetch API with TanStack Query
Backend (SparkyFitnessServer/)
- Runtime: Node.js with Express.js framework
- Database: PostgreSQL with Row Level Security (RLS)
- Authentication: JWT-based authentication
- Architecture Pattern: Repository pattern for data access
- AI Integration: Multi-provider support (OpenAI, Anthropic, Google, etc.)
- External Integrations: Food providers, Exercise data, Health data
Database
- Primary Database: PostgreSQL 15+
- Security: Row Level Security (RLS) for data isolation
- Schema Management: Migration-based schema updates
- Connection: Connection pooling with transaction management
Directory Structure
Root Directory (SparkyFitness/
)
SparkyFitness/
├── src/ # Frontend React application
│ ├── components/ # Reusable UI components
│ ├── contexts/ # React Context providers
│ ├── hooks/ # Custom React hooks
│ ├── pages/ # Page-level components
│ ├── services/ # API service layer
│ └── utils/ # Shared utilities
├── SparkyFitnessServer/ # Backend Node.js application
│ ├── models/ # Repository pattern (database layer)
│ ├── routes/ # Express route handlers
│ ├── integrations/ # External API integrations
│ ├── ai/ # AI provider configurations
│ ├── middleware/ # Express middleware
│ └── utils/ # Backend utilities
├── docker/ # Docker configuration files
└── docs/ # Documentation site (Nuxt Content)
Key Directories Explained
src/
(Frontend)
The frontend follows a component-based architecture with clear separation of concerns:
components/
: Reusable UI components built with shadcn/uicontexts/
: React Context providers for global state (user preferences, auth, etc.)hooks/
: Custom hooks for data fetching, local storage, and business logicpages/
: Top-level page components that compose smaller componentsservices/
: API integration layer with type-safe interfacesutils/
: Shared utility functions and constants
SparkyFitnessServer/
(Backend)
The backend implements a layered architecture with repository pattern:
models/
: Repository pattern implementations for data accessroutes/
: Express route handlers organized by featureintegrations/
: External service integrations (food providers, AI services)middleware/
: Express middleware for authentication, logging, error handlingai/
: AI provider configurations and routing logicutils/
: Backend utilities including database migrations
docker/
Contains all Docker-related configuration:
- Docker Compose files: Separate configurations for development and production
- Dockerfiles: Multi-stage builds for frontend and backend
- Configuration templates: Nginx configuration with environment variable substitution
- Helper scripts: Management scripts for easy Docker operations
docs/
Documentation site built with Nuxt Content and Docus theme:
- Content-driven: All documentation in Markdown with frontmatter
- Auto-generated navigation: Based on file structure and numbering
- Live editing: Supports Nuxt Studio for visual editing
Core Application Features
User Authentication & Access Control
- Individual Users: Full access to their own data
- Family Sharing: Granular permission system for family members
- Row Level Security: Database-enforced data isolation
- JWT Authentication: Secure token-based authentication
Data Management Architecture
- Repository Pattern: All database operations use repository pattern
- Transaction Management: Multi-table operations wrapped in transactions
- External Provider Integration: Modular system for food, exercise, and health data
- Audit Fields:
created_at
,updated_at
on all tables
AI Integration Architecture
Multi-provider AI system supporting various use cases:
AI Integration Flow
User ──► Chat Interface ──► AI Router ──┬──► OpenAI GPT
├──► Google Gemini
└──► Anthropic Claude
│
▼
Database
│
┌─────────┼─────────┐
▼ ▼ ▼
Food Diary Measurements Goals &
Progress
AI Capabilities:
- Food Logging: Natural language food entry and nutrition analysis
- Image Analysis: Photo-based food recognition and logging
- Progress Tracking: Intelligent progress analysis and recommendations
- Goal Management: AI-assisted goal setting and tracking
- Measurement Logging: Conversational body measurement entry
External Integrations
Food Providers
- OpenFoodFacts: Open food database with extensive product information
- Nutritionix: Commercial nutrition database with restaurant chains
- FatSecret: Food database with recipe and meal planning features
Exercise Data
- Wger: Open exercise database with detailed exercise information
- Custom Exercise Library: User-created and community exercises
Health Data
- Apple Health: Integration for importing health and fitness data
- Manual Entry: Direct input for measurements and health metrics
Security Architecture
Database Security
- Row Level Security (RLS): PostgreSQL RLS policies ensure users only access their data
- Encrypted Connections: All database connections use SSL/TLS
- API Key Encryption: All external API keys encrypted at rest
Application Security
- JWT Tokens: Secure authentication with configurable expiration
- Input Validation: Comprehensive input validation and sanitization
- Rate Limiting: API rate limiting to prevent abuse
- CORS Configuration: Properly configured CORS for frontend access
Performance Considerations
Frontend Optimization
- Code Splitting: Route-based code splitting with React.lazy
- State Optimization: TanStack Query for server state caching
- Component Optimization: Memoization and efficient re-rendering
- Bundle Optimization: Vite's optimized production builds
Backend Optimization
- Connection Pooling: PostgreSQL connection pooling
- Query Optimization: Efficient database queries with proper indexing
- Caching Strategy: Response caching for external API calls
- Error Handling: Comprehensive error handling and logging
Database Optimization
- Indexing Strategy: Proper indexing on frequently queried columns
- Query Performance: Optimized queries with explain plans
- Transaction Efficiency: Minimal transaction scope and duration
Deployment Architecture
Docker-based Deployment
- Multi-stage Builds: Optimized Docker images with minimal size
- Environment Separation: Clear separation between development and production
- Service Orchestration: Docker Compose for service coordination
- Health Checks: Container health monitoring and automatic restarts
Production Considerations
- Reverse Proxy: Nginx for load balancing and static file serving
- SSL Termination: SSL/TLS termination at the proxy level
- Environment Variables: Secure configuration management
- Logging Strategy: Centralized logging with structured log formats
Integration Points
Frontend-Backend Communication
- RESTful API: Clean REST API design with consistent response formats
- Type Safety: Shared TypeScript types between frontend and backend
- Error Handling: Standardized error response format
- Authentication: JWT token-based authentication with automatic refresh
Database Integration
- Migration System: Automated database migrations on startup
- Connection Management: Pool-based connection management
- Transaction Patterns: Consistent transaction handling across operations
- Data Validation: Both application-level and database-level validation
This architecture provides a solid foundation for the SparkyFitness application, ensuring scalability, maintainability, and a great user experience.