NeccessoryNeccessory
Cloud

Cloud sessions

Create a session on your backend, run the measurement with the Web SDK, and read the result on your server.

In cloud mode the Web SDK sends video of the person's face to Neccessory, and Neccessory computes the metrics. Every cloud measurement runs in a session. Your backend creates the session with your secret; your app receives only a short-lived token. The secret never leaves your server.

How it works

  1. Your backend creates a session. It calls POST /sdk/v1/cloud/sessions, signed with your API key.
  2. Your backend passes the whole data object to your app. It holds the session token and the parameters the SDK needs.
  3. The Web SDK runs the measurement. Pass the object as session together with mode: 'cloud'. Live values arrive while the person measures.
  4. Neccessory stores the result and delivers it. The SDK fires onResult with the stored result. Your backend reads the same result with GET /sdk/v1/cloud/jobs/{sessionId} or receives it by webhook.

Create a session

POST /sdk/v1/cloud/sessions. Sign it like every /sdk/v1 request — see Authentication.

Request body

FieldTypeDefaultDescription
platform"web" | "ios" | "android"requiredWhere the measurement runs. Recorded on the session
consenttruerequiredConfirms that the person agreed to cloud processing. See Consent
durationSecinteger60Measurement length, 20–180 seconds. The SDK stops and delivers the result when it is reached
featuresstring[]every set the key allowsMetric sets to compute: hrv, bp, spo2, emotion, gaze. [] computes the core metrics only. Unknown names are ignored
userRefstring—Your pseudonymous ID for the person: 1–64 letters, digits and . _ : @ -. See End users

Heart rate, breathing rate, stress and signal quality are always computed. See Metrics for what each set adds.

Response

201 Created:

{
  "ok": true,
  "data": {
    "sessionId": "cj_5e1c7a90b24f68d3a1e0c9b7",
    "sessionToken": "eyJ2IjoxLCJzaWQiOiJjal81ZTFj…",
    "wsUrl": "wss://infer.neccessory.com/v1/stream",
    "expiresAt": 1767225900000,
    "maxDurationSec": 60,
    "features": ["hrv"],
    "frameSpec": { … }
  }
}
FieldTypeDescription
sessionIdstringSession ID, cj_…. Also the job ID you read the result with
sessionTokenstringAuthorizes this one measurement
wsUrlstring | nullAddress the SDK connects to. null with a test key
expiresAtnumberWhen the token expires, epoch milliseconds
maxDurationSecnumberGranted measurement length, seconds
featuresstring[]Metric sets this session computes and bills
frameSpecobjectParameters for the SDK — pass through unchanged
testtruePresent only with a test key

The session token

  • Valid for 5 minutes. The measurement must start before expiresAt.
  • Single use. One session, one measurement. Starting a second measurement with the same token fails with session_already_used.
  • Safe in the browser. It authorizes this one measurement and nothing else.

Create the session when the person is about to measure — when they press Start, not when the page loads. Create a new session for every measurement, including retries.

Complete example

Backend (Node.js)

The helper signs the exact JSON string it sends. If you let an HTTP client serialize the body for you, its bytes can differ from the ones you hashed and the signature fails.

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 sha256Hex = (data) => crypto.createHash('sha256').update(data).digest('hex');

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

async function neccessory(method, path, payload) {
  const body = payload === undefined ? '' : JSON.stringify(payload);
  const res = await fetch(API + path, {
    method,
    headers: signedHeaders(method, path, body),
    body: body || undefined,
  });
  const json = await res.json();
  if (!json.ok) {
    throw Object.assign(new Error(json.error.message), { status: res.status, code: json.error.code });
  }
  return json.data;
}

const app = express();
app.use(express.json());

app.post('/api/measurement-session', async (req, res) => {
  if (req.body.consent !== true) {
    return res.status(400).json({ error: 'consent_required' });
  }
  try {
    const session = await neccessory('POST', '/sdk/v1/cloud/sessions', {
      platform: 'web',
      consent: true,
      durationSec: 60,
      features: ['hrv'],
      userRef: 'u_42',
    });
    res.json(session);
  } catch (error) {
    res.status(502).json({ error: error.code });
  }
});

app.listen(3000);

Browser

import { createMeasurement } from '@neccessory/web-sdk';

