惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AWS News Blog
AWS News Blog
F
Fortinet All Blogs
T
The Blog of Author Tim Ferriss
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
A
About on SuperTechFans
WordPress大学
WordPress大学
MongoDB | Blog
MongoDB | Blog
T
Tailwind CSS Blog
美团技术团队
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
U
Unit 42
有赞技术团队
有赞技术团队
G
GRAHAM CLULEY
Scott Helme
Scott Helme
小众软件
小众软件
T
Threatpost
S
Securelist
SecWiki News
SecWiki News
Recent Announcements
Recent Announcements
L
LINUX DO - 最新话题
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
罗磊的独立博客
Y
Y Combinator Blog
aimingoo的专栏
aimingoo的专栏
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AI
AI
Schneier on Security
Schneier on Security
博客园 - 叶小钗
The GitHub Blog
The GitHub Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
B
Blog RSS Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
S
Secure Thoughts
博客园 - 聂微东
The Hacker News
The Hacker News
Stack Overflow Blog
Stack Overflow Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cloudbric
Cloudbric
V
V2EX
Attack and Defense Labs
Attack and Defense Labs
宝玉的分享
宝玉的分享
Vercel News
Vercel News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build a Fitness Wearable Companion App with React Native (HealthKit + Health Connect)
Famitha M A · 2026-05-14 · via DEV Community

You bought a smartwatch. Within a week, you stopped checking the watch face. The dashboard, the streaks, the weekly chart — all of that lives on the phone.

That phone app is called a companion app, and it's the most underrated piece of any fitness wearable product. The watch captures. The phone interprets, stores, and visualizes.

This post is a code-first walkthrough of how to build one in React Native. We'll cover the architecture, HealthKit (iOS), Health Connect (Android), an optional Apple Watch bridge, and the sync model that doesn't fall over in production.

TL;DR for the impatient:

  • Read from HealthKit on iOS and Health Connect on Android — you cover 90% of wearables without writing firmware.
  • Use react-native-health and react-native-health-connect.
  • Make your backend POST /samples idempotent on the HealthKit UUID. This single rule prevents most sync bugs.
  • The dashboard UI is the time sink, not the integration. Plan accordingly.

The Architecture (Internalize This Before Writing Code)

[Wearable] → [OS Health Store] → [React Native bridge]
   → [Local DB (SQLite / WatermelonDB)]
   → [Sync queue] → [Backend]
   → [Other devices / Web dashboard]

Enter fullscreen mode Exit fullscreen mode

Three things to internalize:

  1. The OS health store is the source of truth for samples, not your app. If the user reinstalls, HealthKit still has the data. Your local DB is a cache for fast UI plus a write buffer for user-generated samples.
  2. Reads are one-directional, writes are bidirectional. Reads pull from HealthKit/Health Connect. Writes hit both the OS store and your backend.
  3. Background delivery is a constraint, not a feature. iOS will throttle aggressively. Design as if your app wakes every 15–30 minutes, not every second.

Pick Your Wearable Target First

The biggest mistake I see: shipping for "wearables" generically. Each platform has a different data model and review hurdle.

Wearable Data path Library Watch-side code?
Apple Watch HealthKit react-native-health Only for watchOS UI
Pixel / Galaxy Watch Health Connect react-native-health-connect Only for Wear OS tile
Fitbit Health Connect / Web API react-native-health-connect + OAuth No
Garmin Garmin Health API OAuth + REST Optional (Connect IQ)
Whoop / Oura / Polar Vendor REST APIs OAuth + REST No
Custom BLE hardware Direct BLE react-native-ble-plx N/A

For most consumer apps, start with HealthKit + Health Connect. They cover every major retail wearable, the user already trusts the permission dialog, and you skip juggling six OAuth flows. Vendor SDKs are a v2 problem.

Step 1 — Scaffold the Expo Project

You need a custom dev client since both health libraries are native modules.

npx create-expo-app fitness-companion --template
cd fitness-companion
npx expo install expo-dev-client
npm install react-native-health react-native-health-connect
npx expo prebuild

Enter fullscreen mode Exit fullscreen mode

In app.json:

