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 & Data Fetching: React Context for global state, and TanStack Query for server state management (with hooks in src/hooks/ and API functions/keys in src/api/).
  • Routing: React Router v6
  • HTTP Client: Fetch API (utilized by 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/ui
  • contexts/: React Context providers for global state (user preferences, auth, etc.)
  • hooks/: Custom hooks for data fetching, local storage, and business logic
  • layouts/: Reusable page structures and layout components
  • pages/: Top-level page components that compose smaller components
  • services/: API integration layer with type-safe interfaces
  • utils/: Shared utility functions and constants

SparkyFitnessServer/ (Backend)

The backend implements a layered architecture with repository pattern:

  • models/: Repository pattern implementations for data access
  • routes/: Express route handlers organized by feature
  • integrations/: External service integrations (food providers, AI services)
  • middleware/: Express middleware for authentication, logging, error handling
  • ai/: AI provider configurations and routing logic
  • utils/: 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

Frontend Data Management with TanStack Query

For new developers, understanding data fetching and state management in the frontend is crucial. SparkyFitness leverages TanStack Query (formerly React Query) for managing server state, which can be a new concept if you're used to simpler global state management solutions.

What is TanStack Query? TanStack Query is a powerful library for managing, caching, and synchronizing server state in your React applications. It handles the complexities of data fetching, including caching, background updates, stale-while-revalidate logic, retries, and error handling, allowing you to focus on your UI.

Why do we use it?

  • Simplified Data Fetching: Reduces boilerplate for data fetching logic.
  • Performance: Aggressive caching and background refetching make the UI feel faster and more responsive.
  • Robustness: Built-in retry mechanisms, error handling, and data synchronization ensure a stable user experience.
  • Developer Experience: Provides powerful hooks (useQuery, useMutation) that integrate seamlessly with React components, abstracting away complex asynchronous logic.

Core Concepts:

  • Queries (useQuery): Used for fetching data (GET requests). They are associated with unique Query Keys (e.g., ['todos', todoId]) which TanStack Query uses for caching and invalidation.
  • Mutations (useMutation): Used for creating, updating, or deleting data on the server (POST, PUT, DELETE requests). Mutations often invalidate relevant queries to ensure the UI reflects the latest server data.
  • Query Keys: Arrays used to uniquely identify queries. They are fundamental for TanStack Query's caching and data synchronization mechanisms.

Integration in SparkyFitness:

  • API Functions: Located in src/api/. These functions define how data is fetched or mutated from the backend. They typically return promises.
  • Query Keys: Also defined in src/api/ alongside their respective API functions, ensuring consistency.
  • Custom Hooks: You'll find useQuery and useMutation implementations wrapped in custom hooks within src/hooks/. These custom hooks abstract the TanStack Query logic, providing a clean interface for components to consume data or trigger server-side changes.

Example (Conceptual): Instead of:

// Component.tsx
useEffect(() => {
  const fetchData = async () => {
    const response = await fetch('/api/users');
    const data = await response.json();
    // ... set state
  };
  fetchData();
}, []);

You'll typically use:

// src/api/userApi.ts
import { api } from '@/services/api';

const userKeys = {
  all: ['users'] as const,
  details: (id: string) => [...userKeys.all, id] as const,
};

const getUsers = () => {
  return api.get('/users');
};

// src/hooks/useUsers.ts
import { useQuery } from '@tanstack/react-query';
import { userKeys, getUsers } from '@/api/userApi';

export const useUsers = () => {
  return useQuery({
    queryKey: userKeys.all,
    queryFn: getUsers,
  });
};

// Component.tsx
import { useUsers } from '@/hooks/useUsers';

const UserList = () => {
  const { data: users, isLoading, isError } = useUsers();

  if (isLoading) return <div>Loading users...</div>;
  if (isError) return <div>Error fetching users</div>;

  return (
    // ... render users
  );
};

This structured approach helps manage data flow efficiently and predictably throughout the application.

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.