NeccessoryNeccessory

Quickstart

Take your first measurement in the browser in about ten minutes — a key, a small server and one HTML page.

This guide builds a working cloud measurement: your server creates a session with your key, and a web page runs the measurement with the Web SDK. You need Node.js 18 or later and a computer with a webcam.

Create a key

Sign in to the console, open Keys and click New key. Keep the default mode, Cloud, and create the key.

Copy the secret now — it is shown only once. Store the key ID and the secret as environment variables on your server:

export NECCESSORY_KEY_ID=nk_live_...
export NECCESSORY_SECRET=nk_live_...

New organizations receive 1,500,000 free tokens ($15) — see Pricing. Key modes and settings are described in API keys.

Add a signing helper

Every API request is signed with your secret. Create neccessory.mjs:

neccessory.mjs
import crypto from 'node:crypto';

const BASE_URL = 'https://neccessory.com';
const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');

export async function neccessory(method, path, body) {
  const payload = body === undefined ? '' : JSON.stringify(body);
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const nonce = crypto.randomBytes(16).toString('base64url');
  const canonical = ['NCS1', method, path.split('?')[0], timestamp, nonce, sha256(payload)].join('\n');
  const signature = crypto
    .createHmac('sha256', sha256(process.env.NECCESSORY_SECRET))
    .update(canonical)
    .digest('base64');

  const response = await fetch(BASE_URL + path, {
    method,
    headers: {
      'content-type': 'application/json',
      'x-key-id': process.env.NECCESSORY_KEY_ID,
      'x-timestamp': timestamp,
      'x-nonce': nonce,
      'x-signature': signature,
    },
    body: payload || undefined,
  });
  const json = await response.json();
  if (!json.ok) {
    throw Object.assign(new Error(json.error.message), { code: json.error.code });
  }
  return json.data;
}

Check that the key works:

node --input-type=module -e "import { neccessory } from './neccessory.mjs'; console.log(await neccessory('POST', '/sdk/v1/auth/test'))"

The response shows your key ID, mode: 'cloud' and the token balance. If you get unauthorized, see Authentication.

Create sessions on your server

The browser never sees your secret. Instead, your server creates a short-lived measurement session and hands it to the page. Install Express and create server.mjs:

npm install express
server.mjs
import express from 'express';
import { neccessory } from './neccessory.mjs';

const app = express();
app.use(express.static('public'));

app.post('/api/measurement-session', async (req, res) => {
  try {
    const session = await neccessory('POST', '/sdk/v1/cloud/sessions', {
      platform: 'web',
      durationSec: 60,
      consent: true,
    });
    res.json(session);
  } catch (error) {
    res.status(502).json({ code: error.code, message: error.message });
  }
});

app.listen(3000, () => console.log('http://localhost:3000'));

consent: true confirms that the person agreed to have their face video processed. In your product, ask for that consent before you create the session — see Data & privacy.

Run the measurement in the page

Create public/index.html. The page loads the Web SDK from neccessory.com, gets a session from your server and starts the measurement:

public/index.html
<!doctype html>
<html lang="en">
  <body>
    <video id="camera" playsinline muted width="480"></video>
    <p id="status">Press Start and look at the camera.</p>
    <p>Heart rate: <strong id="hr">—</strong> bpm</p>
    <button id="start">Start</button>

    <script src="https://neccessory.com/neccessory-sdk/neccessory-sdk.js"></script>
    <script>
      const statusEl = document.getElementById('status');
      const hrEl = document.getElementById('hr');

      document.getElementById('start').addEventListener('click', async () => {
        const session = await fetch('/api/measurement-session', { method: 'POST' })
          .then((response) => response.json());

        const measurement = neccessory.createMeasurement({
          videoEl: document.getElementById('camera'),
          mode: 'cloud',
          session,
          assetOrigin: 'https://neccessory.com',
        });

        measurement
          .onStage((stage) => { statusEl.textContent = stage; })
          .onRealtime((update) => { hrEl.textContent = update.heartRate ?? '—'; })
          .onResult((result) => {
            statusEl.textContent = result.quality.usable
              ? `Done: ${result.cardiac.heartRate.value} bpm, stress index ${result.stress.index}`
              : 'The signal was too weak. Sit still in even light and try again.';
          })
          .onError((error) => { statusEl.textContent = `${error.code}: ${error.message}`; });

        await measurement.start();
      });
    </script>
  </body>
</html>

assetOrigin tells the SDK to load its files from neccessory.com. It is required while the page runs on localhost; on your own domain you can leave it out.

Start the server and open http://localhost:3000:

node server.mjs

Press Start, allow camera access and sit still facing the camera. The live heart rate appears after about 10 seconds; the result arrives when the 60-second session ends.

Find the result

The result is already stored under your key — nothing to submit. Open Measurements in the console to see it, or read it from your server with the sessionId of the session:

const job = await neccessory('GET', `/sdk/v1/cloud/jobs/${sessionId}`);
console.log(job.status, job.measurement);

To have results pushed to your server instead, set up webhooks.

Before you go live

  • Ask for the person's consent before creating a session, and store it.
  • Create sessions only for your signed-in users, and pass your own user ID as userRef.
  • Show metrics only when result.quality.usable is true — see Signal quality.
  • Trust results your server reads from the API, not values posted by the browser — see Attested results.
  • Add the Neccessory origins to your Content Security Policy — see Requirements.
  • Set a monthly spend cap on the key and top up tokens in Console → Spend — see Pricing.

Next steps