Apple Health on my website
How my iPhone sends today's steps, heart rate and sleep to this site every hour, and how the site keeps, caches and shows them, with the code.
The Stats page shows today's numbers from Apple Health: steps, distance, heart rate, last night's sleep and a few more. They come straight from my phone, about once an hour, with no server of my own and no app I had to write.
This is how it works, from the iPhone to the page, with the code.
The idea
Apple Health has no web API. The data lives on the phone, and only apps on the phone can read it. So something on the phone has to send it out.
That something is Health Data Export, a free iPhone app that can POST your Health data as JSON to any HTTPS address, on a schedule. The rest is a small webhook on this site:
- The phone sends a JSON export to
POST /api/health, with a secret token. - The site keeps only today's numbers, in one private file in Vercel Blob.
- The Stats page reads that file, and anyone can read the same numbers at
GET /api/health.
That's all. No database, no history, no queue.
On the iPhone
Health Data Export is free; the only in-app purchases are tips. Besides files and iCloud Drive, it can send JSON to an HTTPS webhook, with an optional bearer token that it keeps in the iOS Keychain.
What I set up:
- Health access for the metrics I show, and nothing else. The app asks for each type, and you can say no to the rest.
- An automation that sends JSON to
https://ryck.dev/api/health, with my token as the bearer token. - Daily totals and averages, not raw samples. Each delivery covers the past week, one number per metric per day, so a missed hour fixes itself on the next one.
- Every hour. iOS decides exactly when background work runs, so "hourly" really means "roughly hourly, when the phone feels like it". For a stats page, that's fine.
The app can also send a test payload with no health samples in it, which is handy for checking the endpoint before any real data goes out. The webhook treats it as a successful no-op.
The token is just a long random string. I made one and gave it to the site and the app:
openssl rand -hex 32vercel env add HEALTH_WEBHOOK_TOKEN productionWhat the phone sends
A delivery looks like this, trimmed to a few metrics, with made-up numbers:
{ "export_date": "2026-11-15T12:08:37Z", "date_range": { "days": 7, "start": "2026-11-09T00:00:00Z", "end": "2026-11-15T23:59:59Z" }, "metrics": [ { "id": "HKQuantityTypeIdentifierStepCount", "aggregation_level": "daily", "data_points": [ { "timestamp": "2026-11-15T00:00:00Z", "start_date": "2026-11-15T00:00:00Z", "end_date": "2026-11-15T00:00:00Z", "unit": "count", "value": 1005, "provenance": "reported" } ] } ], "sleep_summaries": [ { "session_start": "2026-11-14T23:12:00Z", "session_end": "2026-11-15T07:03:00Z", "total_sleep_seconds": 26040, "deep_seconds": 3480, "rem_seconds": 5760, "core_seconds": 16800, "awake_seconds": 1200, "heart_rate_samples": [{ "value": 54 }, { "value": 51 }] } ]}Two things to notice. Metrics use HealthKit's own identifiers, like HKQuantityTypeIdentifierStepCount. And values come in HealthKit's units: metres, metres per second, and percentages as fractions, so 98% blood oxygen arrives as 0.98.
Turning it into today's numbers
All of the parsing lives in src/lib/health.ts. It starts with a map from the names the page uses to HealthKit's identifiers, with a conversion where the units differ:
type Metric = { id: string; convert?: (value: number) => number }
const dailyMetrics = { steps: { id: "HKQuantityTypeIdentifierStepCount" }, distanceKm: { id: "HKQuantityTypeIdentifierDistanceWalkingRunning", convert: (meters) => meters / 1000, }, walkingSpeedKmh: { id: "HKQuantityTypeIdentifierWalkingSpeed", convert: (metersPerSecond) => metersPerSecond * 3.6, }, restingHeartRate: { id: "HKQuantityTypeIdentifierRestingHeartRate" }, // Percentages come as fractions: 0.98 is 98% bloodOxygenPercent: { id: "HKQuantityTypeIdentifierOxygenSaturation", convert: (fraction) => fraction * 100, }, // …and a dozen more} satisfies Record<string, Metric>satisfies checks every entry against Metric but keeps the exact keys, so keyof typeof dailyMetrics becomes the list of metric names, and a typo anywhere on the page is a type error.
Each name ends in its unit, distanceKm, walkingSpeedKmh, bloodOxygenPercent, so the page never has to guess what a number means.
Which day is today?
The export's timestamps are in UTC, but "today" on this site means today in London. Close to midnight, those aren't the same day, so every date goes through one function:
// en-CA writes dates as YYYY-MM-DDconst londonDays = new Intl.DateTimeFormat("en-CA", { timeZone: "Europe/London",})
export function londonDay(date: Date | string) { return londonDays.format(new Date(date))}The en-CA trick gets 2026-11-15 out of Intl without a date library, and the time zone handles summer time for free.
Picking today's values
A delivery has a week of data points per metric. For each metric I want, the parser finds the last point that falls on the export's day, and converts it:
function pick<Key extends string>( definitions: Record<Key, Metric>, metrics: Array<ExportMetric>, matches: (point: DataPoint) => boolean) { const values: Partial<Record<Key, number>> = {} for (const [key, { id, convert }] of Object.entries<Metric>(definitions)) { const point = metrics .find((metric) => metric.id === id) ?.data_points.findLast(matches) if (point) values[key as Key] = convert ? convert(point.value) : point.value } return values}A metric the phone didn't measure today, like blood oxygen on a day without the watch, is simply missing, not zero. The page leaves it out.
The parser itself is short. It throws away anything that isn't an export, including the app's test ping, and keeps one day:
export function parseHealthExport(body: unknown): HealthToday | null { const data = body as Partial<HealthExport> | null if (!data?.export_date || data.test || !Array.isArray(data.metrics)) { return null } const date = londonDay(data.export_date) const night = data.sleep_summaries?.findLast( (summary) => londonDay(summary.session_end) === date )
return { date, updatedAt: data.export_date, metrics: pick( dailyMetrics, data.metrics, (point) => londonDay(point.timestamp) === date ), sleep: night ? parseNight(night, data.metrics) : null, }}Sleep belongs to the night
Sleep is the awkward one. A night starts on one day and ends on the next, so "today's sleep" is the session that ended today. Readings taken while asleep, like breathing rate and wrist temperature, belong to that night rather than to a day, so they're matched by overlap instead:
metrics: pick( nightMetrics, metrics, (point) => point.start_date <= night.session_end && point.end_date >= night.session_start),ISO dates in UTC sort as strings, so comparing them with <= works without parsing a single one.
The webhook
The endpoint is a TanStack Start server route, src/routes/api/health.ts. POST is for the phone; GET is for everyone:
export const Route = createFileRoute("/api/health")({ server: { handlers: { POST: async ({ request }) => { const denied = checkToken(request) if (denied) return denied
let body: unknown try { body = JSON.parse(await request.text()) } catch { return new Response("Expected a JSON body", { status: 400 }) }
const today = parseHealthExport(body) // The app's test ping has no numbers; accept it without a write if (today) { await saveToday(today) await clearHealthCache() } return new Response(null, { status: 204 }) }, GET: async () => { await tagHealthResponse() const headers = { "Cache-Control": "public, s-maxage=300, stale-while-revalidate=300", "Access-Control-Allow-Origin": "*", } const today = await getCurrentToday() // Nothing sent today: an empty response rather than a JSON null if (!today) return new Response(null, { status: 204, headers }) return Response.json(today, { headers }) }, }, },})Checking the token
The token check hashes both sides before comparing them. timingSafeEqual takes the same time whether the first character or the last one is wrong, so the response time doesn't leak how close a guess was. It also throws if the two buffers differ in length, and hashing makes them both 32 bytes:
import { createHash, timingSafeEqual } from "node:crypto"
const digest = (value: string) => createHash("sha256").update(value).digest()
function checkToken(request: Request) { const token = process.env.HEALTH_WEBHOOK_TOKEN if (!token) { console.warn("Health: missing HEALTH_WEBHOOK_TOKEN") return new Response("Not configured", { status: 503 }) } const header = request.headers.get("authorization") ?? "" if (!timingSafeEqual(digest(header), digest(`Bearer ${token}`))) { return new Response("Unauthorized", { status: 401 }) } return null}A missing token is a 503, not a 401: it's my mistake, not the caller's, and it should say so in the logs.
Trying it from the terminal
# Anyone can read today's numbers: 200 with JSON, or 204 if none yetcurl -i https://ryck.dev/api/health
# Without the token: 401curl -i -X POST https://ryck.dev/api/health -d '{}'
# A test ping, like the app's: 204, and nothing is writtencurl -i -X POST https://ryck.dev/api/health \ -H "Authorization: Bearer $HEALTH_WEBHOOK_TOKEN" \ -d '{"export_date":"2026-11-15T12:00:00Z","test":true,"metrics":[]}'Storage: one file in Blob
Only the latest day is kept, in a single private file, overwritten on every delivery. src/lib/health-store.ts:
import { get, put } from "@vercel/blob"
const TODAY = "health/today.json"
export async function saveToday(today: HealthToday) { await put(TODAY, JSON.stringify(today), { access: "private", addRandomSuffix: false, allowOverwrite: true, contentType: "application/json", })}
export async function getToday(): Promise<HealthToday | null> { // Straight from storage, so a read never lags behind the last write const result = await get(TODAY, { access: "private", useCache: false }) if (!result || result.statusCode !== 200) return null return (await new Response(result.stream).json()) as HealthToday}private means the file has no public URL: only the server, with the store's credentials, can read it. addRandomSuffix: false and allowOverwrite: true keep it at the same path forever.
Keeping one day and nothing else was on purpose. A page of today's steps is fun; a year of my heart rate sitting in a bucket is a liability. It also means one write an hour, which fits comfortably in Blob's free tier.
The site checks the date on the way out, too. If the phone hasn't sent anything since midnight, yesterday's numbers aren't shown as today's:
export async function getCurrentToday() { const today = await getToday() return today?.date === londonDay(new Date()) ? today : null}Caching, and clearing it
Blob's free tier also limits reads, and the Stats page shouldn't read Blob on every visit. So the page and the API are cached by Vercel's CDN, and every response that includes health numbers gets a cache tag:
import { addCacheTag, dangerouslyDeleteByTag } from "@vercel/functions"
const CACHE_TAG = "health"
export const tagHealthResponse = () => addCacheTag(CACHE_TAG)
export const clearHealthCache = () => dangerouslyDeleteByTag(CACHE_TAG)When a new export arrives, the webhook deletes everything with that tag. The next visitor gets a fresh page with the new numbers, and everyone after them gets the cached copy again until the next export.
I delete rather than invalidate on purpose. Invalidating marks the cache as stale, and stale-while-revalidate would still serve the old numbers to one more visitor. "Dangerously" sounds scarier than it is here: the worst case is a few extra renders.
The page gets its numbers through a server function, which sets the same headers and tag:
export const getHealthStats = createServerFn({ method: "GET" }).handler( async (): Promise<HealthToday | null> => { setResponseHeader( "Cache-Control", "public, s-maxage=300, stale-while-revalidate=300" ) try { // Imported here so the Blob and file system code stays on the server const { getCurrentToday, tagHealthResponse } = await import("@/lib/health-store") await tagHealthResponse() return await getCurrentToday() } catch (error) { console.error("Health: couldn't read today's numbers", error) return null } })If anything goes wrong, it returns null and the page simply leaves the Health section out. A broken export should never break the page.
Working on it locally
My phone can't reach my laptop, so in development the numbers can't arrive the normal way. Instead, the store writes to a gitignored file when there's no Blob store configured:
const LOCAL_FILE = ".health/today.json"
const savesToFile = () => import.meta.env.DEV && !process.env.BLOB_READ_WRITE_TOKEN && !process.env.BLOB_STORE_IDAnd a small script copies today's numbers from the live site into that file:
pnpm health:pullIt's scripts/health-pull.ts, plain TypeScript that Node runs directly, no build step:
async function pull() { const response = await fetch(`${site.url}/api/health`) if (!response.ok) { console.error(`${site.url}/api/health: ${response.status}`) process.exit(1) } // Empty (204) when the phone hasn't sent anything today return response.status === 204 ? null : ((await response.json()) as HealthToday | null)}
const today = LOCAL && previous ? redate(previous) : await pull()if (!today?.date) { console.log("Nothing to pull: the phone hasn't sent any numbers today.") process.exit(0)}
await mkdir(".health", { recursive: true })await writeFile(".health/today.json", JSON.stringify(today, null, 2))It also says what it got, so I know whether anything changed since the last pull:
Pulled health numbers from https://ryck.dev into .health/today.json Day Sun 15 Nov Exported 12:08 London, 42 minutes ago Since last pull newer than the 11:05 export Metrics 9: steps, distanceKm, activeEnergyKcal, … Sleep 7.2 h, 23:12 → 07:03, 2 night readingsOffline
Pulling needs the network, and the site only shows numbers dated today. So on a plane, yesterday's file is no use: the Health section just disappears.
--local fixes that. Instead of fetching, it takes the last day I pulled and moves it to today:
pnpm health:pull --localpnpm devEverything moves forward by whole days, so last night's sleep still starts at 23:12 and ends at 07:03, just a day later. The export time is the one exception: it can't be later than now, or the page would say the numbers came from the future.
/** The same numbers, moved forward whole days so they fall on today. */function redate(health: HealthToday): HealthToday { const days = Math.round( (Date.parse(`${londonDay(new Date())}T12:00:00Z`) - Date.parse(`${health.date}T12:00:00Z`)) / 86_400_000 ) const shift = (date: string) => new Date(Date.parse(date) + days * 86_400_000).toISOString() // Not later than now, or the export would be from the future const updatedAt = new Date( Math.min(Date.parse(shift(health.updatedAt)), Date.now()) ).toISOString() return { ...health, date: londonDay(new Date()), updatedAt, sleep: health.sleep && { ...health.sleep, start: shift(health.sleep.start), end: shift(health.sleep.end), }, }}Counting the days from noon to noon keeps summer time out of it: a day with a clock change is 23 or 25 hours long, but noon to noon still rounds to one day.
The numbers themselves aren't real for today, of course. They're yesterday's steps with today's date on them, which is all I need to work on the page.
Testing it
The parser is a pure function, so it's easy to test with Vitest. The tests build a delivery shaped like the app's, with made-up numbers:
const point = (day: string, value: number) => ({ timestamp: `${day}T00:00:00Z`, start_date: `${day}T00:00:00Z`, end_date: `${day}T00:00:00Z`, unit: "count", value, provenance: "reported",})
const metric = (id: string, values: Record<string, number>) => ({ id, aggregation_level: "daily", data_points: Object.entries(values).map(([day, value]) => point(day, value)),})Then they check the edges: that only the export's day is kept, with metres turned into kilometres; that a metric with nothing for that day is left out rather than zero; that the test ping and anything else that isn't an export are ignored; and that half past eleven at night UTC is already tomorrow in London in summer, but not in winter:
it("uses London's date, not UTC's", () => { expect(londonDay("2026-07-01T23:30:00Z")).toBe("2026-07-02") expect(londonDay("2026-11-15T23:30:00Z")).toBe("2026-11-15")})In Storybook, the server function is swapped for a mock, so every state of the Health section has a story: early morning with barely any steps, a night without the watch, a phone with no watch at all, and a day with no export yet.
What I'd tell you if you're building one
- Keep the parsing on the server, and in one place. The app's format will change one day, and only one file should care.
- Name values with their units.
distanceKmcan't be confused with miles or metres. - Decide what "today" means, and use one function for it everywhere.
- Keep as little as you can. You can't leak what you didn't store.
- Make the empty state boring. No export yet is normal, not an error.