For the complete documentation index, see llms.txt. This page is also available as Markdown.

Health Bridge Functions

Access your users’ health and fitness data, like steps, workouts, and heart rate, with JavaScript functions that work in both Android and iOS apps.

WebToNative’s health JavaScript functions on Android and iOS, covering request parameters, supported data types, Promise results, and common errors.

  • Android: uses Health Connect.

  • iOS: uses Apple HealthKit.

  • openProvider() is Android-only. Permission settings are opened with window.WTN.Permission.open() on both Android and iOS.

1. Check availability

Use isAvailable() before starting a health-data workflow.

window.WTN.HealthBridge.isAvailable()
  .then(function (result) {
    if (result.available) {
      console.log("Health provider is available");
    } else {
      console.log("Health provider status:", result.status);
    }
  })
  .catch(function () {
    // Not running inside a WebToNative app
  });

Result fields

Key
Type
Description

success

boolean

Whether the availability check completed

available

boolean

true when the provider is available

status

string

Provider status

platform

string

healthConnect on Android or healthKit on iOS

providerVersion

string

Android only; provider version when available

Example Android response:

Example iOS response:

Android status values may include available, providerUpdateRequired, providerNotInstalled, and unsupported. iOS status values include available and unsupported.

2. Open health permission settings

Use window.WTN.Permission.open() to take the user to the relevant settings for the requested permission.

Open settings directly

Show a confirmation dialog first

The permission value is "health" for Health Bridge settings. The destination depends on the platform. On Android, this opens the Health Connect permission/settings page. On iOS, the app's Settings page may open; opening the exact Health app permissions screen is not guaranteed.

3. Check health permission status

Use window.WTN.Permission.check() with dataTypes to check read and write permission status for each requested health data type. This checks the current status; it does not request new permissions or display a permission prompt.

Example successful result:

Each requested data type has its own status. ALLOWED means access is granted for that data type, while NOT_ALLOWED means it is not granted. Check success before reading permissions; a failed check may not include the per-type results.

Platform note: iOS HealthKit does not reveal whether read access was denied. Therefore, a reported read status may not reliably establish that HealthKit will return records; handle empty read results as well.

4. Request health permissions

Request only the read and/or write access your feature needs.

Request keys

Key
Type
Required
Description

permission

string

Yes

Use "health" for Health Bridge permissions

dataTypes

object

Yes

Contains read and/or write arrays

dataTypes.read

string array

No

Types the app wants to read

dataTypes.write

string array

No

Types the app wants to write

Promise result

object

—

Resolve value handled with .then()

Result fields

Key
Type
Description

success

boolean

Whether the permission request flow completed

permissions.read

object array

Per-type read statuses

permissions.write

object array

Per-type write statuses

permissions.*[].dataType

string

Data type being reported

permissions.*[].status

string

ALLOWED or NOT_ALLOWED

error

object

Present if the request flow could not run

error.code

string

Machine-readable error code

error.message

string

Human-readable explanation

error.recoverable

boolean

Whether the issue may be recoverable

Example response:

Important: success: true means the permission flow completed. It does not mean every requested permission was granted. Check each type's status.

iOS read-permission behavior: HealthKit does not reveal whether the user granted or denied read access. For that reason, read entries in this permission callback are reported as ALLOWED after the authorization request completes; this does not guarantee that data will be returned. When the app calls read(), HealthKit authorization is requested as needed, and iOS may show its system permission prompt if access has not already been requested. The read result may still be empty. Write statuses are reported per type.

On Android, read and write statuses represent the permissions granted by Health Connect.

5. Supported data types

Use the exact, case-sensitive names below in dataTypes, read(), and record dataType fields.

Data type
Description
Typical unit
Read
Write

steps

Step count

count

Yes

Yes

distance

Distance travelled

m

Yes

Yes

activeEnergy

Active energy burned

kcal

Yes

Yes

totalEnergy

Total energy burned

kcal

Yes

Android only

floorsClimbed

Floors climbed

count

Yes

Yes

exerciseTime

Exercise duration

min

Yes

No

height

Height

m

Yes

Yes

weight

Body weight

kg

Yes

Yes

bodyFat

Body-fat percentage

%

Yes

Yes

leanBodyMass

Lean body mass

kg

Yes

Yes

heartRate

Heart rate

bpm

Yes

Yes

restingHeartRate

