HealthKit is iOS only. Always gate calls behind an
isDespiaIOS check so your app degrades gracefully in a browser or on Android.Installation
- Bundle
- CDN
Choosing the right approach
HealthKit data can be accessed in three ways. Which one to use depends on whether you need data right now, want to save data, or need to react to changes continuously.| Approach | Use when | How it works |
|---|---|---|
| Read | You need historical data at a specific moment - on page load, on a button tap, or when building a report | Call readhealthkit:// and await the result. Returns records for the last N days. |
| Write | You want to save a value back to HealthKit - for example, logging a weight entry or a step count from your own sensor | Call writehealthkit:// with a value. Adds a new sample without replacing existing data. |
| Observer | You need your server to stay in sync with the user’s health data automatically, without requiring the user to open the app | Register a webhook with healthkit://observe. Despia posts new data to your server whenever HealthKit updates, even in the background. |
How it works
Define theisDespiaIOS check once at the top of your app and reuse it throughout. Despia requests HealthKit permission on the first call for each identifier, then fetches and returns the data.
Read
Usereadhealthkit:// to fetch historical data on demand. This is the right approach when your UI needs to display health data at a point in time - on load, after a user action, or when generating a report. You control exactly when the fetch happens and how many days of history to retrieve.
Pass any valid HKQuantityTypeIdentifier, HKCategoryTypeIdentifier, HKWorkoutTypeIdentifier, or HKCharacteristicTypeIdentifier as the URL host, plus an optional days parameter. See Identifier reference for the full list.
Quantity types
Quantity types cover numeric metrics: steps, heart rate, distance, body mass, calories, and more. Each record represents one day’s value for the requested identifier.Start of day in ISO 8601 format
The health metric value for that day
Unit of measurement, e.g.
count, count/min, kg, m. Determined automatically by the identifier.Sleep data
Sleep analysis usesHKCategoryTypeIdentifierSleepAnalysis. Unlike quantity types, sleep returns individual stage intervals rather than daily aggregates - each record covers a contiguous block of one sleep stage with its own start and end time.
ISO 8601 start time of the sleep stage interval
ISO 8601 end time of the sleep stage interval
Raw integer from
HKCategoryValueSleepAnalysisHuman-readable stage:
inBed, awake, asleep, core, deep, or remWorkouts
UseHKWorkoutTypeIdentifier to fetch workout sessions. Each record includes the activity type, duration, calories burned, and distance where applicable.
ISO 8601 start time of the workout
Activity name such as
running, hiit, or yogaDuration in seconds
Kilocalories burned
Distance in meters.
0 if not applicable for the activity typePrimary metric: distance if available, calories if not, otherwise duration
Unit of
value: m, kcal, or sSupported activityType values
Supported activityType values
| Value | Value | Value |
|---|---|---|
americanFootball | archery | australianFootball |
badminton | baseball | basketball |
barre | bowling | boxing |
climbing | coreTraining | cricket |
crossCountrySkiing | crossTraining | curling |
cycling | dance | downhillSkiing |
elliptical | equestrianSports | fencing |
fishing | flexibility | fitnessGaming |
functionalStrengthTraining | golf | gymnastics |
handball | hiit | hiking |
hockey | hunting | jumpRope |
kickboxing | lacrosse | martialArts |
mindAndBody | mixedCardio | paddleSports |
pilates | play | preparationAndRecovery |
racquetball | rowing | rugby |
running | sailing | skatingSports |
snowSports | snowboarding | soccer |
softball | squash | stairClimbing |
stairs | stepTraining | surfingSports |
swimming | tableTennis | taiChi |
tennis | trackAndField | traditionalStrengthTraining |
volleyball | walking | waterFitness |
waterPolo | waterSports | wheelchairWalkPace |
wheelchairRunPace | wrestling | yoga |
other |
Characteristics
Characteristics such as date of birth, biological sex, and blood type are static values that do not change over time. They return a plain string or raw integer and do not accept adays parameter.
| Identifier | Returns |
|---|---|
HKCharacteristicTypeIdentifierDateOfBirth | ISO 8601 date string |
HKCharacteristicTypeIdentifierBiologicalSex | Raw integer from HKBiologicalSex |
HKCharacteristicTypeIdentifierBloodType | Raw integer from HKBloodType |
HKCharacteristicTypeIdentifierFitzpatrickSkinType | Raw integer from HKFitzpatrickSkinType |
Write
Usewritehealthkit:// to save a value back to HealthKit. This is useful when your app collects health data that should also live in Apple Health - for example, a weight logging form, a manual step entry, or a calorie tracker. Writing adds a new sample to HealthKit without removing or replacing any existing records.
The URL format is writehealthkit://IdentifierString//Value. The unit is resolved automatically from the identifier.
Any writable
HKQuantityTypeIdentifier, passed as the URL host (e.g. HKQuantityTypeIdentifierBodyMass)Numeric value to write. The unit is determined automatically from the identifier - see the Identifier reference.
Write is one-directional. It adds samples to HealthKit but does not delete or modify existing ones. If you need to correct a previously written value, write a new sample - HealthKit stores the history and surfaces the most recent reading.
Observer
Use observers when you need your server to stay current with a user’s health data automatically, without requiring the user to open your app. Observers register a background listener on the device that watches one or more HealthKit types. When new data arrives - from Apple Watch, a connected sensor, or another app - Despia posts a webhook to your server with the latest records. This is fundamentally different from read. Read is a point-in-time fetch that your code initiates. An observer is a persistent subscription that fires on Despia’s side whenever HealthKit tells it something changed. The user does not need to be in the app for a webhook to fire. Common uses for observers include: tracking whether a user hit a daily step goal, alerting a coach when a client logs a workout, syncing sleep data nightly to a backend, and triggering push notifications based on health events.Registering an observer
Comma-separated list of HealthKit identifiers to observe
How often Despia delivers batched updates to your server:
immediate, hourly, daily, or weekly. Defaults to immediate. Use hourly or daily for high-volume types like steps to avoid unnecessary webhook traffic.Full URL of the endpoint that receives webhook POSTs. Append your own query parameters here to identify the user on your server.
Identifying users in webhooks
Webhooks include auserId field containing the Despia device ID. If you need to map webhook events to your own user records, append your user identifier as a query parameter on the server URL when registering the observer. Your server receives it as part of the request URL.
POST /webhook?user=user_abc123 and can route the event directly to the right user record without any device ID mapping.
Webhook payload
Despia sends aPOST with Content-Type: application/json each time an observed type updates. The data object contains one key per observed type, each holding an array of the most recent records (last 1 day).
Always
updateDespia device ID, consistent across all events from the same device. For your own user IDs, use a query parameter on the
server URL instead.ISO 8601 timestamp of when the webhook was sent
One key per observed type, each containing an array of records matching the read response shape for that type
Checking active observers
despia.observingHealthKit holds an array of currently active identifier strings. It is undefined before any observe or unobserve call has been made, and [] once all observers have been stopped. Use this to check whether an observer is already registered before calling observe again.
Stopping observers
Passall to stop every active observer, or a comma-separated list of identifiers to stop specific types. The response contains the updated list of remaining active observers.
Identifier reference
Despia supports all four HealthKit identifier categories. Pass any valid identifier string directly toreadhealthkit:// or writehealthkit:// - Despia resolves the type and unit automatically.
Constructing identifiers
Every identifier follows a predictable pattern based on its category:| Type | Prefix | Example |
|---|---|---|
| Quantity | HKQuantityTypeIdentifier | HKQuantityTypeIdentifierStepCount |
| Category | HKCategoryTypeIdentifier | HKCategoryTypeIdentifierSleepAnalysis |
| Workout | HKWorkoutTypeIdentifier | HKWorkoutTypeIdentifier |
| Characteristic | HKCharacteristicTypeIdentifier | HKCharacteristicTypeIdentifierDateOfBirth |
StepCount under HKQuantityTypeIdentifier - the full identifier string is HKQuantityTypeIdentifierStepCount.
Apple Documentation
HKQuantityTypeIdentifier
Steps, heart rate, distance, body mass, nutrition, and all other numeric types
HKCategoryTypeIdentifier
Sleep analysis, mindfulness, and other category-based types
HKWorkoutActivityType
All workout activity types returned in the
activityType fieldHKCharacteristicTypeIdentifier
Date of birth, biological sex, blood type, and skin type
Resources
NPM Package
despia-native