node server.mjs
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import { createEngineAdmin, createTokenSource, createEngineProxy, ownsAll } from '@neurologyca/capture-server'
import { toNodeListener } from '@neurologyca/capture-server/node'
const { ENGINE_BASE, ENGINE_API_KEY, PORT = '3000' } = process.env
if (!ENGINE_BASE || !ENGINE_API_KEY) throw new Error('Set ENGINE_BASE (your environment\'s Engine URL, in your kit) and ENGINE_API_KEY')
// 1. One person and their enrolment. In your app: your signed-in user, and the pair saved in your database.
const admin = createEngineAdmin({ baseUrl: ENGINE_BASE, apiKey: ENGINE_API_KEY })
const measurement = (await admin.listProtocolLibrary()).find((p) => p.name === 'Measurement' && p.status === 'published')
if (!measurement) {
console.error('Your environment does not offer the Measurement protocol yet. Ask Neurologyca, or use the cURL tab with another protocol.')
process.exit(1)
}
const { externalId } = await admin.createUser({ name: 'quickstart-user' }) // the package generates an opaque UUID
const { userProtocolId } = await admin.enrol(externalId, measurement.pid)
const next = await admin.getNextPosition(userProtocolId)
if (!next) throw new Error('The enrolment has no position to capture')
const pair = { userProtocolId, protocolMechanicId: next.protocolMechanicId }
console.log(`Person ${externalId} enrolled in Measurement. Each start creates one: delete it when you are done (irreversible), with ENGINE_BASE and ENGINE_API_KEY set as for server.mjs:
node --input-type=module -e "import { createEngineAdmin } from '@neurologyca/capture-server'; await createEngineAdmin({ baseUrl: process.env.ENGINE_BASE, apiKey: process.env.ENGINE_API_KEY }).deleteUser('${externalId}')"`)
// 2. The proxy: the browser calls /engine/* with no token and the proxy adds yours. ownsAll checks every id a route
// carries: here, only this person's enrolment.
const tokens = createTokenSource({ baseUrl: ENGINE_BASE, apiKey: ENGINE_API_KEY })
const engine = toNodeListener(createEngineProxy({
baseUrl: ENGINE_BASE,
tokens,
mountPath: '/engine',
authorize: async (_req, route) => ownsAll(route, {
userProtocol: async (up) => up === pair.userProtocolId,
user: async (userId) => userId === externalId,
}),
}))
// 3. The page, its bundle and the pair.
const files = new Map([['/', ['index.html', 'text/html']], ['/page.js', ['public/page.js', 'text/javascript']]])
const server = http.createServer(async (req, res) => {
const url = req.url ?? '/'
if (url.startsWith('/engine/')) return engine(req, res) // before any body parser
if (url === '/pair') {
res.writeHead(200, { 'content-type': 'application/json' })
return res.end(JSON.stringify(pair))
}
const file = files.get(url)
if (!file) { res.writeHead(404); return res.end() }
res.writeHead(200, { 'content-type': file[1] })
res.end(await readFile(new URL(file[0], import.meta.url)))
})
server.listen(Number(PORT), () => {
const { port } = /** @type {import('node:net').AddressInfo} */ (server.address())
console.log(`Open http://localhost:${port}`)
})
```
### 4. Your page [Section titled “4. Your page”](#4-your-page) index.html
```html
Quickstart: Measurement with the SDK
```
page.js
```js
// Your page: a short Measurement capture with the SDK, from the camera or from a video file of yours.
// Bundle it for the browser: npx esbuild page.js --bundle --format=esm --outfile=public/page.js
import { createProtocolClient, classifyMediaError } from '@neurologyca/capture'
const out = /** @type {HTMLPreElement} */ (document.querySelector('#out'))
const video = /** @type {HTMLVideoElement} */ (document.querySelector('#video'))
const picker = /** @type {HTMLInputElement} */ (document.querySelector('#file'))
const cancel = /** @type {HTMLButtonElement} */ (document.querySelector('#cancel'))
// One client for the whole page, created when it loads and reused for every capture.
const client = createProtocolClient({
baseUrl: '/engine', // your backend's proxy: the browser carries no token
keepPrepared: true, // what prepare() loaded survives a capture: measure again without preparing in between
taxonomy: { contextId: 'measurement' }, // Measurement: any value; required by the SDK, though Measurement does not send it (0.29.0)
startup: { includeUserAgent: false }, // the startup report stays in the SDK: no user agent, and nothing is sent anywhere
// The SDK's own words for each startup stage of a capture (userMessage), ready to show.
onStartupStage: (e) => { if (e.kind === 'capture' && e.userMessage) out.textContent = e.userMessage },
onWarning: (w) => console.warn(w.code, w.message),
onError: (e) => { out.textContent = `${e.code}: ${e.message}` }, // a failure mid-capture (a 409, a lost session): its cause
})
// Prepare once, before the first click, so Start does not wait for the face model. It never calls Engine and asks for no
// permission. With keepPrepared the models stay between captures: no prepare() after one. It does not reject on a failed
// load (the capture then loads it itself). The SDK releases what it kept when the page goes away (pagehide): you do not
// listen for it. Call client.release() only when you drop the client, or between one person and the next.
const prepare = () => { client.prepare().catch((e) => console.warn(e.code, e.message)) }
prepare()
document.querySelector('#start')?.addEventListener('click', async () => {
out.textContent = 'Capturing…'
// Cancel: before the capture starts, the signal cuts the start; once it runs, session.abort() ends it.
const stopper = new AbortController()
/** @type {Awaited> | null} */
let session = null
cancel.disabled = false
cancel.onclick = () => { stopper.abort(); void session?.abort().catch(() => { /* already over */ }) }
try {
// The pair comes from your backend (it enrolled the person), never from the browser.
const { userProtocolId, protocolMechanicId } = await (await fetch('/pair')).json()
const file = picker.files?.[0]
video.srcObject = null // an earlier camera run left its stream here, and it would hide your video
if (file) video.src = URL.createObjectURL(file) // a video of yours: give it its src BEFORE capturing
session = await client.captureProtocol({
captureId: crypto.randomUUID(), // yours: it joins this capture's warnings and startup report
userProtocolId,
protocolMechanicId,
source: file ? { type: 'video', el: video } : { type: 'webcam' },
signal: stopper.signal,
// Your video: play it now (muted, so it plays on its own). The camera: show the SDK's preview in your