Resting heart rate

bpm

Yes

Yes

hrv

Heart-rate variability

ms

Yes

No

bloodGlucose

Blood glucose

mmol/L

Yes

Yes

oxygenSaturation

Blood oxygen saturation

%

Yes

Yes

bodyTemperature

Body temperature

°C

Yes

Yes

respiratoryRate

Respiratory rate

breaths/min

Yes

Yes

vo2Max

VO₂ max

mL/kg/min

Yes

No

sleep

Sleep records and stages

min

Yes

Yes

waterIntake

Water intake

mL

Yes

Yes

calorieIntake

Calories consumed

kcal

Yes

Yes

menstruation

Menstrual flow information

flow level

Yes

Yes

Notes:

  • exerciseTime is derived from exercise sessions on Android.

  • totalEnergy is derived from active plus basal energy on iOS and cannot be written on iOS.

  • exerciseTime, hrv, and vo2Max are read-only on both platforms.

  • For menstruation, supply the flow level through the unit field when writing: light, medium, or heavy.

  • Data availability depends on provider support, user permissions, and which apps or devices have recorded the data.

6. Read health records

Use read() to retrieve records for one or more data types over a date range.

Request keys

Key
Type
Required
Description

dataTypes

string array

Yes

Data types to read

startDate

ISO-8601 string

Yes

Start of the requested time range

endDate

ISO-8601 string

Yes

End of the requested time range; must be after startDate

Promise result

object

—

Resolve value handled with .then()

bucket

string

No

raw (default), minute, hour, day, or week

aggregation

object

No

Per-type aggregation override where supported, e.g. { "heartRate": "latest" }

unitSystem

string

No

metric or imperial; defaults to the app's configured unit system

includeSource

boolean

No

Whether to include source app identifiers; defaults to true

deduplicate

boolean

No

For supported bucketed cumulative totals, use provider aggregation to account for overlapping source records; defaults to true

limit

number

No

Maximum rows per data type per page; default and maximum 5000

pageToken

string

No

Token from a previous response to retrieve the next page

Successful result

Result fields

Key
Type
Description

success

boolean

Whether the read succeeded

data

object

Records grouped by data type, e.g. data.steps

data.<dataType>[]

object array

Rows returned for that type

start, end

string

Record or bucket time boundaries

unit

string

Unit for the returned value

sources

string array

Source app identifiers; omitted if includeSource: false

value

number

Measurement value, when applicable

aggregation

string

Aggregation used for a bucketed row

totalMinutes, stages

number/object array

Sleep duration and stage details

flow

string

Menstrual flow level

min, max, sampleCount

number

Additional heart-rate summary values when available

metric

string

HRV measurement type

hasMore

boolean

Whether more pages are available

nextPageToken

string or null

Pass this value as pageToken to get the next page

unsupported

string array

Requested data type names that are not recognized

A type with no matching records returns an empty array. Read rows do not contain record IDs; retain IDs returned by write() if you need to delete records later.

Buckets, aggregation, and pagination

  • raw returns individual records. minute, hour, day, and week return grouped rows.

  • Buckets use the device's local time zone. Day boundaries follow local midnight; week boundaries start on local Monday.

  • Supported aggregations depend on the data type. Cumulative quantities such as steps and distance support sum; measurement types such as heart rate support avg or latest.

  • deduplicate applies to supported bucketed cumulative totals. It does not change raw reads.

  • Empty buckets are omitted. Bucketed row dates include the local UTC offset; raw row dates are UTC ISO-8601 strings.

  • If hasMore is true, pass nextPageToken back as pageToken with the same request options. Treat the token as opaque; do not edit it. limit applies separately to each requested data type.

History access

historyAccess is an Android-only configuration setting.

  • Android: Reading Health Connect data older than 30 days requires historyAccess to be enabled and the appropriate Health Connect history permission to be granted.

  • iOS: historyAccess is not used by the iOS permission flow and does not restrict HealthKit historical reads. HealthKit does not use this Android-specific setting.

7. Write health records

Use write() to save records to the user's health provider. Required fields depend on the data type.

Request keys

Key
Type
Required
Description

records

object array

Yes

Records to save

records[].dataType

string

Yes

Supported data type name

records[].value

number

Most types

Measurement value in the canonical unit listed above

records[].timestamp

ISO-8601 string

Point-in-time records

