BT

API Reference

Complete reference for the BodyTracker class — the single entry point for the core @bodytracker/sdk package. Every constructor, method, and property is documented below with its full signature, parameters, return value, and a runnable example. If you're building with React, the Hooks reference wraps this same class with reactive bindings.

new BodyTracker()

Constructorsince v1.0.0

Creates a new tracker instance from a configuration object. The constructor is synchronous and does no camera or model work — it validates the config, stores it, and puts the tracker in the idle status. Call init() afterward to perform the async setup that actually prepares tracking.

TypeScript
new BodyTracker(config: BodyTrackerConfig)

Parameters

ParameterTypeDescription
configRequired
BodyTrackerConfigTracker configuration: your API key, target environment, optional camera device, activity type allowlist, movement smoothing, and locale.

Returns

BodyTrackerA new tracker instance in the idle status, ready to be initialized.

Throws

  • TypeErrorThrown synchronously if config.apiKey is missing, empty, or not a string.

Example

tracker.tsTypeScript
import { BodyTracker } from "@bodytracker/sdk"; const tracker = new BodyTracker({  apiKey: "bt_live_7Gm3q...redacted",  environment: "production",  activityTypes: ["standing", "walking", "running"],  smoothing: { enabled: true, windowSize: 5 },}); console.log(tracker.getStatus()); // "idle"

Notes

  • Constructing a tracker has no side effects on the page — no camera prompt, no network request — until init() is called.
  • Use environment: "sandbox" during development to exercise the full API against synthetic tracking data without a real camera feed.

init()

Methodsince v1.0.0

Performs the tracker's asynchronous setup: requests camera permission via getUserMedia, downloads and warms up the on-device tracking model, and transitions status from idle to initializing to ready. Every other tracking method requires init() to have resolved first.

TypeScript
init(): Promise<void>

Returns

Promise<void>Resolves once the tracker has reached the ready status and startSession() can be called.

Throws

  • CameraPermissionDeniedErrorThrown if the user denies the camera permission prompt or the browser blocks getUserMedia.
  • ModelLoadErrorThrown if the tracking model fails to download or fails to initialize on the current device.

Example

