NeccessoryNeccessory
Web SDK

Quickstart

Run a measurement in the browser in cloud mode or on-device mode and get the result to your backend.

Your backend authorizes each measurement with your secret. Your page runs it with the Web SDK. The secret never reaches the browser.

  • Cloud mode works with a cloud key, which you create in the console yourself. Neccessory cloud computes the metrics, stores the result and attests it.
  • On-device mode computes the metrics in the browser. It requires a key approved for on-device use.

Before you begin

  • Get a key ID and secret in the console — see API keys. Keep the secret on your server.
  • Install the SDK — see Installation.
  • Serve the page over HTTPS. On localhost, add assetOrigin: 'https://neccessory.com' to createMeasurement() and prefetchMeasurement() — see Browser support.

Cloud mode

Create a session on your backend

Call POST /sdk/v1/cloud/sessions from your server and return the whole data object to the page. A session is valid for 5 minutes and runs one measurement, so create it right before the user starts.

server.js
import crypto from 'node:crypto';
import express from 'express';

const API = 'https://neccessory.com';
const KEY_ID = process.env.NECCESSORY_KEY_ID;
const SECRET = process.env.NECCESSORY_SECRET;

const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');

function signHeaders(method, path, body = '') {
  const timestamp = String(Math.floor(Date.now() / 1000));
  const nonce = crypto.randomUUID();
  const canonical = ['NCS1', method, path, timestamp, nonce, sha256(body)].join('\n');
  const signature = crypto.createHmac('sha256', sha256(SECRET)).update(canonical).digest('base64');
  return {
    'Content-Type': 'application/json',
    'x-key-id': KEY_ID,
    'x-timestamp': timestamp,
    'x-nonce': nonce,
    'x-signature': signature,
  };
}

const app = express();

app.post('/api/measurement-session', async (req, res) => {
  const path = '/sdk/v1/cloud/sessions';
  const body = JSON.stringify({
    platform: 'web',
    durationSec: 60,
    features: ['hrv', 'bp', 'spo2'],
    consent: true,
  });
  const response = await fetch(API + path, {
    method: 'POST',
    headers: signHeaders('POST', path, body),
    body,
  });
  const { ok, data, error } = await response.json();
  if (!ok) return res.status(response.status).json(error);
  res.json(data);
});

app.listen(3000);

Sign exactly the string you send as the body. The signature scheme is described in Authentication.

  • consent: true confirms that the user agreed to the measurement. Ask for consent before you create the session — see Data & privacy.
  • features selects the metric sets — see Metrics. Omit it to get every set your key allows.
  • Add userRef to link the measurement to a user in your system — see End users.

Run the measurement on your page

index.html
<video id="camera" playsinline muted
  style="position: fixed; width: 1px; height: 1px; opacity: 0; pointer-events: none"></video>
<canvas id="preview" style="width: 100%; max-width: 640px"></canvas>
<p id="status"></p>
<p id="hint"></p>
<p><span id="hr">--</span> bpm</p>
<button id="start">Start</button>
measure.js
import { createMeasurement } from '@neccessory/web-sdk';

const $ = (id) => document.getElementById(id);

const STAGE_TEXT = {
  requestingCamera: 'Allow camera access',
  connecting: 'Connecting…',
  ready: 'Hold still and look at the camera',
  uploading: 'Uploading…',
  processing: 'Calculating results…',
};

const HINT_TEXT = {
  faceTooSmall: 'Move closer to the camera',
  tooDark: 'Find more light',
  tooBright: 'Move out of direct light',
  unstable: 'Hold still',
  lowSignal: 'Keep your face in view and hold still',
};

$('start').addEventListener('click', async () => {
  $('start').disabled = true;

  const response = await fetch('/api/measurement-session', { method: 'POST' });
  if (!response.ok) {
    $('status').textContent = 'Could not start the measurement';
    $('start').disabled = false;
    return;
  }
  const session = await response.json();

  const m = createMeasurement({
    videoEl: $('camera'),
    previewEl: $('preview'),
    mode: 'cloud',
    session,
  });

  m.onStage((stage) => {
    $('status').textContent = STAGE_TEXT[stage] ?? 'Loading…';
  })
    .onCoach((reason) => {
      $('hint').textContent = reason ? HINT_TEXT[reason] ?? '' : '';
    })
    .onRealtime(({ heartRate }) => {
      if (heartRate != null) $('hr').textContent = heartRate;
    })
    .onResult((result) => {
      $('status').textContent = result.quality.usable
        ? `Done: ${result.cardiac.heartRate.value} bpm`
        : 'The signal was too weak. Sit still in even light and try again.';
      $('start').disabled = false;
    })
    .onError((error) => {
      $('status').textContent = `Measurement failed: ${error.code}`;
      $('start').disabled = false;
    });

  await m.start();
});

Set mode: 'cloud' explicitly. Without it, the SDK runs on-device and ignores the session.

The measurement ends by itself when the session duration (durationSec) is reached, and onResult fires. Call m.stop() to end it earlier. If the user switches to another tab, the measurement ends early.

Each measurement needs a new session. To measure again, request a new session and call createMeasurement() again.