const heartRate = document.querySelector('#heart-rate');

async function measure() {
  const session = await fetch('/api/measurement-session', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ consent: document.querySelector('#consent').checked }),
  }).then((res) => res.json());

  createMeasurement({
    videoEl: document.querySelector('#camera'),
    mode: 'cloud',
    session,
  })
    .onRealtime((update) => {
      heartRate.textContent = update.heartRate ?? '--';
    })
    .onResult((result) => {
      heartRate.textContent = result.cardiac.heartRate.value ?? '--';
    })
    .onError((error) => {
      console.error(error.code, error.message);
    })
    .start();
}

document.querySelector('#start').addEventListener('click', measure);

By default the SDK uses delivery: 'auto': if the live connection drops, it completes the measurement by upload and still delivers the result. All options and callbacks are in Configuration and Callbacks & errors.

Consent is required

Send consent: true only after the person has agreed that video of their face is sent to Neccessory for processing. Without it the request fails with 400 consent_required. Collecting and recording consent is your responsibility — see Data & privacy.

Get the result on your backend

The result the SDK delivers to your app is already stored under your key. Do not trust a copy your app sends back to you — read it on your backend. See Attested results.

GET /sdk/v1/cloud/jobs/{sessionId} returns the session's job. When status is completed, measurement holds the result.

StatusMeaningFinal
pendingSession created, measurement not started. Still pending after expiresAt means it never started; it costs nothing—
runningMeasurement in progressNo
completedDone. measurement holds the result, measurementId its IDYes
failedNo result. error.code says whyYes
abortedEnded early — the person left, or the connection dropped. See belowYes

If the live connection dropped and the SDK completed the measurement by upload, the session's job is aborted with error.code: "superseded", and supersededBy points to the job that holds the result: supersededBy.jobId, supersededBy.status and supersededBy.measurementId. Read that job the same way.

async function getSessionResult(sessionId) {
  const job = await neccessory('GET', `/sdk/v1/cloud/jobs/${sessionId}`);
  if (job.error?.code === 'superseded' && job.supersededBy) {
    return neccessory('GET', `/sdk/v1/cloud/jobs/${job.supersededBy.jobId}`);
  }
  return job;
}

Poll every 2–5 seconds until the status is final, or subscribe to webhooks: cloud.job.completed, cloud.job.failed, cloud.job.aborted and cloud.job.expired fire for sessions and video jobs alike. When the SDK completed a measurement by upload, the cloud.job.completed event carries the new job; its supersedes field holds the original session ID.

Test keys

With a test key (nk_test_…) the session response has test: true and wsUrl: null. No video is processed: the result is synthetic and ready about 2 seconds after the session is created. Until then the job shows running.

Run the Web SDK with delivery: 'batch' for test sessions. Without wsUrl, any other delivery fails with no_ws_url.

createMeasurement({
  videoEl: document.querySelector('#camera'),
  mode: 'cloud',
  session,
  delivery: session.test ? 'batch' : 'auto',
});

Test sessions are free, skip quota checks, and their results carry test: true. See API keys.

Errors

Creating a session can fail with:

HTTPCodeCauseFix
400invalid_platformplatform is missing or not web, ios or androidSend a valid platform
400consent_requiredconsent is not trueCollect consent, then send consent: true
400invalid_durationdurationSec is outside 20–180Send a value from 20 to 180
400validation_erroruserRef has an invalid formatUse 1–64 letters, digits and . _ : @ -
401unauthorizedInvalid signature, or the key is disabled or expiredCheck your signing code; the exact reason is in the usage log
403feature_not_allowedA requested metric set is not enabled on the keyEnable it on the key or remove it from features
403quota_exceededThe key's monthly cloud seconds would be exceededRaise the quota — see Limits & quotas
403token_quota_exceededThe key's monthly spend ceiling is reachedRaise the ceiling — see Limits & quotas
403insufficient_tokensThe balance cannot cover this measurementTop up — see Pricing
429rate_limitedThe key's requests-per-minute limit is reachedBack off and retry — see Limits & quotas
503cloud_unavailableCloud processing is temporarily unavailableRetry later. GET /api/v1/status reports availability

Errors the SDK reports during the measurement are listed in Callbacks & errors. The full API list is in Errors.