init.tsTypeScript
const tracker = new BodyTracker({ apiKey: "bt_test_2Lp9x...redacted" }); try {  await tracker.init();  console.log(tracker.getStatus()); // "ready"} catch (error) {  console.error("Failed to initialize tracker:", error);}

Notes

  • Calling init() more than once on the same instance is safe — subsequent calls resolve immediately once the tracker is ready.
  • In environment: "sandbox" mode, init() skips the camera permission prompt entirely and resolves against synthetic data.

startSession()

Methodsince v1.0.0

Begins a new tracking session and transitions status to tracking. A session groups continuous movement data under a single id until stopSession() is called, and can be paused and resumed without ending it.

TypeScript
startSession(options?: StartSessionOptions): Promise<Session>

Parameters

ParameterTypeDescription
optionsOptional
StartSessionOptionsOptional session metadata: the activity to record under and a human-readable label shown in exports and dashboards.

Returns

Promise<Session>Resolves with the newly created session once recording has started.

Throws

  • TrackerNotReadyErrorThrown if init() has not resolved yet — the tracker must be in the ready status.
  • SessionAlreadyActiveErrorThrown if a session is already recording or paused; stop it first.

Example

start-session.tsTypeScript
await tracker.init(); const session = await tracker.startSession({  activity: "running",  label: "Morning run",}); console.log(session.id, session.status); // "recording"

Notes

  • If options.activity is omitted, the SDK infers the initial activity from the live camera feed as soon as tracking starts.

stopSession()

Methodsince v1.0.0

Ends the active tracking session, finalizes its analytics, and transitions status back to ready. Use exportSession() afterward if you need the raw or formatted session data.

TypeScript
stopSession(): Promise<SessionSummary>

Returns

Promise<SessionSummary>Resolves with the completed session's duration, activity, and average tracking quality.

Throws

  • NoActiveSessionErrorThrown if there is no recording or paused session to stop.

Example

stop-session.tsTypeScript
const summary = await tracker.stopSession(); console.log(`Tracked ${summary.durationSeconds}s of ${summary.activity}`);console.log(`Average quality: ${summary.averageQuality}`);

pauseSession()

Methodsince v1.0.0

Pauses the active session without ending it — movement data stops accumulating and status becomes paused, but the session id and elapsed duration are preserved. Call resumeSession() to continue.

TypeScript
pauseSession(): void

Returns

voidNo return value; check getStatus() to confirm the tracker is now paused.

Throws

  • NoActiveSessionErrorThrown if there is no recording session to pause.

Example

pause-session.tsTypeScript
tracker.pauseSession();console.log(tracker.getStatus()); // "paused"

Notes

  • Unlike stopSession(), pausing does not produce a SessionSummary — the session is still open.

resumeSession()

Methodsince v1.0.0

Resumes a session previously paused with pauseSession(), transitioning status back to tracking and continuing to accumulate movement data on the same session id.

TypeScript
resumeSession(): void

Returns

voidNo return value; check getStatus() to confirm the tracker is tracking again.

Throws

  • NoActiveSessionErrorThrown if there is no paused session to resume.

Example

resume-session.tsTypeScript
tracker.resumeSession();console.log(tracker.getStatus()); // "tracking"

getStatus()

Methodsince v1.0.0

Synchronously reads the tracker's current lifecycle status. Useful for guarding calls to session methods or driving UI state without subscribing to events.

TypeScript
getStatus(): TrackerStatus

Returns

TrackerStatusOne of "idle" | "initializing" | "ready" | "tracking" | "paused" | "stopped" | "error".

Example

get-status.tsTypeScript
const status = tracker.getStatus(); if (status === "tracking") {  console.log("Currently recording a session.");}

getActivity()

Methodsince v1.0.0

Synchronously reads the most recently detected activity and tracking quality, along with the timestamp since that activity began. Useful for polling in render loops where subscribing to activityChanged would be overkill.

TypeScript
getActivity(): ActivitySnapshot

Returns

ActivitySnapshotThe current activity, its tracking quality, and an ISO 8601 timestamp for when it started.

Example

get-activity.tsTypeScript
const snapshot = tracker.getActivity(); console.log(`${snapshot.activity} (${snapshot.quality} quality) since ${snapshot.since}`);

Notes

  • Before the first activity is detected, activity defaults to "idle" and quality to "searching".

on()

Methodsince v2.0.0

Subscribes handler to the given event and returns an unsubscribe function — the preferred way to detach a listener, especially for handlers created inline. See the Events reference for every event name and its payload shape.

TypeScript
on(event: TrackerEventName, handler: (payload: unknown) => void): () => void

Parameters

ParameterTypeDescription
eventRequired
TrackerEventNameThe event to subscribe to, e.g. "activityChanged" or "sessionEnded".
handlerRequired
(payload: unknown) => voidCalled with the event's payload each time it fires. Narrow payload's type per-event using the Events reference.

Returns

() => voidA function that, when called, removes this exact handler from this exact event.

Example

on.tsTypeScript
const unsubscribe = tracker.on("activityChanged", (event) => {  console.log("Activity changed:", event);}); // Later, when you no longer need updates:unsubscribe();

Notes

  • The same handler can be registered for multiple events, and the same event can have multiple handlers — all are called in registration order.

off()

Methodsince v2.0.0

Removes a previously registered handler from an event. Requires the exact same function reference passed to on() — prefer the unsubscribe function on() returns unless you need to detach a named handler from elsewhere.

TypeScript
off(event: TrackerEventName, handler: (payload: unknown) => void): void

Parameters

ParameterTypeDescription
eventRequired
TrackerEventNameThe event the handler was registered on.
handlerRequired
(payload: unknown) => voidThe exact handler reference originally passed to on().

Returns

voidNo return value. Calling off() with a handler that isn't registered is a safe no-op.

Example

off.tsTypeScript
function handleQualityChanged(payload: unknown) {  console.log("Quality changed:", payload);} tracker.on("qualityChanged", handleQualityChanged); // ...later, from anywhere with a reference to the same function:tracker.off("qualityChanged", handleQualityChanged);

exportSession()

Methodsince v2.0.0

Generates a downloadable export of a completed session's tracking data in the requested format. json includes the full frame-level movement timeline; csv flattens it into rows suitable for spreadsheets; pdf renders a human-readable summary report.

TypeScript
exportSession(sessionId: string, format: "json" | "csv" | "pdf"): Promise<Blob>

Parameters

ParameterTypeDescription
sessionIdRequired
stringThe id of a completed session, as returned by startSession() or stopSession().
formatRequired
"json" | "csv" | "pdf"The export format to generate.

Returns

Promise<Blob>Resolves with a Blob you can download via a generated object URL or upload elsewhere.

Throws

  • SessionNotFoundErrorThrown if no session with the given sessionId exists for this API key.
  • UnsupportedFormatErrorThrown if format is not one of "json", "csv", or "pdf".

Example

export-session.tsTypeScript
const summary = await tracker.stopSession();const blob = await tracker.exportSession(summary.id, "csv"); const url = URL.createObjectURL(blob);const link = document.createElement("a");link.href = url;link.download = `session-${summary.id}.csv`;link.click();URL.revokeObjectURL(url);

Notes

  • pdf exports are generated server-side and take noticeably longer to resolve than json or csv.

destroy()

Methodsince v1.0.0

Tears down the tracker: stops any active session without producing a summary, releases the camera stream, unloads the tracking model, and removes all event listeners. Transitions status to stopped.

TypeScript
destroy(): void

Returns

voidNo return value.

Example

destroy.tsTypeScript
tracker.destroy();console.log(tracker.getStatus()); // "stopped"

Notes

  • A destroyed instance cannot be reused — construct a new BodyTracker if you need to track again.
  • Always call destroy() when unmounting the component or page that owns the tracker to release the camera. @bodytracker/react's hooks do this for you automatically.