Get the result on your backend

The cloud result is already stored and has an id; a complete result with usable quality also has attested: true. Read it on your backend rather than trusting values sent from the page:

  • Job status. GET /sdk/v1/cloud/jobs/{sessionId} — the session ID is also the job ID. See Cloud sessions.
  • Webhooks. The cloud.job.completed event delivers the job with the measurement. See Webhooks.
  • By ID. GET /sdk/v1/measurements/{id} with result.id, or signAndFetchMeasurement() from the package on Node.js 20 or later. See Measurements.

If the connection dropped and the SDK finished the measurement by upload, the session's job ends as aborted with supersededBy pointing to the job that holds the result.

With a test key, the session has no live connection: pass delivery: 'batch' to createMeasurement(). The result is synthetic.

On-device mode

On-device mode requires a key approved for on-device use. Apply in the console — see API keys. On-device results are not attested — see Attested results.

Mint a model grant on your backend

The grant lets the page load the on-device models. Add this route to the server from the cloud example; it reuses signHeaders:

server.js
app.post('/api/model-grant', async (req, res) => {
  const path = '/sdk/v1/models/grant';
  const response = await fetch(API + path, {
    method: 'POST',
    headers: signHeaders('POST', path),
  });
  const { ok, data, error } = await response.json();
  if (!ok) return res.status(response.status).json(error);
  res.json({ grant: data.grant });
});

A grant is valid for 15 minutes. Mint one per page load or per measurement.

Run the measurement on your page

On-device mode has no automatic end. Call m.stop() after 30–60 seconds — the example counts down from 45. stop() computes the result and fires onResult.

measure.js
import { createMeasurement, prefetchMeasurement, toMeasurementInput } from '@neccessory/web-sdk';

const DURATION_SEC = 45;
const $ = (id) => document.getElementById(id);

prefetchMeasurement();

$('start').addEventListener('click', async () => {
  $('start').disabled = true;
  const { grant } = await fetch('/api/model-grant', { method: 'POST' }).then((r) => r.json());

  const m = createMeasurement({
    videoEl: $('camera'),
    previewEl: $('preview'),
    mode: 'on-device',
    modelGrant: grant,
  });
  m.init({ keyId: 'nk_live_…' });

  let timer;
  m.onStage((stage) => {
    if (stage !== 'ready') return;
    let left = DURATION_SEC;
    $('status').textContent = `${left} s`;
    timer = setInterval(() => {
      left -= 1;
      $('status').textContent = `${left} s`;
      if (left === 0) {
        clearInterval(timer);
        m.stop();
      }
    }, 1000);
  })
    .onRealtime(({ heartRate }) => {
      $('hr').textContent = heartRate ?? '--';
    })
    .onResult(async (result) => {
      $('status').textContent = 'Saving…';
      await fetch('/api/measurements', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(toMeasurementInput(result)),
      });
      $('status').textContent = 'Done';
      $('start').disabled = false;
    })
    .onError((error) => {
      clearInterval(timer);
      $('status').textContent = `Measurement failed: ${error.code}`;
      $('start').disabled = false;
    });

  await m.start();
});

The markup is the same as in the cloud example.

prefetchMeasurement() starts downloading the SDK runtime as soon as the page loads. The first on-device start downloads tens of megabytes, so call it early.

Store the result from your backend

Your backend stores the result with POST /sdk/v1/measurements. signAndSubmit() from the package signs and sends the request. It needs Node.js 20 or later:

server.js
import { signAndSubmit } from '@neccessory/web-sdk';

app.post('/api/measurements', express.json({ limit: '256kb' }), async (req, res) => {
  try {
    const stored = await signAndSubmit({ keyId: KEY_ID, secret: SECRET, result: req.body });
    res.json({ id: stored.id });
  } catch (error) {
    res.status(502).json(error);
  }
});

Accept results only from your signed-in users. The stored measurement has an id, origin: "on_device" and attested: false. Storing results is free. The request format is in Measurements.

Submitting from the browser

m.submit(result) signs and stores the result directly from the page. It needs the secret in init():

m.init({ keyId: 'nk_live_…', secret: 'nk_live_…' });
m.onResult(async (result) => {
  const stored = await m.submit(result);
  console.log(stored.id);
});

The secret becomes public

Anyone who opens the page can read the secret and sign requests as you. Use submit() only on internal pages whose users you trust with the key. Everywhere else, store results from your backend.

Lifecycle

MethodWhat it does
createMeasurement(options)Creates a measurement bound to your video element. mode selects cloud or on-device. Create a new one for each run.
m.init({ keyId, secret })On-device only. Sets the key ID the SDK adds to the result. secret is needed only for submit().
m.start()Opens the camera, loads the SDK and starts capturing. Resolves once capture has started. Never rejects — failures go to onError.
m.stop()Ends the measurement and releases the camera. On-device, it computes the result and fires onResult. In cloud mode, it resolves after the result arrives.
m.submit(result)On-device only. Stores the result with POST /sdk/v1/measurements. Requires secret.

Next steps: Callbacks & errors · Configuration · React