Terra Docs
Dashboard
  • Docs
  • API Reference
  • Changelog
  • Get started ⚡️ Choose your integration
  • Health & Fitness API
    • Overview
    • Set up your Integrations
    • Connect a User
    • Receive data updates
    • Request Historical data
    • Write data
    • Debugging FAQ
    • Mobile-Only Sources: Apple, Samsung, Google Fit
      • iOS (Swift)
      • Android (Kotlin)
      • React Native
      • Flutter
  • Streaming API
    • Getting Started
    • Wearable -> Your app
      • iOS (Swift)
      • Android
    • Your app -> Terra
      • iOS (Swift)
      • Android
    • Terra -> Your Backend
  • Teams API
  • Biomarkers API - Upcoming
Powered by GitBook
On this page
  • 1. Install and Setup the Terra React Native Plugin
  • 2. Initialize the SDK
  • 3. Connect a User
  • 4. Validate the Connection
  • 5. Background Delivery setup (iOS only)
  • Disconnecting a user
  • Historical Data retrieval
  • Writing data

Was this helpful?

  1. Health & Fitness API
  2. Mobile-Only Sources: Apple, Samsung, Google Fit

React Native

PreviousAndroid (Kotlin)NextFlutter

Last updated 24 days ago

Was this helpful?

1. Install and Setup the Terra React Native Plugin

  1. Install the using npm (npm install terra-react).

  2. Complete the following iOS and/or Android setup.


2. Initialize the SDK

The first step is to initialize the Terra SDK.

The initialization only needs to be done once on app start, (e.g. in your app.tsx or an equivalent file), and ideally, and everytime the app is brought into the foreground. This ensures that the SDK is properly set up and ready to be used.

The SDK should be initialized every time your app is opened.

This is a necessary prerequisite for other SDK functions to run as expected

Step 1: Import the Terra Plugin

In your project, you should now be able to import function from the Terra Plugin. Here is an example:

app.tsx
import { initTerra } from 'terra-react';

Step 2: Initialize the Terra SDK

In order to interact with the SDK, you need to call initTerra first.

Call initTerra() with the following arguments:

  • devId: Your Developer ID provided by Terra.

  • referenceId: An ID of your choice to identify your app user.

Find more details in the SDK Reference: Terra manager initialization function

app.tsx
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { initTerra, initConnection } from 'terra-react';

const App = () => {
  const [initialized, setInitialized] = useState<boolean>(false);
  
  useEffect(() => {
    const initializeTerra = async () => {
      try {
        const devID = 'YOUR_DEV_ID';
        const referenceId = 'YOUR_REFERENCE_ID';
        
        const successMessage = await initTerra(devID, referenceId);
        if (successMessage.error !== null) {
          throw new Error("Terra manager failed to initialise");
        }
        // Can proceed with other Terra plugin methods
        setInitialized(true);
      } catch (error) {
        console.error('Failed to initialize Terra:', error);
      }
    };

    initializeTerra();
  }, []);

  return (
    <View>
      <Text>Welcome to the App using Terra</Text>
    </View>
  );
};

export default App;

(N.B This call is asynchronous, please ensure this is complete before using other SDK functions).


3. Connect a User

Once Terra is initialized, you can create a connection by calling the function initConnection() to trigger a permission screen pop up.

From terra-react, import initConnection and call the function with the following arguments:

  • type: Specify the connection type (e.g. Connections.APPLE_HEALTH , Connections.SAMSUNG, Connections.HEALTH_CONNECT )

  • token: A one-time authentication token generated from your backend server. This ensures secure communication between your app and the Terra servers.

  • customPermissions: A set of permissions that define what data you want to request from Apple Health (e.g., heart rate, steps). If empty, it defaults to all available permissions.

  • schedulerOn:

    • iOS: Defaults the Background Delivery option to true. This will make Terra send new data from the provider to your webhook automatically.

    • Android: To allow Terra to make scheduled requests whenever the app is in the foreground.

app.tsx
import { Connections, initConnection } from 'terra-react';

const initializeConnection = async () => {
  try {
    // Example token received from your backend
    const token = 'example_token';
    
    // Define connection type and custom permissions
    const connection = Connections.APPLE_HEALTH;
    const customPermissions = [];      // Leave empty to default to all permissions
    const schedulerOn = true;          // Enables background delivery
    
    // Initialize the connection
    const successMessage = await initConnection(
      connection,
      token, 
      schedulerOn,
      customPermissions,
    );
    if (successMessage.error !== null) {
      throw new Error("Error initialising a connection");
    }
  } catch (error) {
    console.error('Connection failed:', error);
  }
}

