Gareth Wilson Gareth Wilson

Guide to Terra API Webhooks: Features and Best Practices

Published


Terra gives developers one API for health and fitness data from wearables and apps such as Garmin, Fitbit, Oura and Google Fit. Users connect their device accounts through Terra, and Terra then pushes their activity, sleep, body and daily data to you in a normalised format as it arrives. The webhook destination is how that data, and the events about each user's connection, reach your application.

This guide covers setting up a Terra webhook destination, the event types and how to route them, verifying the timestamped terra-signature header, and Terra's delivery rules: an 8-second response limit, roughly eight hours of retries, and a circuit breaker that pauses data during outages.

What are Terra API webhooks?

A Terra webhook destination is a single callback URL for your developer account, configured on the dashboard Connections page with its own signing secret. Every event type is sent to it; there's no per-event subscription. Two broad kinds of delivery arrive:

  • Connection events about users: a successful or failed auth, a deauth, a user_reauth that replaces a user record, access_revoked from the provider side, and connection_error when a provider returns 401, 403 or 412.
  • Data events with normalised health data: activity, sleep, body, daily, athlete, nutrition, menstruation and hormone. They arrive throughout the day as devices sync, and in response to data requests you make.

Terra also sends status events for asynchronous requests, a periodic healthcheck, and, if you enable ping mode, deliveries that carry a download link instead of the data itself.

Terra API webhook features

FeatureDetails
Signaturehex HMAC-SHA256
Signature headerterra-signature
BodyJSON
Event routingBody field type

Events and payloads

Event (type)Triggered WhenCommon Use Cases
authA user connects a provider (check status)Store the Terra user_id, mark the connection live
deauthA user disconnectsStop syncing, clean up
user_reauthA user re-authenticates and gets a new user IDRemap the stored user ID
access_revokedThe user revoked access at the providerAsk the user to reconnect
connection_errorA provider connection failsAlert, prompt reconnection
activityNew workout dataTraining logs
sleepNew sleep dataRecovery dashboards
bodyNew body metricsHealth trends
dailyNew daily summaryDaily dashboards
athleteProfile dataKeep profile fields in sync

The status events are processing (data is being fetched asynchronously), large_request_processing and large_request_sending (for requests covering more than a month), rate_limit_hit (a provider rate limit; Terra will retry) and google_no_datasource (a Google Fit user with no linked data source).

Ping mode has a naming conflict in Terra's own docs. The event table calls the download-link event s3_upload, while the webhooks page's example and handler use s3_payload. Handle both until your own deliveries show which one is sent.

Event Payload Structure

Every body starts with type. Most also have status (success, warning, error and so on) and a user object identifying the Terra user and provider. user_reauth has new_user and old_user instead. Depending on the type, you'll also see message, reference_id (your own ID for the user, set when they connected) or data, an array of normalised records.

Terra documents each type with a template ("user": User, String, Number) rather than a complete example, so check field names against the data model reference and a real delivery. The terra-reference header ties a data request you make to the webhook deliveries it produces, so you can match data back to the request that asked for it.

Setting up Terra API webhooks

Prerequisites

  • A Terra developer account with dashboard access
  • A public HTTPS endpoint (during development, use the Hookdeck CLI tunnel below)