{
  "expo": {
    "ios": {
      "infoPlist": {
        "NSHealthShareUsageDescription": "Read your activity to power your dashboard.",
        "NSHealthUpdateUsageDescription": "Save workouts you log in the app."
      },
      "entitlements": {
        "com.apple.developer.healthkit": true
      }
    },
    "android": {
      "permissions": [
        "android.permission.health.READ_STEPS",
        "android.permission.health.READ_HEART_RATE",
        "android.permission.health.READ_SLEEP",
        "android.permission.health.READ_EXERCISE"
      ]
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Step 2 — Read Health Data on iOS (HealthKit)

import AppleHealthKit, { HealthKitPermissions } from 'react-native-health';

const permissions: HealthKitPermissions = {
  permissions: {
    read: [
      AppleHealthKit.Constants.Permissions.Steps,
      AppleHealthKit.Constants.Permissions.HeartRate,
      AppleHealthKit.Constants.Permissions.SleepAnalysis,
      AppleHealthKit.Constants.Permissions.Workout,
      AppleHealthKit.Constants.Permissions.ActiveEnergyBurned,
    ],
    write: [AppleHealthKit.Constants.Permissions.Workout],
  },
};

AppleHealthKit.initHealthKit(permissions, (err) => {
  if (err) console.error('HealthKit init failed', err);
});

Enter fullscreen mode Exit fullscreen mode

Fetch today's step count:

const startOfDay = new Date();
startOfDay.setHours(0, 0, 0, 0);

AppleHealthKit.getStepCount(
  { date: startOfDay.toISOString() },
  (err, results) => {
    if (err) return;
    setSteps(results.value);
  }
);

Enter fullscreen mode Exit fullscreen mode

Three production gotchas

  • Aggregated queries can double-count. If the user has both an Apple Watch and a third-party app writing steps, the default aggregate may count both. Use getSamples with explicit source filtering when accuracy matters.
  • iOS won't tell you if read permission was denied. getStepCount just silently returns zero. Render an empty state, not an error.
  • enableBackgroundDelivery needs HKObserverQuery. Budget half a day to wire it up properly the first time.

Step 3 — Read Health Data on Android (Health Connect)

Health Connect replaced the Google Fit dev API in 2025. Pixel Watch and Galaxy Watch already write to it.

import {
  initialize,
  requestPermission,
  readRecords,
} from 'react-native-health-connect';

await initialize();

await requestPermission([
  { accessType: 'read', recordType: 'Steps' },
  { accessType: 'read', recordType: 'HeartRate' },
  { accessType: 'read', recordType: 'SleepSession' },
  { accessType: 'read', recordType: 'ExerciseSession' },
]);

const result = await readRecords('Steps', {
  timeRangeFilter: {
    operator: 'between',
    startTime: startOfDay.toISOString(),
    endTime: new Date().toISOString(),
  },
});

const totalSteps = result.records.reduce((sum, r) => sum + r.count, 0);

Enter fullscreen mode Exit fullscreen mode

Health Connect's permission UX is cleaner than HealthKit's (one consolidated screen), but you can only read the past 30 days unless the user explicitly grants extended history access.

Step 4 — Apple Watch Bridge (Optional)

If you want a watchOS app — say, a quick-start workout button — you need a watchOS target in Xcode bridged to RN via WCSession. The watch app itself is Swift (RN doesn't run on watchOS).

Minimal Swift bridge:

class WatchBridge: NSObject, WCSessionDelegate, RCTBridgeModule {
  static func moduleName() -> String! { "WatchBridge" }

  func session(_ session: WCSession,
               didReceiveMessage message: [String : Any]) {
    if let event = message["event"] as? String, event == "workoutSample" {
      RCTBridge.current()?.eventDispatcher().sendAppEvent(
        withName: "WatchWorkoutSample", body: message
      )
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

On the RN side, subscribe with NativeEventEmitter and update your store. A reasonable v1 scope: start/end workout from the watch face, with samples flowing back live. Anything more (full watch UI, complications) is multi-week work.

For Wear OS, the equivalent is the Data Layer API with MessageClient. Same pattern: native module, JS bridge, event emitter.

Step 5 — The Dashboard UI (Where Time Actually Goes)

Data flows. Now you need the actual app. Standard companion-app screens:

  • Today — steps, heart-rate ring, active calories, latest workout
  • Trends — weekly/monthly bar charts
  • Workouts — list of ExerciseSession / Workout records with detail view
  • Goals — editable daily targets, local + synced
  • Settings — permissions, units, connected devices

Stack I'd recommend:

  • Charts: victory-native (maintained, gesture support, works on both platforms). Skip react-native-svg-charts — unmaintained.
  • List: virtualize aggressively. Users routinely have thousands of historical workouts.
  • State: Zustand or Redux Toolkit. Avoid Context for high-frequency updates from health observers.

Honest aside: this is the part of the build that's the least interesting and the most time-consuming. The integration code lands in week one. The dashboard eats the next two-to-three weeks if you write every screen by hand.

The third time I built one of these, I described the spec in plain English to an AI mobile app builder and got a full Expo project — components, navigation, theming — in under an hour, then plugged my HealthKit hooks into it. The tool I used was RapidNative, which generates real React Native + Expo code (not a proprietary runtime — you own the output). Worth a look if the dashboard is the part you'd rather not write by hand.

Step 6 — Sync, Offline, Conflicts

The pattern that survives production:

  1. Local-first writes. WatermelonDB or expo-sqlite. Every user-logged workout → local DB → HealthKit/Health Connect → upload queue.
  2. Pull-based reads from the health store. On app open and on background fetch (~30 min cadence on iOS), pull deltas since last_sync_timestamp, dedupe by UUID, upsert.
  3. Idempotent uploads. Every HealthKit sample has a stable UUID. Make POST /samples a no-op on duplicate UUIDs:
// Backend pseudocode
async function ingestSample(sample) {
  await db.samples.upsert({
    where: { healthkit_uuid: sample.uuid },
    update: { value: sample.value, modified_at: sample.endDate },
    create: { ...sample, healthkit_uuid: sample.uuid },
  });
}

Enter fullscreen mode Exit fullscreen mode

This single rule prevents 90% of the sync bugs that haunt fitness apps.

  1. No cellular uploads by default. Gate behind a setting. Battery-sensitive users uninstall fast.

Edge case that bites everyone: a user edits a workout in the Apple Health app. HealthKit emits an "updated" sample with the same UUID but a new modification date. Your sync code must handle this — most don't, which is why so many fitness apps quietly drift out of sync.

Realistic Timeline

For a single full-stack dev who's shipped React Native before:

Phase Time
Setup, permissions, HealthKit + Health Connect reads 3–5 days
Dashboard UI (5 screens, charts, theming) 5–8 days
Local DB + backend sync 4–6 days
Apple Watch companion (basic workout start/stop) 5–7 days
Polish + App Store review prep 5–10 days
v1 ship 3–5 weeks

The dashboard phase is the easiest to compress because it has nothing to do with wearables. Scaffolding it with an AI tool can take that week down to a day.

App Store Gotchas That Kill Submissions

  • PrivacyInfo.xcprivacy is mandatory for any iOS app touching HealthKit (since 2024). Missing it = auto-reject.
  • HealthKit data cannot be used for advertising or sold. Period.
  • Health Connect requires a published privacy policy URL in your Play Store listing.
  • You cannot transmit another user's HealthKit data. "Share with a friend" features need each recipient's own HealthKit permission grants.

FAQ

Can I use Expo for this?
Yes, with a custom dev client. npx expo prebuild then eas build --profile development. Expo Go won't work because of the native modules.

Do I have to ship a watchOS app to support Apple Watch?
No. The watch already writes to HealthKit. Read from HealthKit and you support every Apple Watch user without writing Swift. A watchOS app is only for on-wrist UI.

Google Fit vs Health Connect?
Health Connect replaced Google Fit's dev API in 2025. New apps should use react-native-health-connect.

Can React Native do live heart-rate streaming?
Not via HealthKit (samples arrive on a delay). For real-time streams, either a watchOS app over WCSession or a direct BLE connection via react-native-ble-plx.


Wrap-up

The integration work — HealthKit, Health Connect, WCSession — is irreducible. You write it yourself. The UI on top is boilerplate you've seen in fifty other apps, and it's where most of the calendar disappears.

Start with the system health stores. Make your sync endpoint idempotent. Don't ship a watchOS app until you've validated the phone experience.

If this was useful, drop a comment with what you're building — happy to dig into specific edge cases (sleep data is a rabbit hole, ask me how I know).

Cover photo by Onur Binay on Unsplash.