HealthKit data cannot be accessed directly from a web app — it is iOS-native and requires a native iOS app or Shortcut to export data. The integration pattern for Lovable: use an iOS Shortcut or simple Swift app to export health data as JSON, send it to a Supabase Edge Function webhook, store it in your Supabase database, and build a Lovable dashboard that displays the health metrics with charts. This web-compatible workaround lets you visualize Apple Health data without building a full iOS app.
Display Apple HealthKit data in a Lovable web dashboard using iOS Shortcuts
Apple HealthKit stores an enormous amount of personal health data — steps, heart rate, sleep stages, workouts, blood oxygen, calories, nutrition, and dozens of other metrics collected from Apple Watch, iPhone sensors, and connected apps. However, HealthKit is deliberately isolated from the web for privacy reasons: it can only be accessed by native iOS or macOS apps using Apple's HealthKit framework, not by web applications or browsers. This is a fundamental platform restriction, not a configuration issue.
The workaround for displaying HealthKit data in a Lovable web app has two stages. The first stage is iOS-native: you either use the iOS Shortcuts app to create an automated routine that reads specified health metrics and sends them as JSON to a webhook URL, or you build a minimal Swift iOS app that reads HealthKit and forwards the data. The second stage is Lovable-native: the webhook is a Supabase Edge Function that receives the JSON, validates it (using a shared secret to prevent spoofing), stores the metrics in Supabase, and your Lovable React dashboard retrieves and visualizes them.
The iOS Shortcuts approach requires no iOS development skills — the Shortcuts app is pre-installed on every iPhone and uses a visual workflow builder. A Health shortcut can read metrics like step count, resting heart rate, and sleep analysis, convert them to a dictionary, and POST them to a URL. Scheduled automations in Shortcuts make this happen automatically — for example, syncing the previous day's data every morning at 7am without any manual intervention. The result is a Lovable dashboard that stays current with your Apple Health data without requiring a native iOS app.
Integration method
HealthKit is iOS-native and cannot be accessed from a web browser. The integration uses a two-stage pattern: an iOS Shortcut or lightweight Swift app reads HealthKit data and sends it to a Supabase Edge Function webhook as a JSON POST request. The Edge Function validates the request, stores the metrics in Supabase, and the Lovable frontend displays the data as dashboards and charts. The iOS component is a one-time setup; all ongoing data visualization is handled by Lovable.
Prerequisites
- An iPhone or iPad with the Shortcuts app installed (pre-installed on iOS 12+ and all current iPhones)
- Apple Health data recorded on the device (from Apple Watch, manual entries, or connected apps)
- A Lovable account with an active Lovable Cloud project
- A Supabase table to store health metrics (your Edge Function will create the schema via Lovable's AI)
- Basic understanding of iOS Shortcuts' visual workflow builder (no coding required)
Step-by-step guide
Create the Supabase database schema for health metrics
Create the Supabase database schema for health metrics
Before building the iOS Shortcut, set up the Supabase database table that will store health data. The schema needs to accommodate different metric types (steps, heart rate, sleep, workouts) with timestamps and optional user identification for multi-user implementations. Open Lovable's chat and ask the AI to create the health metrics table. Lovable will generate the database migration, create the table in your Supabase project, and add appropriate RLS policies. A flexible health_metrics table uses an EAV (Entity-Attribute-Value) pattern: each row stores one measurement (metric_type, value, unit, recorded_at) rather than a separate column for each metric type. This handles the variety of Apple Health data types without requiring schema changes as you add new metric types. For workouts, which have richer data (type, duration, calories, route), a separate workouts table makes more sense than the EAV pattern. Lovable's AI will create both tables and the appropriate indexes for date-range queries, which are the most common pattern for health dashboards.
Create two Supabase tables for health data storage. First, a 'health_metrics' table with columns: id (uuid primary key), user_id (text, for identifying the device/user), metric_type (text, e.g. 'steps', 'heart_rate', 'sleep_duration'), value (numeric), unit (text, e.g. 'count', 'bpm', 'hours'), recorded_date (date), created_at (timestamptz). Add a unique constraint on (user_id, metric_type, recorded_date). Second, a 'workouts' table with: id, user_id, workout_type (text), duration_minutes (numeric), calories (numeric), start_time (timestamptz), notes (text). Add RLS policies so each user_id can read and write only their own rows. Also add an index on recorded_date for both tables.
Paste this in Lovable chat
Pro tip: The unique constraint on (user_id, metric_type, recorded_date) enables upsert behavior — re-syncing the same day's data updates existing records rather than creating duplicates.
Expected result: The health_metrics and workouts tables are created in Supabase with the correct schema, indexes, and RLS policies. Lovable's database panel shows both tables.
Create a webhook Edge Function to receive health data
Create a webhook Edge Function to receive health data
The Edge Function is the entry point for data from the iOS Shortcut. It receives a POST request containing health metrics as JSON, validates a shared secret to ensure the request comes from your iOS Shortcut (not an outside actor), and upserts the data into Supabase. The validation uses a simple shared secret: a random string you generate once, store in Cloud → Secrets, and also configure in the iOS Shortcut. When the Shortcut sends the request, it includes this secret in a header. The Edge Function verifies it before processing the data. To add the secret, click the '+' icon next to Preview in the Lovable editor, go to Cloud → Secrets, and add: - Name: HEALTHKIT_WEBHOOK_SECRET — Value: a randomly generated string (e.g., a UUID — use any random UUID generator) The Edge Function expects the incoming JSON to follow a specific format that the iOS Shortcut will send: a metrics array with objects containing metric_type, value, unit, and recorded_date, plus a workouts array for workout data. The Step 3 Shortcut will be built to match this format.
Create a Supabase Edge Function at supabase/functions/health-webhook/index.ts that receives POST requests from an iOS Shortcut containing health data. Verify the HEALTHKIT_WEBHOOK_SECRET from the x-webhook-secret header. Accept a JSON body with 'userId' (string), 'metrics' (array of {metric_type, value, unit, recorded_date}), and optional 'workouts' (array of {workout_type, duration_minutes, calories, start_time}). Upsert all metrics into the health_metrics table and insert workouts into the workouts table using Supabase service role key. Return success counts.
Paste this in Lovable chat
1// supabase/functions/health-webhook/index.ts2import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';34const corsHeaders = {5 'Access-Control-Allow-Origin': '*',6 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, x-webhook-secret',7};89Deno.serve(async (req) => {10 if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });1112 // Validate webhook secret13 const incomingSecret = req.headers.get('x-webhook-secret');14 const expectedSecret = Deno.env.get('HEALTHKIT_WEBHOOK_SECRET');1516 if (!incomingSecret || incomingSecret !== expectedSecret) {17 console.error('Invalid webhook secret');18 return new Response(JSON.stringify({ error: 'Unauthorized' }), {19 status: 401,20 headers: { ...corsHeaders, 'Content-Type': 'application/json' },21 });22 }2324 try {25 const { userId, metrics = [], workouts = [] } = await req.json();2627 if (!userId) {28 return new Response(JSON.stringify({ error: 'userId is required' }), {29 status: 400,30 headers: { ...corsHeaders, 'Content-Type': 'application/json' },31 });32 }3334 const supabase = createClient(35 Deno.env.get('SUPABASE_URL')!,36 Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!37 );3839 let metricsUpserted = 0;40 let workoutsInserted = 0;4142 if (metrics.length > 0) {43 const metricsToUpsert = metrics.map((m: Record<string, unknown>) => ({44 user_id: userId,45 metric_type: m.metric_type,46 value: m.value,47 unit: m.unit,48 recorded_date: m.recorded_date,49 }));5051 const { error } = await supabase52 .from('health_metrics')53 .upsert(metricsToUpsert, { onConflict: 'user_id,metric_type,recorded_date' });5455 if (error) throw error;56 metricsUpserted = metrics.length;57 }5859 if (workouts.length > 0) {60 const workoutsToInsert = workouts.map((w: Record<string, unknown>) => ({61 user_id: userId,62 ...w,63 }));6465 const { error } = await supabase.from('workouts').insert(workoutsToInsert);66 if (error) console.warn('Workout insert warning:', error);67 workoutsInserted = workouts.length;68 }6970 return new Response(JSON.stringify({ success: true, metricsUpserted, workoutsInserted }), {71 headers: { ...corsHeaders, 'Content-Type': 'application/json' },72 });73 } catch (error) {74 console.error('Health webhook error:', error);75 return new Response(JSON.stringify({ error: String(error) }), {76 status: 500,77 headers: { ...corsHeaders, 'Content-Type': 'application/json' },78 });79 }80});Pro tip: The HEALTHKIT_WEBHOOK_SECRET must be kept secure and configured identically in both Cloud → Secrets and your iOS Shortcut. If the secret ever leaks, regenerate it in both places.
Expected result: The health-webhook Edge Function is deployed. Requests without the correct webhook secret are rejected with 401. Valid requests with health data are upserted into the health_metrics table.
Build the iOS Shortcut to export Apple Health data
Build the iOS Shortcut to export Apple Health data
Now build the iOS Shortcut that reads Apple Health data and sends it to your Edge Function webhook. Open the Shortcuts app on your iPhone. Tap the '+' button to create a new shortcut. Name it 'Sync Health Data to Lovable'. Before building the shortcut, you need two things: 1. Your Edge Function webhook URL — in Lovable, click '+' → Cloud → Edge Functions, find health-webhook, and copy the URL. It looks like https://your-project-ref.supabase.co/functions/v1/health-webhook. 2. Your HEALTHKIT_WEBHOOK_SECRET value — copy it from Cloud → Secrets. In the Shortcut builder, add the following actions in order: 1. 'Get Health Sample' action: set metric to 'Step Count', timeframe to 'Yesterday', aggregation to 'Sum'. Save as 'Steps Variable'. 2. 'Get Health Sample' action: metric to 'Resting Heart Rate', yesterday, aggregation to 'Average'. Save as 'HeartRate Variable'. 3. 'Get Health Sample' action: metric to 'Sleep Analysis', yesterday, aggregation to 'Sum of Values'. Save as 'Sleep Variable'. 4. 'Get Current Date' action — format as YYYY-MM-DD. Save as 'Yesterday' (use 'Add Time' with -1 day). 5. 'Dictionary' action: create a dictionary with keys userId (a unique identifier for your device, like your name or email), metrics (an array), and add each metric as a dictionary with metric_type, value, unit, and recorded_date keys. 6. 'Get Contents of URL' action: URL = your Edge Function URL, Method = POST, Headers = Content-Type: application/json and x-webhook-secret: YOUR_SECRET, Body = the dictionary from step 5. For the automated daily sync, go to Automation tab → Create Personal Automation → Time of Day → 7:00 AM → Daily, then add 'Run Shortcut' and select your Sync shortcut. This runs the sync automatically every morning.
Pro tip: Test the Shortcut manually first by tapping Run before setting up the automation. Check Cloud → Logs in Lovable to see the incoming request and confirm the data is being stored in Supabase.
Expected result: The iOS Shortcut runs successfully and sends health data to the Edge Function webhook. Cloud → Logs shows a 200 response. The health_metrics table in Supabase contains rows with yesterday's step count, heart rate, and sleep data.
Build the health metrics dashboard in Lovable
Build the health metrics dashboard in Lovable
With health data flowing into Supabase from the iOS Shortcut, build the dashboard that visualizes it. Open Lovable's chat and describe the charts and metrics you want to display. Lovable will generate React components using Recharts (which shadcn/ui's chart components are built on) and wire them to Supabase queries. The dashboard should query the health_metrics table with date range filters, transform the rows into the format Recharts expects (arrays of objects with date and value keys), and render line charts for trend data and bar charts for daily comparisons. For a personal health dashboard, a typical layout includes: - A date range selector (Last 7 days / Last 30 days / Last 90 days) - Step count line chart with a goal line at 10,000 steps/day - Resting heart rate line chart with normal range (60-100 bpm) shaded - Sleep duration bar chart with 8-hour goal line - Recent workouts list with type icons, duration, and calories Lovable's AI can generate all of these charts from a single descriptive prompt. Describe the visual design and the data source, and Lovable will handle the Supabase query, data transformation, and chart configuration.
Build a health dashboard page that queries the health_metrics and workouts tables in Supabase for the current user. Add a 7/30/90 day toggle that changes the query date range. Create three charts using shadcn/ui chart components: (1) a line chart of daily step counts with a dashed goal line at 10,000, (2) a line chart of resting heart rate in bpm, (3) a bar chart of sleep duration in hours. Below the charts, show a list of recent workouts with workout_type, duration_minutes, calories, and formatted start_time. If there is no data yet, show an empty state with instructions for setting up the iOS Shortcut.
Paste this in Lovable chat
Pro tip: Add an 'empty state' component that shows when the health_metrics table has no data for the current user. Include the Edge Function webhook URL and a simplified Shortcut setup guide so users can get started without leaving the app.
Expected result: The health dashboard displays charts populated with real Apple Health data synced from the iOS Shortcut. The date range toggle updates all charts simultaneously. The workouts list shows recent activities with correct metrics.
Set up automatic daily sync and handle edge cases
Set up automatic daily sync and handle edge cases
The daily automation in iOS Shortcuts ensures health data stays current without manual intervention. To complete the setup, configure the Shortcut automation as described in Step 3 and then test the edge cases that commonly cause syncing to break. Common edge cases to handle: Missing days: if the iPhone is off or the automation fails to run, a gap appears in the dashboard. Add a 'Sync last 7 days' button in the Lovable dashboard that triggers the iOS Shortcut manually for a date range. Alternatively, modify the Shortcut to send data for the last 3 days instead of just yesterday, relying on the unique constraint upsert behavior to avoid duplicates. Data availability: Apple Health does not always have data for every metric every day. Some metrics like resting heart rate require Apple Watch and only appear if the watch was worn. Add null checks in your dashboard components so missing data appears as empty chart segments rather than errors. Multiple devices: if a household has multiple iPhones, each device needs its own userId in the Shortcut configuration to avoid overwriting each other's data. The Lovable dashboard can then support user switching or display multiple users' data simultaneously for fitness coach use cases. For a robust production setup handling multiple users' health data, consider adding authentication to the webhook using Supabase JWT tokens from each user's Lovable login session, replacing the simple shared secret approach. This gives each user their own secure channel.
Add a 'Sync History' section to the health dashboard showing when data was last received for each metric type. Display a 'Last sync' timestamp and a badge showing how many days of data are available. If any metric has not synced in more than 48 hours, show a yellow warning badge with a message saying 'Check your iOS Shortcut automation'. Add a manual refresh button that re-fetches from Supabase without triggering the iOS Shortcut.
Paste this in Lovable chat
Pro tip: Store a sync_log table in Supabase with the timestamp of each successful webhook call. Query this in the dashboard to show sync health and catch automation failures early.
Expected result: The daily automation runs at the configured time and syncs health data without manual intervention. The dashboard's last sync timestamp updates each morning. Missing data is handled gracefully with empty state indicators rather than errors.
Common use cases
Personal health metrics dashboard
Build a personal web dashboard that displays your weekly step counts, resting heart rate trends, sleep duration, and workout history as interactive charts. The dashboard updates automatically each morning when your iOS Shortcut syncs the previous day's data. This gives you a custom view of your health data beyond what the Apple Health app natively provides — you design the charts, time ranges, and metrics that matter to you.
Build a personal health dashboard page that fetches data from the health_metrics table in Supabase. Display: a line chart of daily step counts for the last 30 days, a line chart of resting heart rate for the last 30 days, a bar chart of sleep duration for the last 14 nights, and a list of recent workouts with type, duration, and calories burned. Add date range selectors above each chart. Use shadcn/ui chart components for the visualizations.
Copy this prompt to try it in Lovable
Fitness coach progress tracking tool
A fitness coach can ask clients to set up the iOS Shortcut to sync their health data to a shared Lovable dashboard. The coach's view shows all clients' step counts, workout frequency, and heart rate trends on a single page, enabling remote coaching without each client needing to manually report their activity. Supabase RLS policies ensure each client can only see their own data while the coach can see everyone's.
Build a fitness coach dashboard where each client has their data in a separate panel. The coach can see all clients' weekly step averages, workout completion rates, and resting heart rate trends. Add a comparison view that shows all clients' step counts on the same chart with different colored lines. Clients should only see their own data when they log in; the coach sees everyone's.
Copy this prompt to try it in Lovable
Clinical research data collection
Research studies that need continuous health metric collection from participants can use this pattern. Participants set up the iOS Shortcut to sync daily health data automatically. The Lovable app provides the study dashboard where researchers review aggregate trends, flag outliers, and monitor data collection completeness without processing manual exports.
Build a research dashboard that shows data collection statistics for each study participant: last sync time, number of days with complete step data, average daily steps for the study period, and any days with missing data highlighted. Allow researchers to download a participant's complete dataset as CSV. Use participant IDs instead of names for privacy. Add alerts when a participant has not synced in more than 48 hours.
Copy this prompt to try it in Lovable
Troubleshooting
iOS Shortcut runs without errors but no data appears in the Supabase health_metrics table
Cause: The Shortcut may be sending to the wrong URL, the webhook secret does not match, or the request body format does not match what the Edge Function expects. The Shortcut succeeds from its perspective (it gets a response) but the Edge Function returns an error that the Shortcut ignores.
Solution: In Cloud → Logs, look for incoming requests to the health-webhook function. If no logs appear, the URL in the Shortcut is wrong — verify you copied the correct Edge Function URL from Cloud → Edge Functions in Lovable. If logs show a 401 error, the x-webhook-secret header value in the Shortcut does not match HEALTHKIT_WEBHOOK_SECRET in Cloud → Secrets — update the Shortcut to use the exact secret value.
Health data appears in Supabase but charts in the Lovable dashboard show no data or empty state
Cause: The Supabase query in the frontend is filtering by the wrong user_id, or the date range filter is excluding the dates that have data, or the metric_type string in the stored data does not match what the chart component expects (e.g., 'Step Count' stored but querying for 'steps').
Solution: Open Lovable's database panel (Cloud → Database) and look directly at the health_metrics table to see what user_id and metric_type values are actually stored. Compare these to the values your dashboard query uses. Update either the Shortcut (to use the expected metric_type strings) or the dashboard query (to match the strings the Shortcut sends).
iOS Shortcuts automation runs but Apple Health returns no data for some metrics
Cause: Some Apple Health metrics require specific hardware or app setup. Resting heart rate requires an Apple Watch worn overnight. Sleep analysis requires either Apple Watch sleep tracking or a third-party sleep tracking app. Step count requires an iPhone in pocket or Apple Watch. If the data source was not active, HealthKit returns empty or zero values.
Solution: Add a null/zero check in the Shortcut before including a metric in the JSON payload. If a 'Get Health Sample' action returns empty or 0 for a metric, skip including it in the metrics array. In the Edge Function, add validation to skip metrics with null or zero values. In the dashboard, show a 'No data available' indicator for metrics with no recorded values rather than a chart with a flat zero line.
The iOS Shortcut shows a 'Shortcut stopped' error when it tries to send data
Cause: iOS blocks the Shortcut from running background network requests to URLs it does not recognize as trusted, or the request is being rejected by iOS privacy settings that prevent Shortcuts from accessing specific health categories without explicit user permission.
Solution: Ensure the Shortcut has been granted permission to access each health category. When you add a 'Get Health Sample' action for a new metric type the first time, iOS prompts for permission. If you dismissed that prompt, go to Settings → Privacy → Health → Shortcuts and verify all required categories are enabled. For the network request, ensure the Edge Function URL is HTTPS — iOS Shortcuts blocks HTTP URLs.
Best practices
- Generate a cryptographically random webhook secret (like a UUID or a 32-character random hex string) for HEALTHKIT_WEBHOOK_SECRET — health data is sensitive personal information and the webhook must not be accessible without authentication.
- Use the upsert pattern with a unique constraint on (user_id, metric_type, recorded_date) so re-running the Shortcut for the same day updates rather than duplicates records — this makes recovery from failed syncs simple.
- Store the received metric values exactly as Apple Health reports them and handle unit conversion in the frontend rather than in the Edge Function — this preserves the original precision and makes it easier to display different unit systems (metric vs. imperial) per user preference.
- Never assume all health metrics will be available on every sync day — some metrics require specific hardware (Apple Watch) and some may simply not have been measured. Always write defensive chart components that handle missing or null data gracefully.
- For multi-user health apps, switch from the shared webhook secret approach to per-user Supabase JWT authentication in the webhook Edge Function — this ensures users can only write data to their own rows and cannot overwrite other users' health data.
- Inform users clearly that health data is being sent over the internet to Supabase and add a privacy policy explaining how the data is stored and used — health information is sensitive and users deserve transparency about where their HealthKit data goes.
- Test your iOS Shortcut on the day it is built and then check back after 24 hours of automated daily syncing — automation timing on iOS can shift based on low power mode, Focus modes, and background app refresh settings that users may change.
Alternatives
Choose Fitbit API if your users have Fitbit devices — the Fitbit API is web-accessible via OAuth 2.0 and does not require the iOS Shortcut workaround, making it a direct REST integration with Lovable Edge Functions.
Choose Garmin Connect if your users are athletes with Garmin devices — Garmin offers a Health API with webhook support that sends activity data directly to your Edge Function without any iOS Shortcut setup.
Choose Google Fit if your users are on Android — Google Fit's REST API is directly accessible from web apps and Edge Functions via OAuth 2.0, unlike HealthKit which requires the iOS Shortcut workaround.
Frequently asked questions
Why can't a Lovable web app access HealthKit directly from the browser?
Apple designed HealthKit as an iOS/macOS framework for security and privacy reasons — it is only accessible by apps that have been explicitly granted HealthKit entitlements through Apple's developer program and reviewed by Apple. Web browsers running in Safari or any browser on iOS cannot access HealthKit because they do not have the app-level HealthKit permission. This is a deliberate architectural decision by Apple, not a limitation of Lovable. The iOS Shortcut workaround works because Shortcuts is a native iOS app with the HealthKit entitlement that Apple has granted.
Is the iOS Shortcuts approach reliable enough for daily health tracking?
iOS Shortcuts automations are reasonably reliable but not guaranteed. iOS may delay or skip automations when the device is in Low Power Mode, when an iPhone has not been unlocked recently, when Focus modes are active, or when background app refresh is disabled. For personal use, missed occasional syncs are acceptable. For clinical or research use cases requiring reliable data collection, consider building a minimal Swift iOS app with HealthKit background delivery, which Apple designed specifically for reliable background health data collection.
Can multiple family members or users share one Lovable health dashboard?
Yes. Each person sets up their own iOS Shortcut with their own unique userId string (a name, email, or any identifier you choose). The health_metrics table stores data for all users, differentiated by user_id. The Lovable dashboard can show a user selector to switch between family members' data, or each user can log in to the Lovable app with their own Supabase Auth account and see only their own data (enforced by RLS policies keyed to their Supabase user ID). Map Supabase user IDs to the userId strings in the Shortcut using a profile table.
What Apple Health metrics can the iOS Shortcut access?
The Shortcuts app can read most common health metrics through its 'Get Health Sample' action, including step count, resting heart rate, active energy burned, sleep analysis, workout minutes, heart rate variability, blood oxygen, respiratory rate, mindful minutes, and dietary data. Some clinical-grade metrics like blood glucose require a connected device (like a Dexcom CGM) that has written that data to HealthKit. Complex metrics like VO2 max are calculated by Apple and available as read-only HealthKit quantities. The Shortcuts app's health actions include approximately 40+ metric types.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation