SparkyFitness Documentation

repository·main·Indexed 26 days ago

https://github.com/codewithcj/sparkyfitness

A self-hosted, privacy-focused fitness and nutrition tracking platform featuring a backend API, web frontend, and native mobile apps. Documentation covers codebase architecture, Row Level Security (RLS) patterns, feature implementation workflows, database migration checklists, and deployment guides for Docker, Helm (Kubernetes), and NixOS.

Tokens
95K
Snippets
146
Records
495
Agent score
90%

What's inside SparkyFitness

  1. Overview of SparkyFitness Architecture

    main

    SparkyFitness uses a client-server model with a clear separation of concerns:

    • Frontend: A React application (Vite + TypeScript) that communicates with the backend via HTTP/API.
    • Backend: A Node.js/Express.js API that handles business logic, authentication, and integrations.
    • Data Layer: A PostgreSQL database (v15+) utilizing Row Level Security (RLS) for data isolation, alongside AI services (OpenAI, Anthropic, Google) and external APIs (Nutritionix, OpenFoodFacts, etc.).
  2. Overview of SparkyFitness

    main
    SparkyFitness is a full-stack, self-hosted fitness tracking application designed as an alternative to MyFitnessPal. It allows users to monitor nutrition, exercise, and body measurements while maintaining complete control over their data. The platform includes AI-powered nutrition assistance for chat-based food logging and image recognition.
  3. Overview of Testing Patterns by Layer

    main

    The SparkyFitness project follows a layered testing strategy. Use the appropriate framework and approach based on the layer you are testing:

    LayerFrameworkFocusLocation
    RouteVitest + supertestHTTP contract, status codes, validationSparkyFitnessServer/tests/<domain>Routes.test.ts
    ServiceVitestBusiness logic, orchestration, error handlingSparkyFitnessServer/tests/<domain>Service.test.ts
    RepositoryVitestSQL query shape and mapping (mocked)SparkyFitnessServer/tests/<domain>Repository.test.ts
    RLS PolicyVitest + real DBRow-level security, permissions, delegationSparkyFitnessServer/tests/rlsPermissionMatrix.integration.test.ts
    React QueryJest + @testing-libraryHook state, cache, error handlingSparkyFitnessFrontend/src/tests/hooks/*.test.tsx
    ComponentJest + @testing-libraryUI rendering and user interactionsSparkyFitnessFrontend/src/tests/components/
    MobileJest (jest-expo)API calls and state updatesSparkyFitnessMobile/__tests__/services/

    Important Note on Frameworks:

    • Server-side uses Vitest. Use vi.* for mocking.
    • Frontend and Mobile use Jest. Use jest.mock and jest.fn (do not use vi.*).
  4. Overview of SparkyFitness Docker Services

    main

    The production Docker Compose setup consists of the following core services:

    • sparkyfitness-db: A PostgreSQL 15 (Alpine) database server. Data is persisted in a Docker volume mapped to ../postgresql on the host.
    • sparkyfitness-server: The Node.js backend application. It depends on sparkyfitness-db and uses environment variables for database connections, logging, API encryption, JWT secrets, and the frontend URL.
    • sparkyfitness-frontend: The React frontend served via Nginx. It maps host port 3004 to container port 80. It depends on sparkyfitness-server.

    Optional Service:

    • sparkyfitness-garmin: A microservice for syncing data from Garmin Connect. This is commented out by default in docker-compose.yml; uncomment the block to enable it.
  5. Overview of SparkyFitness features

    main

    SparkyFitness is a privacy-first, self-hosted fitness tracking platform.

    Core Capabilities:

    • Track nutrition, exercise, hydration, sleep, fasting, mood, and body measurements.
    • Set goals and perform daily check-ins.
    • View interactive charts and long-term reports.
    • Manage multiple user profiles and family access.
    • Support for light/dark themes and secure authentication (OIDC, TOTP, Passkey, MFA).

    Health & Device Integrations: Automatically syncs activity (steps, workouts, sleep) and health metrics (weight, body measurements) from platforms including Apple Health, Google Health Connect/API, Fitbit, Garmin Connect, Withings, Polar Flow, Strava, and various food databases (OpenFoodFacts, USDA, etc.).

    SparkyAI (Beta): A conversational interface that allows users to log food, exercise, and body stats via chat or by uploading food images.

  6. SparkyFitness Core Features

    main

    SparkyFitness provides the following capabilities:

    • Nutrition Tracking: Log meals, create custom foods, and analyze trends.
    • Exercise Logging: Record workouts and browse an exercise database.
    • Body Measurements: Track weight and measurements with progress visualization.
    • AI Nutrition Coach: Chat-based food logging with image recognition support.
    • Goal Setting: Set and track fitness and nutrition goals.
    • Comprehensive Reports: Detailed analytics and progress tracking.
    • Privacy-First: Self-hosted architecture for complete data control.
  7. Compare Cycle Tracking Modes

    main

    The Period & Cycle Hub provides five distinct tracking modes designed for different physiological phases. Use the following summary to determine which mode fits your current needs:

    FeatureStandard (standard)TTC (ttc)Pregnancy (pregnant)Postpartum (Roadmap)Menopause (Roadmap)
    Menstrual FlowYesYesNoLochia OnlyNo
    Cycle PredictionsYesYesNoNoNo
    Fertility/OvulationYesYes (Advanced)NoNoNo
    Symptom MatrixYesYesTrimester-basedRecovery-basedHot flash focus
    Fetal/Labor ToolsNoNoYesNoNo
    Specialized LogsNoNoNoBreastfeeding/KegelsHRT/Hot Flashes
  8. Understand SparkyFitness Health Data Integrations

    main

    SparkyFitness integrates with Apple HealthKit and Google Health Connect to provide fitness insights.

    Data Collection

    With explicit user permission, the App may read the following data from the device's health database:

    • Active Energy Burned
    • Basal Metabolic Rate
    • Steps
    • Workouts

    The App may also write data (such as workout sessions) to these services when using tracking features.

    Data Usage

    • Display: Showing fitness progress and metrics within the App.
    • Analysis: Calculating daily summaries (e.g., Total Calories).
    • Storage: Health data is primarily processed locally on the device.
  9. SparkyFitness Technical Architecture

    main

    The application is built using the following technology stack:

    • Frontend: React 18, TypeScript, Vite, and Tailwind CSS.
    • Backend: Node.js, Express, and PostgreSQL.
    • AI Integration: Multi-provider support including OpenAI, Anthropic, and Google.
    • Deployment: Docker containers (supports both development and production configurations).
    • Security: Implements Row Level Security (RLS), JWT authentication, and encrypted API keys.
  10. Security and Privacy for MCP Server

    main

    The MCP server implements several security layers to protect your health data:

    1. User Isolation (RLS): Tools are restricted by PostgreSQL Row Level Security. The AI can only access data belonging to the user authenticated by the provided API key.
    2. Admin-Only Dev Tools: Debugging tools are off by default. They are only enabled if DEV_TOOLS_ENABLED=true and an admin API key is used. These tools bypass RLS and should only be used for active debugging.
    3. Local First: If running SparkyFitness locally, your data remains on your infrastructure and is only sent to your chosen AI provider (e.g., Anthropic, OpenAI) when you interact with the assistant.
  11. System Prompt for Sparky AI Coach

    main

    The chatbot-full.md file defines the persona and operational logic for Sparky, the AI nutrition and wellness coach. Sparky is designed to track food, exercise, and measurements, providing advice based on user data.

    Key behaviors include:

    • Direct Logging: When users state facts (e.g., "I ate X"), Sparky executes tool calls immediately without asking for permission.
    • Data Retrieval: When asked about goals, calories, or progress, Sparky must use retrieval tools (e.g., sparky_get_goal_snapshot, sparky_get_nutrition_summary) rather than relying on memory.
    • Clarification Logic: Sparky uses sparky_ask_user only when a lookup is ambiguous or requires weight conversions that cannot be safely inferred. Otherwise, it defaults to logging with safe assumptions (e.g., inferring meal type from time of day).