{"id":18831422,"url":"https://github.com/kingstinct/react-native-healthkit","last_synced_at":"2025-12-16T12:39:45.406Z","repository":{"id":37896047,"uuid":"275260119","full_name":"kingstinct/react-native-healthkit","owner":"kingstinct","description":"HealthKit bindings for React Native with TypeScript","archived":false,"fork":false,"pushed_at":"2024-09-20T08:11:56.000Z","size":29342,"stargazers_count":236,"open_issues_count":18,"forks_count":47,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-10-29T21:45:01.961Z","etag":null,"topics":["healthkit","ios","react-hooks","reactnative","typescript"],"latest_commit_sha":null,"homepage":"https://kingstinct.com/react-native-healthkit/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kingstinct.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["robertherber","kingstinct"]}},"created_at":"2020-06-26T22:40:28.000Z","updated_at":"2024-10-26T21:41:16.000Z","dependencies_parsed_at":"2023-02-01T06:30:56.489Z","dependency_job_id":"1feee3f2-982b-4300-bf79-44bac23bff97","html_url":"https://github.com/kingstinct/react-native-healthkit","commit_stats":{"total_commits":176,"total_committers":14,"mean_commits":"12.571428571428571","dds":"0.19318181818181823","last_synced_commit":"9ded779461c812581398372109fcba671bc226b3"},"previous_names":[],"tags_count":47,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingstinct%2Freact-native-healthkit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingstinct%2Freact-native-healthkit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingstinct%2Freact-native-healthkit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingstinct%2Freact-native-healthkit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kingstinct","download_url":"https://codeload.github.com/kingstinct/react-native-healthkit/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247574089,"owners_count":20960496,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["healthkit","ios","react-hooks","reactnative","typescript"],"created_at":"2024-11-08T01:54:10.893Z","updated_at":"2025-12-16T12:39:45.400Z","avatar_url":"https://github.com/kingstinct.png","language":"TypeScript","funding_links":["https://github.com/sponsors/robertherber","https://github.com/sponsors/kingstinct","https://github.com/sponsors/Kingstinct"],"categories":["Javascript"],"sub_categories":[],"readme":"# @kingstinct/react-native-healthkit\n\n[![Test Status](https://github.com/Kingstinct/react-native-healthkit/actions/workflows/test.yml/badge.svg)](https://github.com/Kingstinct/react-native-healthkit/actions/workflows/test.yml)\n[![Latest version on NPM](https://img.shields.io/npm/v/@kingstinct/react-native-healthkit)](https://www.npmjs.com/package/@kingstinct/react-native-healthkit)\n[![Downloads on NPM](https://img.shields.io/npm/dt/@kingstinct/react-native-healthkit)](https://www.npmjs.com/package/@kingstinct/react-native-healthkit)\n[![Discord](https://dcbadge.limes.pink/api/server/hrgnETpsJA?style=flat)](https://discord.gg/hrgnETpsJA)\n\n\nReact Native bindings for HealthKit with full TypeScript and Promise support covering about any kind of data. Keeping TypeScript mappings as close as possible to HealthKit - both in regards to naming and serialization. This will make it easier to keep this library up-to-date with HealthKit as well as browsing [the official documentation](https://developer.apple.com/documentation/healthkit) (and if something - metadata properties for example - is not typed it will still be accessible).\n\n| Data Types                  | Query | Save  | Subscribe | Examples                               |\n| ----------------------------|:------|:------|:----------|:---------------------------------------|\n| 100+ Quantity Types         | ✅    | ✅    | ✅       | Steps, energy burnt, blood glucose etc.. |\n| 63 Category Types           | ✅    | ✅    | ✅       | Sleep analysis, mindful sessions etc.. |\n| 75+ Workout Activity Types  | ✅    | ✅    | ✅       | Swimming, running, table tennis etc..  |\n| Correlation Types           | ✅    | ✅    | ✅       | Food and blood pressure                |\n| Document Types              | ✅    | ❌    | ✅       | [CDA documents](https://developer.apple.com/documentation/healthkit/hkcdadocument) exposed as Base64 data  |\n| Clinical Records            | ⚠️    | ❌    | ⚠️       | Lab results etc in [FHIR JSON format](https://www.hl7.org/fhir/json.html) (see [Clinical Records](https://github.com/kingstinct/react-native-healthkit#clinical-records))  |\n\n### Disclaimer\n\nThis library is provided as-is without any warranty and is not affiliated with Apple in any way. The data might be incomplete or inaccurate.\n\n## Installation\n\n### Expo\nUsage with Expo is possible - just keep in mind it will not work in Expo Go and [you'll need to roll your own Dev Client](https://docs.expo.dev/development/getting-started/). \n\n1. `yarn add @kingstinct/react-native-healthkit react-native-nitro-modules`\n2. Update your app.json with the config plugin:\n```json\n{\n  \"expo\": {\n    \"plugins\": [\"@kingstinct/react-native-healthkit\"]\n  }\n}\n```\nthis will give you defaults that make the app build without any further configuration. If you want, you can override the defaults:\n```json\n{\n  \"expo\": {\n    \"plugins\": [\n      [\"@kingstinct/react-native-healthkit\", {\n        \"NSHealthShareUsageDescription\": \"Your own custom usage description\",\n        \"NSHealthUpdateUsageDescription\": \"Your own custom usage description\",\n        \"background\": true\n      }]\n    ]\n  }\n}\n```\n3. Build a new Dev Client\n\n### Native or Expo Bare Workflow\n1. `yarn add @kingstinct/react-native-healthkit react-native-nitro-modules`\n2. `npx pod-install`\n3. Set `NSHealthUpdateUsageDescription` and `NSHealthShareUsageDescription` in your `Info.plist` \n4. Enable the HealthKit capability for the project in Xcode.\n5. Since this package is using Swift you might also need to add a bridging header in your project if you haven't already, you can [find more about that in the official React Native docs](https://reactnative.dev/docs/native-modules-ios#exporting-swift)\n\n## Usage\n\nDuring runtime check and request permissions with `requestAuthorization`. Failing to request authorization, or requesting a permission you haven't requested yet, will result in the app crashing. This is easy to miss - for example by requesting authorization in the same component where you have a hook trying to fetch data right away.. :)\n\nSome hook examples:\n```TypeScript\nimport { useHealthkitAuthorization, saveQuantitySample } from '@kingstinct/react-native-healthkit';\n\nconst [authorizationStatus, requestAuthorization] = useHealthkitAuthorization(['HKQuantityTypeIdentifierBloodGlucose'])\n\n// make sure that you've requested authorization before requesting data, otherwise your app will crash\nimport { useMostRecentQuantitySample, HKQuantityTypeIdentifier, useMostRecentCategorySample } from '@kingstinct/react-native-healthkit';\n\nconst mostRecentBloodGlucoseSample = useMostRecentQuantitySample('HKQuantityTypeIdentifierBloodGlucose')\nconst lastBodyFatSample = useMostRecentQuantitySample('HKQuantityTypeIdentifierBodyFatPercentage')\nconst lastMindfulSession = useMostRecentCategorySample('HKCategoryTypeIdentifierMindfulSession')\nconst lastWorkout = useMostRecentWorkout()\n```\n\nSome imperative examples:\n```TypeScript\n  import { isHealthDataAvailable, requestAuthorization, subscribeToChanges, saveQuantitySample, getMostRecentQuantitySample } from '@kingstinct/react-native-healthkit';\n\n  const isAvailable = await isHealthDataAvailable();\n\n  /* Read latest sample of any data */\n  await requestAuthorization({ toRead: ['HKQuantityTypeIdentifierBodyFatPercentage'] }); // request read permission for bodyFatPercentage\n\n  const { quantity, unit, startDate, endDate } = await getMostRecentQuantitySample('HKQuantityTypeIdentifierBodyFatPercentage'); // read latest sample\n  \n  console.log(quantity) // 17.5\n  console.log(unit) // %\n\n  await requestAuthorization({\n    toRead: ['HKQuantityTypeIdentifierHeartRate']\n  }); // request read permission for heart rate\n\n  /* Subscribe to data (Make sure to request permissions before subscribing to changes) */\n  const [hasRequestedAuthorization, setHasRequestedAuthorization] = useState(false);\n  \n  useEffect(() =\u003e {\n    requestAuthorization(['HKQuantityTypeIdentifierHeartRate']).then(() =\u003e {\n      setHasRequestedAuthorization(true);\n    });\n  }, []);\n  \n  useEffect(() =\u003e {\n    if (hasRequestedAuthorization) {\n      const unsubscribe = subscribeToChanges('HKQuantityTypeIdentifierHeartRate', () =\u003e {\n        // refetch data as needed\n      });\n\n      return () =\u003e unsubscribe();\n    }\n  }, [hasRequestedAuthorization]);\n\n  /* write data */\n  await requestAuthorization({ toShare: ['HKQuantityTypeIdentifierInsulinDelivery'] }); // request write permission for insulin delivery\n\n  saveQuantitySample(\n      'HKQuantityTypeIdentifierInsulinDelivery',\n      'IU',\n      5.5,\n      {\n        metadata: {\n          // Metadata keys could be arbirtary string to store app-specific data.\n          // To use built-in types from https://developer.apple.com/documentation/healthkit/samples/metadata_keys\n          // you need to specify string values instead of variable names (by dropping MetadataKey from the name).\n          HKInsulinDeliveryReason: HKInsulinDeliveryReason.basal,\n        },\n      }\n    );\n```\n\n### HealthKit Anchors\nIn 6.0 you can use HealthKit anchors to get changes and deleted items which is very useful for syncing. This is a breaking change - but a very easy one to handle that TypeScript should help you with. Most queries now return an object containing samples which is what was returned as only an array before. \n\n```newAnchor``` is a base64-encoded string returned from HealthKit that contain sync information.  After each successful sync, store the anchor for the next time your anchor query is called to only return the values that have changed.\n\n```limit``` will indicate how many records to consider when sycning data, you can set this value to 0 indicate no limit.\n\nExample:\n\n```TypeScript\n  const { newAnchor, samples, deletedSamples } = await queryQuantitySamplesWithAnchor('HKQuantityTypeIdentifierStepCount', {\n    limit: 2,\n  })\n\n  const nextResult = await queryQuantitySamplesWithAnchor('HKQuantityTypeIdentifierStepCount', {\n    limit: 2,\n    anchor: newAnchor,\n  })\n\n  // etc..\n```\n\n## Migration to 9.0.0\n\nThere are a lot of under-the-hood changes in version 9.0.0, some of them are breaking (although I've tried to reduce it as much as possible).\n- The library has been migrated to react-native-nitro-modules. This improves performance, type-safety and gets rid of a lot of boilerplate code that made it harder to maintain and add features to the library.\n- Naming conventions have changed - most of the HK-prefixed stuff has been removed to avoid conflicts on the native side and also make the library more beautiful to look at. As an example the type previously called HKQuantityTypeIdentifier is now just QuantityTypeIdentifier.\n- Fewer required params - for example calling `queryQuantitySamples('HKQuantityTypeIdentifierStepCount')` without arguments will simply return the last 20 samples.\n- Flexible filters that map closer to the native constructs. For example this supports filtering by uuid, multiple uuids as well as on items related to a specific workout.\n- `deleteObjects` replaces all previous deletion methods, using the new flexible filters.\n- Workouts are returned as proxies containing not only data but also functions, for example `getWorkoutRoutes`.\n- Object identifiers are now just strings (not enums), but more strictly typed for each use case.\n- Units are now just strings. There's a `isQuantityCompatibleWithUnit()` helper function. Also, units are never required when querying, it always defaults to the users preferred unit.\n\n## A note on Apple Documentation\n\nWe're striving to do as straight a mapping as possible to the Native Libraries. This means that in most cases the Apple Documentation makes sense. However, when it comes to the Healthkit [Metadata Keys](https://developer.apple.com/documentation/healthkit/samples/metadata_keys) the documentation doesn't actually reflect the serialized values. For example HKMetadataKeyExternalUUID in the documentation serializes to HKExternalUUID - which is what we use.\n\n## Clinical Records\n\nFor accessing Clinical Records use old version (3.x) or use specific branch \"including-clinical-records\". The reason is we cannot refer to this code natively in apps without getting approval from Apple, this could probably be solved by the config plugin but we haven't had time to look into it yet.\n\n## Android alternatives\n\nFor a similar library for Android, check out [react-native-health-connect](https://github.com/matinzd/react-native-health-connect/) that works with the new Health Connect. For Google Fit [react-native-google-fit](https://www.npmjs.com/package/react-native-google-fit) seems to be the most popular option, and and another possible option is to work directly with the Google Fit REST API which I've some experience with.\n\n## Contributing\n\nSee the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.\n\n## Sponsorship and enterprise-grade support\n\nIf you're using @kingstinct/react-native-healthkit to build your production app [please consider funding its continued development](https://github.com/sponsors/Kingstinct). It helps us spend more time on keeping this library as good as it can be.\n\nAt Kingstinct we're also able to provide enterprise-grade support for this package, [find us here](https://kingstinct.com) or [drop an email](mailto:healthkit@kingstinct.com) for more information. Also feel free to join our [Discord community](https://discord.gg/hrgnETpsJA).\n\n## License\n\nMIT\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkingstinct%2Freact-native-healthkit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkingstinct%2Freact-native-healthkit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkingstinct%2Freact-native-healthkit/lists"}