Syncing HealthKit data in React Native: what the tutorials don't tell you

November 25, 2026 โ€” 15 min read
Syncing HealthKit data in React Native: what the tutorials don't tell you

Hi everybody! ๐Ÿ‘

It's been a while since I last wrote something here, but this past year I've been working on something I really wanted to share with you: how my team and I built an integration to sync Apple Health data in a React Native app.

I worked on a big part of the implementation, from the first version of the sync to a lot of its edge cases, but this was definitely a team effort. This post is what we learned together along the way.

So, first thing I need to say: most HealthKit tutorials end at the same place. You ask for permission, you read today's steps, you show a number on the screen and... done! Or not? ๐Ÿคจ

That was not our problem. We were working on a health app where users connect Apple Health once, and from then on their data catches up automatically whenever they use the app. Without them thinking about it, without losing data and without creating duplicate records on the backend.

So, let's take a look at how it works and the stories (and bugs) behind it.

The setup

The stack is pretty simple:

  • Expo (SDK 55) with a development build (HealthKit doesn't run in Expo Go, I learned that pretty quickly).
  • @kingstinct/react-native-healthkit (v10.1) as the bridge to HealthKit. It's typed, it's maintained and it supports the anchored queries I'll talk about in a bit.
  • TypeScript (5.9) and React Query (v5) for the API calls.

Asking for permission is the easy part:

import { requestAuthorization } from '@kingstinct/react-native-healthkit';
 
// Only the types your app actually needs
const TYPES_TO_READ = [
  'HKQuantityTypeIdentifierStepCount',
  'HKCategoryTypeIdentifierSleepAnalysis',
] as const;
 
await requestAuthorization({ toRead: TYPES_TO_READ });

But here comes the first surprise ๐Ÿ‘€:

HealthKit keeps read authorization private. It's a privacy decision from Apple.

If a query for sleep comes back empty, you can't tell whether the user denied access or simply doesn't have any sleep samples. From your app's point of view, both look exactly the same.

So you can't build a screen like this one:

  • Steps: connected โœ…
  • Sleep: not connected โŒ

What we did instead was be honest about what we can see. For each health data type, we show when data last arrived, and if nothing has arrived yet, we just say so:

  • Steps: updated 2 hours ago
  • Sleep: no data yet

Right below, a short note like:

"Missing something? You can review what you share with this app in Settings."

With a button that takes them straight to Settings (Linking.openSettings() in React Native), so they can go to Health from there and manage the permissions for your app.

That way the user can double-check their permissions themselves, instead of us guessing.

Fun fact ๐Ÿ’ก: Android's Health Connect does tell you which permissions were granted, which is why both platforms ended up with different UIs.

An example of what this can look like
An example of what this can look like

Don't sync by date. Sync with anchors โš“๏ธ

Our first idea was the obvious one: "let's save the date of the last sync and next time read everything after that date". To be honest, it breaks very quickly:

  • A user can log older data (a workout they forgot to log, a device that syncs a day later), so it shows up "in the past", before your last sync date.
  • Two samples can share the same timestamp, which makes your "after this date" logic very messy.
  • A user can delete data, and a regular date-filtered sample query will never tell you about it.

Luckily, HealthKit has a better tool for this: anchored queries.

Every time you read, HealthKit gives you back an anchor, which works like a bookmark ๐Ÿ”–. It marks your progress through one particular query stream (a data type plus the filters you used).

Next time, you pass that anchor and HealthKit returns only what changed since then: new samples and deleted ones.

That gives you two kinds of sync:

  • Initial sync: the very first time a user connects Apple Health. There's no anchor saved yet, so you start from scratch and read a limited window of their recent history.
  • Incremental sync: every sync after that. You already have a saved anchor, so HealthKit only gives you what changed since last time (new data and deletions). These are usually small and fast.

One thing that's easy to miss: a saved anchor doesn't mean the initial sync is done.

If the app closes after the first page, you have an anchor, but there may still be more history to read. So the next run has to keep going from that anchor until it catches up.

The history window

On the first sync, you usually don't want to read the user's whole history, so you pick a cutoff, for example "the last 30 days".

You can also opt to save that initial cutoff together with the anchor, so if a initial sync gets interrupted, the next run uses it as a reference instead of calculating a new one.

Initial and incremental sync run the same loop, the only difference is where they start
Initial and incremental sync run the same loop, the only difference is where they start

This is what the initial sync looks like. There's nothing saved yet, so you calculate the cutoff once and store it next to the first anchor:

// Illustrative example, written for @kingstinct/react-native-healthkit v10.1.
// Other versions may use a different filter shape, so check the docs for yours.
import { queryQuantitySamplesWithAnchor } from '@kingstinct/react-native-healthkit';
import { subDays } from 'date-fns';
 
// Any HealthKit data type you sync, one at a time
const healthDataType = 'HKQuantityTypeIdentifierStepCount';
 
// Example values, tune them for your app
const PAGE_SIZE = 100;
const HISTORY_DAYS = 30;
 
// uploadToYourApi, loadProgress and saveProgress are your own helpers
 
// Initial sync: pick the cutoff once...
const cutoff = subDays(new Date(), HISTORY_DAYS);
 
const { samples, deletedSamples, newAnchor } =
  await queryQuantitySamplesWithAnchor(healthDataType, {
    limit: PAGE_SIZE,
    filter: { startDate: cutoff },
  });
 
// Send the data to your backend so it can be stored/ingested
await uploadToYourApi(healthDataType, samples, deletedSamples);
 
// ...and save it together with the anchor.
// This is only the first page: there may still be more history to read!
await saveProgress(healthDataType, { anchor: newAnchor, cutoff });

And this is the full loop, which works for both. If there's no saved progress, it starts an initial sync; if there is, it resumes with the same anchor and cutoff:

// Same imports, healthDataType, constants and helpers as above
const saved = await loadProgress(healthDataType);
 
// Calculate the cutoff once and reuse it, so the query scope never changes
const cutoff = saved?.cutoff ?? subDays(new Date(), HISTORY_DAYS);
let anchor = saved?.anchor;
 
while (true) {
  const { samples, deletedSamples, newAnchor } =
    await queryQuantitySamplesWithAnchor(healthDataType, {
      limit: PAGE_SIZE,
      anchor,
      filter: { startDate: cutoff },
    });
 
  // Nothing new and nothing deleted: we're caught up ๐ŸŽ‰
  if (samples.length === 0 && deletedSamples.length === 0) break;
 
  // Throws if any upload chunk fails, so the anchor below is never saved
  await uploadToYourApi(healthDataType, samples, deletedSamples);
 
  anchor = newAnchor;
  await saveProgress(healthDataType, { anchor, cutoff });
}

There are two details in there that cost us some debugging time:

  1. Don't rely on a short page to know you're done.

    Pages can come back with only deletions, and Apple's docs describe the limit as the maximum number of samples without saying exactly how deletions count toward it.

    It's safer to stop when a successful query returns neither new samples nor deletions, like the loop above does.

  2. Save the anchor only after the page's work succeeds, including every upload chunk.

    If you save it early and an upload fails, the next incremental sync starts after that page and silently skips it.

    Saving it afterward means some requests can be replayed, so make your API idempotent: use each sample's UUID as its key, so uploading the same sample twice updates the same record instead of creating a duplicate, and deleting an already deleted UUID does nothing.

Also, unlike Health Connect, HealthKit doesn't document a 30-day expiry for anchors. But Apple does describe deleted objects as temporary: the system may remove them at any time to free up space.

On Android, the equivalent (changes tokens) expires after 30 days, so there you need a fallback... but that's a story for another post.

When there's a LOT of data

Remember the history window? This is the story of why it mattered.

The first version worked great on our phones. Then we tested with people who had years of Apple Watch data, and reading all of it on first open made the app feel broken.

Limiting the initial sync to a recent window fixed that.

A couple of other things we learned:

  • Pages, then chunks. A HealthKit query page and an upload request are two different things. Each page gets uploaded in smaller chunks, so one big page never becomes one giant request. (The sizes in this post are just examples, not production settings.)
  • Retries with exponential backoff, but only for failures that are transient. p-retry works great for this. Trust me, a 400 will still be a 400 on the third try, so retrying it just wastes the user's battery.
// Illustrative example, written for p-retry v6.2.
// Newer major versions changed the callback signatures, so check the docs for yours.
import pRetry from 'p-retry';
 
// You decide what's worth retrying. For example, your API being
// temporarily down or busy (502, 503, 504), a timeout (408) or
// too many requests (429) can get better on their own.
// A bad request (400) or a missing permission (403) won't.
const YOUR_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
 
// How you read the status and spot network errors depends on your
// API client (fetch, axios, ...), so these two are your own helpers.
const isTransient = (error: unknown) => {
  const status = getHttpStatus(error);
  if (status) return YOUR_RETRYABLE_STATUSES.includes(status);
 
  // No status: only retry if your client says it was a network failure
  return isTransientNetworkError(error);
};
 
// Example values, tune them for your app
await pRetry(() => uploadToYourApi(chunk), {
  retries: 3,
  factor: 2,
  minTimeout: 1_000,
  maxTimeout: 30_000,
  shouldRetry: (error) => isTransient(error),
});

Not every sample is worth sending

Some data types are huge.

Step counts are a good example: HealthKit stores them as lots of small intervals, and when someone has an iPhone and an Apple Watch, both of them write them.

Sending every interval to a backend means a looot of rows, sometimes for a number you only need per day.

For types like that, my teammates came up with a lighter approach (and it was a great call!):

  1. Keep reading changes with the anchored query. The anchor still moves forward, and you find out what changed.
  2. Skip uploading the raw samples, since you usually don't need every little interval. Or keep them too, if you want them for debugging or reconciliation later.
  3. Ask HealthKit for the daily total of each affected day, using a statistics query.
  4. Upload just one value per day.

A nice side effect: HealthKit handles the aggregation for you, including overlapping data from the phone and the watch.

Just keep in mind that query options, which sources you include and where your day boundaries fall (time zones, midnight) can all affect how your totals compare with what the user sees in the Health app.

Deletions are the tricky part here.

A deleted object gives you its UUID, but not the original timestamps, so you can't tell which day it belonged to.

When a page includes deletions, we recalculated the totals for a recent range of days instead of only the days we saw.

And the important rule: the anchor only advances after the recalculated totals upload successfully.

If the totals fail, the next sync starts again from the old anchor and recalculates the same days.

Other (not so small) edge cases

Besides the big pieces, there were a few edge cases along the way that looked small at first... and then they weren't ๐Ÿ˜…. Most tutorials don't cover them, so here they are.

The phone is locked ๐Ÿ”’

HealthKit data is protected while the device is locked, so if a sync is running and the user locks the phone, a query can fail with errorDatabaseInaccessible ("Protected health data is inaccessible").

Retrying right away doesn't help, the phone is still locked!

So when you get that error, a simple approach is to skip that type and try again later from the same saved anchor. The next time the sync runs, it picks up from the same place.

It also helps to keep the screen awake while a sync is running (expo-keep-awake is perfect for this) and to show a small message asking the user to keep their phone unlocked.

Anchors saved in Keychain were locked too

This one was sneaky. If you store your anchors in Expo SecureStore (the iOS Keychain), by default they can only be read or written while the phone is unlocked.

So if the user locks the phone (or auto-lock does it) while a sync is still running, iOS keeps the app alive for a few seconds... just enough for an upload to finish and for saving the anchor to fail.

We found the fix, and it's literally one option: AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY.

It changes when the stored anchor can be accessed: after a restart, it becomes available once the user unlocks the phone for the first time, and it stays available after that, even while the phone is locked.

The anchors stay encrypted, and HealthKit data access still follows its own rules:

import * as SecureStore from 'expo-secure-store';
 
const options = {
  keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
};
 
await SecureStore.setItemAsync(key, anchor, options);
const saved = await SecureStore.getItemAsync(key, options); // same option when reading

Two syncs at the same time

In a real app, a sync can start from more than one place (the app opening, the app coming back to the foreground, the user pressing a button...). Two of them running at once means two loops reading and writing the same anchors, plus duplicated uploads.

It's very tempting to reuse the status you already show in the UI (something like 'syncing') as the lock.

We learned this one the hard way. UI state changes for UI reasons, and sooner or later something resets it while a sync is still running.

A safer option is a dedicated flag in a store (here with Zustand), and only two functions can touch it:

import { create } from 'zustand';
 
type SyncLockState = {
  isLocked: boolean;
  acquireSyncLock: () => boolean;
  releaseSyncLock: () => void;
};
 
export const useSyncLock = create<SyncLockState>((set, get) => ({
  isLocked: false,
  acquireSyncLock: () => {
    if (get().isLocked) return false;
    set({ isLocked: true });
    return true;
  },
  releaseSyncLock: () => set({ isLocked: false }),
}));

This works within the same JavaScript runtime because there's no await between reading the flag and updating it, so two callers can never both get true.

And every caller acquires the lock before syncing and releases it in a finally:

const { acquireSyncLock, releaseSyncLock } = useSyncLock.getState();
 
if (!acquireSyncLock()) return; // another sync is already running
 
try {
  await syncAllHealthDataTypes(); // your own sync function
} finally {
  releaseSyncLock(); // always, even if the sync throws
}

The trade-off: if someone forgets the release, every later sync is blocked for the rest of the app session, so it's worth having tests for that.

Reinstalls and different users

  • After a reinstall, the Keychain can still have the old anchors, but the data on the backend may be gone. Detect the reinstall and clear those stale anchors so the next sync starts fresh.
  • Store sync progress per user. If someone logs out and another person logs in on the same phone, they shouldn't inherit each other's sync state.

So, when does the sync run?

There's no real background sync here. The sync runs while the user is in the app:

When What happens
The app opens or comes back to the foreground Incremental sync
A screen that shows health data gets focus Silent sync, with a short cooldown
The user taps a "Sync" button Manual sync with feedback

For our users, "my data catches up when I open or use the app" was good enough, and it kept things a lot simpler.

What I would tell myself a year ago

  • Design for "keep syncing", not "read once". Anchors, deletions and retries are the real feature.
  • Save your progress only after the work succeeds. Anchors, cutoffs, tokens: all of them.
  • Lock your phone while testing. Seriously! Some of the sneakiest bugs only show up when the phone is locked.
  • Keep the UI state and the sync lock separate. They look like the same thing. They're not.
  • Write the docs as you go. A README with a flowchart for every sync path saves a lot of time for new people on the team (and for you).

Looking back, reading from HealthKit was the easy part. The interesting engineering was figuring out how to resume the sync when a request failed, the app closed, or someone locked their phone.

And that's it! I hope you enjoyed this one and that it saves you some of the debugging hours it cost us.

If you're building something similar and have questions, reach out, I'm happy to help. And if you'd like to read how we did the same on Android with Health Connect, let me know ๐Ÿ™‚!

Looking for a product builder?

I bring not only my expertise, but also a collaborative spirit that turns ideas into remarkable products.

Reach out to me at hey@nopitown.com