How Do I Register My Endpoint?

  1. In the Terra dashboard, open Connections and add a Webhook data destination (see Terra's webhook setup docs).
  2. Enter your endpoint URL, for example https://example.com/webhooks/terra-api.
  3. Decide whether you want ping mode, which sends a download link in place of the data.

How Do I Get My Terra Signing Secret?

The destination's signing secret is shown on the same Connections page. Copy it into WEBHOOK_SECRET and use it as text: the HMAC key is its UTF-8 bytes.

Environment Variables

WEBHOOK_SECRET=your_terra_signing_secret

Test a delivery

Start a local receiver and forward requests with the Hookdeck CLI:

npx hookdeck-cli listen 3000 terra-api --path /webhooks/terra-api

Set the CLI URL as the destination, connect a test device account through Terra's widget, and watch for the auth event followed by the first data events. Leave it running a while and you'll also see a healthcheck.

Securing Terra API webhooks

terra-signature has the form t=<unix seconds>,v1=<signature>, sometimes with a v0= entry too. Build the message from the t value as text, a dot and the raw body, compute HMAC-SHA256 with the signing secret, and compare the hex result against each v1 value. Ignore v0. The docs show 64-character lowercase hex values without naming the encoding. See Terra's webhook docs.

Terra doesn't document a timestamp tolerance. The verifier below doesn't enforce one, so a retry or a Hookdeck replay of an old delivery still verifies.

Node.js verification

const crypto = require('node:crypto');

function verifySignature(rawBody, headers, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof secret !== 'string' || !secret) return false;
  const signature = headers['terra-signature'];
  if (typeof signature !== 'string') return false;
  const key = Buffer.from(secret, 'utf8');
  const parts = signature.split(',').map((part) => part.trim());
  const times = parts.filter((part) => part.startsWith('t=')).map((part) => part.slice(2));
  if (times.length !== 1 || !/^[0-9]+$/.test(times[0])) return false;
  const message = Buffer.concat([Buffer.from(`${times[0]}.`, 'utf8'), rawBody]);
  const candidates = parts.filter((part) => part.startsWith('v1=')).map((part) => part.slice(3));
  const expected = crypto.createHmac('sha256', key).update(message).digest();
  return candidates.some((candidate) => {
    if (!/^[0-9a-fA-F]{64}$/.test(candidate)) return false;
    const received = Buffer.from(candidate, 'hex');
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

There's no event ID, so the handler uses a hash of the body to skip repeats. It answers healthcheck straight away, accepts either ping-mode type name, and handles user_reauth before anything else so later data lands on the right user.

const express = require('express');

function createTerraApp({ seenBefore, remember, saveConnection, remapUser, fetchPing, saveData }) {
  const app = express();
  app.post('/webhooks/terra-api', express.raw({ type: '*/*' }), async (req, res) => {
    const secret = process.env.WEBHOOK_SECRET;
    if (!secret) return res.sendStatus(500);
    if (!verifySignature(req.body, req.headers, secret)) return res.sendStatus(401);
    let payload;
    try {
      payload = JSON.parse(req.body.toString('utf8'));
    } catch {
      return res.sendStatus(400);
    }
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
      return res.sendStatus(400);
    }
    if (typeof payload.type !== 'string') return res.sendStatus(400);
    if (payload.type === 'healthcheck') return res.sendStatus(200);
    const bodyHash = crypto.createHash('sha256').update(req.body).digest('hex');
    try {
      if (await seenBefore(bodyHash)) return res.sendStatus(200);
      if (payload.type === 'user_reauth') {
        await remapUser(payload.old_user, payload.new_user);
      } else if (['auth', 'deauth', 'access_revoked', 'connection_error'].includes(payload.type)) {
        await saveConnection(payload.type, payload.status, payload.user);
      } else if (payload.type === 's3_payload' || payload.type === 's3_upload') {
        await fetchPing(payload, req.headers['terra-reference']);
      } else if (Array.isArray(payload.data)) {
        await saveData(payload.type, payload.user, payload.data, req.headers['terra-reference']);
      } else {
        console.log('Terra status event', payload.type, payload.status);
      }
      await remember(bodyHash);
    } catch {
      return res.sendStatus(503);
    }
    return res.sendStatus(200);
  });
  return app;
}

Keep saveData short. Large data events still need a response within 8 seconds, so store the array and process it from a queue.

On a Hookdeck Terra API source, Hookdeck parses t and every v1, signs <t>.<body> with your secret and accepts the request if any v1 matches. Terra receives 200 either way. A mismatch is stored as failed verification and not forwarded, and no age limit is applied to t.

Keep wearable data flowing. Hookdeck Event Gateway answers Terra well inside 8 seconds, so the circuit breaker stays closed, and holds every data event for retries and replay well beyond Terra's eight-hour window.

Terra API webhook limitations and pain points

Events are dropped after about eight hours

The Problem: An outage longer than the retry window loses data with no notification.

Why It Happens: Terra retries up to 10 times with exponential backoff from 30 seconds, about 8 hours in all, then drops the event.

Workarounds:

  • Monitor for gaps and request the missing range through Terra's data endpoints once you're back.
  • Keep the terra-reference of each request so you can tell which data came back.

How Hookdeck Can Help: Hookdeck acknowledges deliveries as they arrive and keeps them, so your downtime doesn't count against Terra's retries. Events are retried and replayable from Hookdeck instead.

The circuit breaker pauses data

The Problem: During sustained failures, data events stop while auth events continue, and paused time still uses up retries.

Why It Happens: Terra runs a circuit breaker per destination that pauses data events, and paused cycles count towards the 10 retries.

Workarounds:

  • Fix failures quickly; a short outage that trips the breaker can cost more data than expected.
  • After recovery, backfill data for users who had auth activity during the outage.

How Hookdeck Can Help: With Hookdeck returning 200 on Terra's first attempt, failures in your service don't trip Terra's breaker.

Tight 8-second timeout

The Problem: Large data payloads take longer than 8 seconds to process synchronously.

Why It Happens: Terra counts only a 2xx within 8 seconds as success.

Workarounds:

  • Persist the body and respond, then parse and store records asynchronously.
  • Consider ping mode, which replaces the data with a download link you can fetch later.

How Hookdeck Can Help: Hookdeck responds to Terra immediately and gives your endpoint a separate, configurable timeout.

Templates instead of examples

The Problem: Payload fields have to be confirmed by experiment.

Why It Happens: Terra's event pages show templates such as "user": User rather than full bodies, and the ping-mode event name differs between pages.

Workarounds:

  • Capture real deliveries for each type you use and test against them.
  • Route on type with a default branch, and accept both s3_payload and s3_upload.

How Hookdeck Can Help: Hookdeck records every request in full, so you can inspect and replay real Terra payloads while building handlers.

No event ID

The Problem: Retries can't be matched to the original by ID.

Why It Happens: Deliveries carry no unique event identifier; terra-reference identifies a request, not a single event.

Workarounds:

  • Hash the body for deduplication, and upsert data records by user and time range.

How Hookdeck Can Help: Hookdeck assigns its own ID to every request and can drop exact duplicates.

Best practices

Remap users on user_reauth

Replace old_user with new_user in your records as soon as user_reauth arrives, or later data will look like it belongs to an unknown user.

Upsert health data

Data for the same day can arrive more than once as devices sync. Upsert by user, type and time window rather than inserting each delivery.

Treat data as sensitive

Health data is personal and often regulated. Keep payloads out of logs, encrypt them at rest, and delete them when a deauth arrives if your policy requires it.

Allow Terra's IPs if you filter traffic

Terra lists its egress IPs on its data destinations overview page. Use that list for firewall rules, and verify the signature regardless.

Conclusion

Terra's webhooks combine connection lifecycle events and high-volume health data on one signed destination. The signature is straightforward, but delivery isn't forgiving: eight seconds to respond, about eight hours of retries, a circuit breaker that pauses data, and no event IDs or full examples to build against.

Hookdeck Event Gateway holds Terra events beyond its retry window and keeps the circuit breaker closed while your service recovers.

Get started with Hookdeck for free and handle Terra API webhooks reliably in minutes.


Gareth Wilson

Gareth Wilson

Product Marketing

Multi-time founding marketer, Gareth is PMM at Hookdeck and author of the newsletter, Community Inc.