Time of a single measurement

records[].start

ISO-8601 string

Interval records

Interval start time

records[].end

ISO-8601 string

Interval records

Interval end time; must be after start

records[].unit

string

Some types

Unit override for blood glucose or flow level for menstruation

records[].stages

object array

Optional for sleep

Sleep stages with stage, start, and end

records[].isCycleStart

boolean

Optional; iOS menstruation

Indicates cycle start; ignored on Android

Promise result

object

—

Resolve value handled with .then()

Use ISO-8601 timestamps with Z or an explicit UTC offset. Use start and end for interval records, and timestamp for point-in-time records. The exact required fields vary by data type.

Result fields

Example success or partial-success result:

Key
Type
Description

success

boolean

Whether the request was processed; individual records may still fail

recordIds

string array

IDs for successfully saved records

results

object array

One result per submitted record, in input order

results[].dataType

string

Data type for the submitted record

results[].success

boolean

Whether that record was saved

results[].recordId

string

ID of a successfully saved record

results[].error

object

Error details for a record that could not be saved

results[].error.code

string

Machine-readable error code

results[].error.message

string

Human-readable explanation

results[].error.recoverable

boolean

Whether the issue may be recoverable

A top-level success: true does not guarantee that every record was saved. Check results[].success for each record. Keep the returned recordIds if you may need to delete those records later.

Read-only types (exerciseTime, hrv, and vo2Max, plus totalEnergy on iOS) cannot be written.

8. Delete records

Use the record IDs returned by write() to delete records previously written by the app.

Request keys

Key
Type
Required
Description

recordIds

string array

Yes

Record IDs returned by write()

dataType

string

Yes

Data type associated with the IDs in this request

Promise result

object

—

Resolve value handled with .then()

Result fields

Example response:

Key
Type
Description

success

boolean

Whether the request was processed; individual IDs may still fail

deletedIds

string array

IDs successfully deleted

results

object array

One result per submitted ID

results[].recordId

string

ID being processed

results[].success

boolean

Whether that ID was deleted

results[].error

object

Error details when deletion fails

results[].error.code

string

Machine-readable error code

results[].error.message

string

Human-readable explanation

results[].error.recoverable

boolean

Whether the issue may be recoverable

Only records written by the app can be deleted. Always inspect results[], because individual IDs may fail even when the overall request was processed.

9. Common error codes

Failures generally include an error object with code, message, and recoverable. Use error.code for program logic; message wording may vary by platform. Promise rejections are handled with .catch() when the call is unavailable outside a WebToNative app.

Error code
Meaning
Suggested action

HEALTH_UNAVAILABLE

The health provider is unavailable or Health Bridge is not enabled

Check availability and app configuration

PROVIDER_NOT_INSTALLED

Health Connect is not installed

Use openProvider() on Android

PROVIDER_UPDATE_REQUIRED

Health Connect needs an update

Use openProvider() on Android

PERMISSION_DENIED

Required access is not granted

Request the required permission; on Android, the user may need to change Health Connect settings

HISTORY_PERMISSION_REQUIRED

Android historical access is not enabled or granted

Enable history access and grant the Health Connect history permission

TYPE_UNSUPPORTED

An unsupported data type or invalid parameter was supplied

Check the data type name and request fields

WRITE_NOT_SUPPORTED

The requested type cannot be written

Check the data type's write support

DELETE_NOT_PERMITTED

A record could not be deleted

Confirm the record ID and that it was written by this app

DATE_RANGE_INVALID

A date is invalid, missing, or an interval does not run forward

Use valid ISO-8601 dates and ensure end is later than start

RESULT_TOO_LARGE

The requested limit is greater than 5000

Use a limit of 5000 or less and paginate, or request bucketed data

STORE_ERROR

The platform health provider could not complete the operation

Check the message and retry when appropriate

Example error response:

10. Practical guidance

  1. Check provider availability before starting.

  2. Request only the read/write permissions required for the feature.

  3. Use exact, case-sensitive data type names.

  4. Use ISO-8601 timestamps with Z or an explicit UTC offset.

  5. Check top-level success, then inspect per-record results for write() and deleteRecords().

  6. Keep record IDs returned by write() if records may need to be deleted later.

  7. For large date ranges, use buckets or pagination.

  8. A completed permission flow does not guarantee that data exists for every requested type.

Last updated