Apple Health Kit Permission Screen: initConnection()

Apple Health only shows the permission popup once, so calling initConnection() multiple times won’t trigger the popup again unless:

a. you call initConnection with an expanded set of customPermissions

b. the app is deleted & reinstalled.

initConnection only needs to be called a single time.

Health Connect prohibits the permission popup to appear more than once for any given permission, so calling initConnection more than once will result in no action at all

The only case where it would re-appear is if:

  • you call initConnection with an expanded set of customPermissions

  • the app is deleted & reinstalled.

  • A permission that was not granted to use on release by Google has been requested by the app

Apple Health Kit Permission Screen: WebViews 🚧

  • Apple HealthKit implements the permissions popup as a WebView.

  • If your app is also based on a WebView, you will need to interrupt your WebView, call initConnection, then upon completion re-open your WebView.


4. Validate the Connection

function getUserId(connection: Connections): Promise<GetUserId>

5. Background Delivery setup (iOS only)

For Apple apps, you can enable background delivery settings to allow data to be synced even when your app is not brought to the foreground.

  1. Go to your /ios folder in the React Native project

  2. Call the function setUpBackgroundDelivery in your AppDelegate's didFinishLaunchingWithOptions function

This will ensure you get updates for the user's Apple Health data automatically sent to your destination.

AppDelegate.m
#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <TerraiOS/TerraiOS-Swift.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"AwesomeProject";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};
  [Terra setUpBackgroundDelivery];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

Now you'll start receiving health data events automatically to your Data Destination (e.g. webhook)!

You can also request historical data to backfill, to verify that data exists, or as a fallback.


Disconnecting a user


Historical Data retrieval

You may set toWebhook to false if you wish for the callback function to return the data payload on the client side.

import { Connections, initConnection, getDaily } from 'terra-react';

const requestData = async () => {
  try {
    // Example connection type and dates
    const connection = Connections.APPLE_HEALTH;
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
  
    // Optionally, send data to webhook or not
    const toWebhook = false;
    // Call the getDaily function
    const dataMessage = await getDaily(connection, startDate, endDate, toWebhook);
  
    if (dataMessage.error !== null) {
      throw new Error("Failed to get data for user");
    }
    if (dataMessage.success) {
      // process data here
      console.log('Daily data:', dataMessage.data);
    }
  
  } catch (error) {
    // Handle failure (network error, etc.)
    console.error('Failed to get daily data:', error);
  }
}

Writing data

You may write data into Apple Health (Health Connect not yet supported) through one of the helper functions in the SDK

device_data must be passed in for postActivity to succeed.

// Create a payload for the activity data
import { Activity, postActivity, Connections } from 'terra-react';

const postActivityToAppleHealth = async () => {
  const activityPayload: Activity = {
    metadata: {
      name: 'Morning Run',
      start_time: '2024-11-01T07:30:00.000000+00:00',
      end_time: '2024-11-01T08:30:00.000000+00:00',
      type: ActivityType.RUNNING,
    },
    device_data: {
      name:  'Terra'
    },
    heart_rate_data: {
      summary: {
        avg_hr_bpm: 130,
        max_hr_bpm: 160,
      },
    },
    distance_data: {
      summary: {
        distance_meters: 5000,
      },
    },
    calories_data: {
      total_burned_calories: 400,
    },
  };
  
  const resp = await postActivity(Connections.APPLE_HEALTH, activityPayload);
  if (resp.error !== null) {
    throw new Error("failed to post activity to Apple Health")
  }
  // Activity posted yipeeee!
}

1. Call

To ensure a connection is still valid on the client side, use the method. This function returns the user_id for the connection or null if none exists.

Check out the for details about all the functions in the SDK.

In order to disconnect an Apple Health user, you may use, called from your backend.

You can request for historical data using one of the

Check out the for details about all the functions in the SDK

React Native SDK reference
terra-react package
initConnection()
getUserId
the same endpoint as for Web API-based integrations
data retrieval functions.
React Native SDK reference
postActivity
  1. In your terminal, cd to your /ios folder, and run pod install to install all the dependencies.

  2. Add Capabilities:

    1. Healthkit > Healthkit Background Delivery

    2. Background Modes > Background processing

    3. Background modes > Background fetch

  3. Add the following keys to your info.plist:

Method 1: Using XCode

  • 1) Go to the /ios directory of your project, open the .xcworkspace in XCode.

  • 2) Go to info.plist, and add the following keys and values:

Key
Value

Privacy - Health Share Usage Description

Description of how Health data is used

(Min 3 words)

Privacy - Health Records Usage Description

Description of how Health data is used

(Min 3 words)

Privacy - Health Update Usage Description

Description of how Health data is used

(Min 3 words)

Permitted background task scheduler

co.tryterra.data.post.request

Method 2: Directly editing info.plist in your React Native project

  • 1) In your RN app project, go to your /ios folder

  • 2) Go to info.plist, and add the following tags:

info.plist
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
  <string>co.tryterra.data.post.request</string>
</array>
  
<key>NSHealthClinicalHealthRecordsShareUsageDescription</key>
<string>Using TerraiOS to gather health data</string>

<key>NSHealthShareUsageDescription</key>
<string>Using TerraiOS as a mean of getting Health Data</string>

<key>NSHealthUpdateUsageDescription</key>
<string>Allow writing data to health kit</string>

Access Samsung Health

Terra API provides direct access to the Samsung Health SDK via our privileged partnership with Samsung.

If you'd like to apply for Samsung Health access, please reach out to us by submitting a ticket on the Terra Support page. You can find this in your Terra Dashboard!

We will send you the dedicated setup for Samsung Health after your application approval.


Access Health Connect

1. In the Health Connect app

Give all permissions between the apps you wish to read from (e.g. Samsung Health, Google Fit, etc) & Health Connect.

2. Add Health Connect capability to your app

In your app project, go to the /android folder.

Include the permission tags under the Activity you wish to link the user to when they click the privacy policy link in the Health Connect permission screen. Here are the steps:

  1. Go to your Android App's AndroidManifest.xml

  2. Go to your Privacy Policy <activity> and include the following tags under this <activity> tag.

"Your Android manifest needs to have an Activity that displays your app's privacy policy, which is your app's rationale of the requested permissions, describing how the user's data is used and handled." — Health Connect.

AndroidManifest.xml
<intent-filter>
  <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
 </intent-filter>
  
<intent-filter>
   <action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
  <category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
</intent-filter>

Apply for Health Connect access

Before going live (release), you will need to apply for permissions to access the Health Connect API with Google.

  1. For each permission which you are not using, please add the following lines to your AndroidManifest.xml

AndroidManifest.xml
<uses-permission android:name="android.permission.health.READ_HEART_RATE" tools:node="remove"/>

with android.permission.health.XXX for each permission you aren't using

Data Sources requiring the Terra Mobile-SDK

The Mobile SDK is ONLY used to connect to the following integrations:

Apple Health - iOS

Samsung Health - Android

Google Fit - Android. Note: the is the preferred way to connect to Google Fit until its sunsetting on June 30, 2025 due to better reliability

For ALL other integrations, please refer to the

Use this .

application form

Always validate the connection before using the SDK

Check if a user_id exists right after initializing the Terra SDK to see if the connection still exists.

  1. Check if the User is Connected

    1. If the function returns a user ID, the user is still connected, 🎉 keep vibing along!

    2. If the function returns nil, the user needs to reconnect.

  2. Re-connect if Needed If the connection is lost, you can call terra.initConnection() again to re-establish the connection.

Calling terra.initConnection() when the user is already connected or just needs a reconnection will not trigger any permission screens from Apple Health, and the user flow will remain uninterrupted. The connection will be re-established if necessary.

Health & Fitness API
Health & Fitness API

2. Generate an Auth Token

To be able to call the initConnection() method, you need to pass a token as an argument.

This token is a single-use token created to ensure the authentication endpoint for creating a connection (and connecting the SDK to Terra's servers) does not get abused.

Generate the token with this endpoint POSThttps://api.tryterra.co/v2/auth/generateAuthToken . Make sure to call it with your Terra x-api-key and dev-id in the headers from your backend server. After you generate the token, provide the response to your client side using your own logic.

Go to the SDK Reference to find more details on the .

  • During the development phase, it it acceptable to place this call on the client side, exposing your API key in your mobile app.

  • For a production implementation, DO NOT expose your API key this way, and make sure to only make this call from your backend.

iOS Background Delivery Behaviour:

  • Data will still be triggered if the app is killed (with much lower frequency)

  • Data will only be triggered when phone is unlocked

  • Data can only be triggered where there is network connection

  • Only enabled Data Types from will be triggered by background delivery.

the Terra Dashboard
Generate the Mobile SDK Auth Token API Endpoint