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
- Your backend creates a session. It calls
POST /sdk/v1/cloud/sessions, signed with your API key. - Your backend passes the whole
dataobject to your app. It holds the session token and the parameters the SDK needs. - The Web SDK runs the measurement. Pass the object as
sessiontogether withmode: 'cloud'. Live values arrive while the person measures. - Neccessory stores the result and delivers it. The SDK fires
onResultwith the stored result. Your backend reads the same result withGET /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
| Field | Type | Default | Description |
|---|---|---|---|
platform | "web" | "ios" | "android" | required | Where the measurement runs. Recorded on the session |
consent | true | required | Confirms that the person agreed to cloud processing. See Consent |
durationSec | integer | 60 | Measurement length, 20–180 seconds. The SDK stops and delivers the result when it is reached |
features | string[] | every set the key allows | Metric sets to compute: hrv, bp, spo2, emotion, gaze. [] computes the core metrics only. Unknown names are ignored |
userRef | string | — | 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": { … }
}
}| Field | Type | Description |
|---|---|---|
sessionId | string | Session ID, cj_…. Also the job ID you read the result with |
sessionToken | string | Authorizes this one measurement |
wsUrl | string | null | Address the SDK connects to. null with a test key |
expiresAt | number | When the token expires, epoch milliseconds |
maxDurationSec | number | Granted measurement length, seconds |
features | string[] | Metric sets this session computes and bills |
frameSpec | object | Parameters for the SDK — pass through unchanged |
test | true | Present 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
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.
| Status | Meaning | Final |
|---|---|---|
pending | Session created, measurement not started. Still pending after expiresAt means it never started; it costs nothing | — |
running | Measurement in progress | No |
completed | Done. measurement holds the result, measurementId its ID | Yes |
failed | No result. error.code says why | Yes |
aborted | Ended early — the person left, or the connection dropped. See below | Yes |
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:
| HTTP | Code | Cause | Fix |
|---|---|---|---|
| 400 | invalid_platform | platform is missing or not web, ios or android | Send a valid platform |
| 400 | consent_required | consent is not true | Collect consent, then send consent: true |
| 400 | invalid_duration | durationSec is outside 20–180 | Send a value from 20 to 180 |
| 400 | validation_error | userRef has an invalid format | Use 1–64 letters, digits and . _ : @ - |
| 401 | unauthorized | Invalid signature, or the key is disabled or expired | Check your signing code; the exact reason is in the usage log |
| 403 | feature_not_allowed | A requested metric set is not enabled on the key | Enable it on the key or remove it from features |
| 403 | quota_exceeded | The key's monthly cloud seconds would be exceeded | Raise the quota — see Limits & quotas |
| 403 | token_quota_exceeded | The key's monthly spend ceiling is reached | Raise the ceiling — see Limits & quotas |
| 403 | insufficient_tokens | The balance cannot cover this measurement | Top up — see Pricing |
| 429 | rate_limited | The key's requests-per-minute limit is reached | Back off and retry — see Limits & quotas |
| 503 | cloud_unavailable | Cloud processing is temporarily unavailable | Retry 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.