@chrisprobably/capacitor-health
v7.0.19
Published
Capacitor plugin to interact with data from Apple HealthKit and Health Connect
Readme
@capgo/capacitor-health
Capacitor plugin to read and write health metrics via Apple HealthKit (iOS) and Health Connect (Android). The TypeScript API keeps the same data types and units across platforms so you can build once and deploy everywhere.
Install
npm install @capgo/capacitor-health
npx cap synciOS Setup
- Open your Capacitor application's Xcode workspace and enable the HealthKit capability.
- Provide usage descriptions in
Info.plist(update the copy for your product):
<key>NSHealthShareUsageDescription</key>
<string>This app reads your health data to personalise your experience.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>This app writes new health entries that you explicitly create.</string>Android Setup
This plugin now uses Health Connect instead of Google Fit. Make sure your app meets the requirements below:
- Min SDK 26+. Health Connect is only available on Android 8.0 (API 26) and above. The plugin’s Gradle setup already targets this level.
- Declare Health permissions. The plugin manifest ships with the required
<uses-permission>declarations (READ_/WRITE_STEPS,READ_/WRITE_DISTANCE,READ_/WRITE_ACTIVE_CALORIES_BURNED,READ_/WRITE_HEART_RATE,READ_/WRITE_WEIGHT). Your app does not need to duplicate them, but you must surface a user-facing rationale because the permissions are considered health sensitive. - Ensure Health Connect is installed. Devices on Android 14+ include it by default. For earlier versions the user must install Health Connect by Android from the Play Store. The
Health.isAvailable()helper exposes the current status so you can prompt accordingly. - Request runtime access. The plugin opens the Health Connect permission UI when you call
requestAuthorization. You should still handle denial flows (e.g., show a message ifcheckAuthorizationreports missing scopes).
If you already used Google Fit in your project you can remove the associated dependencies (play-services-fitness, play-services-auth, OAuth configuration, etc.).
Usage
import { Health } from '@capgo/capacitor-health';
// Verify that the native health SDK is present on this device
const availability = await Health.isAvailable();
if (!availability.available) {
console.warn('Health access unavailable:', availability.reason);
}
// Ask for separate read/write access scopes
await Health.requestAuthorization({
read: ['steps', 'heartRate', 'weight'],
write: ['weight'],
});
// Query the last 50 step samples from the past 24 hours
const { samples } = await Health.readSamples({
dataType: 'steps',
startDate: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
endDate: new Date().toISOString(),
limit: 50,
});
// Persist a new body-weight entry (kilograms by default)
await Health.saveSample({
dataType: 'weight',
value: 74.3,
});Supported data types
| Identifier | Default unit | Notes |
| ---------- | ------------- | ----- |
| steps | count | Step count deltas |
| distance | meter | Walking / running distance |
| calories | kilocalorie | Active energy burned |
| heartRate| bpm | Beats per minute |
| weight | kilogram | Body mass |
All write operations expect the default unit shown above. On Android the metadata option is currently ignored by Health Connect.
API
isAvailable()requestAuthorization(...)checkAuthorization(...)readSamples(...)saveSample(...)startObservingHRV()- Interfaces
- Type Aliases
isAvailable()
isAvailable() => Promise<AvailabilityResult>Returns whether the current platform supports the native health SDK.
Returns: Promise<AvailabilityResult>
requestAuthorization(...)
requestAuthorization(options: AuthorizationOptions) => Promise<AuthorizationStatus>Requests read/write access to the provided data types.
| Param | Type |
| ------------- | --------------------------------------------------------------------- |
| options | AuthorizationOptions |
Returns: Promise<AuthorizationStatus>
checkAuthorization(...)
checkAuthorization(options: AuthorizationOptions) => Promise<AuthorizationStatus>Checks authorization status for the provided data types without prompting the user.
| Param | Type |
| ------------- | --------------------------------------------------------------------- |
| options | AuthorizationOptions |
Returns: Promise<AuthorizationStatus>
readSamples(...)
readSamples(options: QueryOptions) => Promise<ReadSamplesResult>Reads samples for the given data type within the specified time frame.
| Param | Type |
| ------------- | ----------------------------------------------------- |
| options | QueryOptions |
Returns: Promise<ReadSamplesResult>
saveSample(...)
saveSample(options: WriteSampleOptions) => Promise<void>Writes a single sample to the native health store.
| Param | Type |
| ------------- | ----------------------------------------------------------------- |
| options | WriteSampleOptions |
startObservingHRV()
startObservingHRV() => Promise<void>Interfaces
AvailabilityResult
| Prop | Type | Description |
| --------------- | ---------------------------------------- | ------------------------------------------------------ |
| available | boolean | |
| platform | 'ios' | 'android' | 'web' | Platform specific details (for debugging/diagnostics). |
| reason | string | |
AuthorizationStatus
| Prop | Type |
| --------------------- | ----------------------------- |
| readAuthorized | HealthDataType[] |
| readDenied | HealthDataType[] |
| writeAuthorized | HealthDataType[] |
| writeDenied | HealthDataType[] |
AuthorizationOptions
| Prop | Type | Description |
| ----------- | ----------------------------- | ------------------------------------------------------- |
| read | HealthDataType[] | Data types that should be readable after authorization. |
| write | HealthDataType[] | Data types that should be writable after authorization. |
ReadSamplesResult
| Prop | Type |
| ------------- | --------------------------- |
| samples | HealthSample[] |
HealthSample
| Prop | Type |
| ---------------- | --------------------------------------------------------- |
| dataType | HealthDataType |
| value | number |
| unit | HealthUnit |
| startDate | string |
| endDate | string |
| sourceName | string |
| sourceId | string |
QueryOptions
| Prop | Type | Description |
| --------------- | --------------------------------------------------------- | ------------------------------------------------------------------ |
| dataType | HealthDataType | The type of data to retrieve from the health store. |
| startDate | string | Inclusive ISO 8601 start date (defaults to now - 1 day). |
| endDate | string | Exclusive ISO 8601 end date (defaults to now). |
| limit | number | Maximum number of samples to return (defaults to 100). |
| ascending | boolean | Return results sorted ascending by start date (defaults to false). |
WriteSampleOptions
| Prop | Type | Description |
| --------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| dataType | HealthDataType | |
| value | number | |
| unit | HealthUnit | Optional unit override. If omitted, the default unit for the data type is used (count for steps, meter for distance, kilocalorie for calories, bpm for heartRate, kilogram for weight). |
| startDate | string | ISO 8601 start date for the sample. Defaults to now. |
| endDate | string | ISO 8601 end date for the sample. Defaults to startDate. |
| metadata | Record<string, string> | Metadata key-value pairs forwarded to the native APIs where supported. |
Type Aliases
HealthDataType
'steps' | 'distance' | 'calories' | 'heartRate' | 'weight' | 'sleepAnalysis' | 'hrv'
HealthUnit
'count' | 'meter' | 'kilocalorie' | 'bpm' | 'kilogram' | 'sleepCategory' | 'ms'
Record
Construct a type with a set of properties K of type T
{ [P in K]: T; }
Credits:
this plugin was inspired by the work of https://github.com/perfood/capacitor-healthkit/ for ios and https://github.com/perfood/capacitor-google-fit for Android
