Proxy by hand
The 13 routes the browser SDK calls, forwarded to Engine by a proxy of your own (Express or nginx), for when you do not use capture-server.
With @neurologyca/capture-server, the proxy is a few lines: Your backend. This page is for a backend without it: your page gets a token from your backend (getToken) and your proxy forwards the 13 routes.
Why a proxy in your origin
Section titled “Why a proxy in your origin”The browser SDK never calls Engine directly: it calls a path in your origin (/engine by default) and your server forwards the request.
- Engine accepts browsers only from the origins Neurologyca configures. A proxy in your origin does not depend on that list.
- Your server decides which routes the browser can reach, and for which users.
- The token travels one way: from your token endpoint to the page, and from the page to your proxy.
Forward the token, or inject it
Section titled “Forward the token, or inject it”The SDK gets a token from your token endpoint and sends it as Authorization: Bearer … on every request. The recommended proxy forwards that header, with an allowlist of routes. That is what both examples below do.
The alternative is to inject the token in the proxy: your token endpoint returns an opaque value of your own session, and the proxy checks it and replaces it with the real token. The SDK does not read the token, so it works the same; the Engine token then never reaches the browser.
Either way, closing routes reduces what a page can do, but it is not a security boundary: a token in the browser can be used against Engine directly. Your backend decides who can capture what.
The 13 routes
Section titled “The 13 routes”These are all the routes the SDK calls. {up} is the userProtocolId, {pm} the protocolMechanicId and {externalId} the user’s id.
| # | Method | Route | What for |
|---|---|---|---|
| 1 | GET | /user-protocols/{up} |
State: next position, progress, baseline warning, availability |
| 2 | GET | /user-protocols/{up}/mechanics/{pm} |
The plan of steps of the position |
| 3 | GET | /user-protocols/{up}/{pm}/sessions |
Earlier attempts; polled every 3 seconds while closing |
| 4 | GET | /users/{externalId}/baseline |
Only with getBaselineInfo() |
| 5 | POST | /users/{externalId}/baseline |
Only with captureBaseline() |
| 6 | GET | /stream/{up} |
Live events, during the whole session; reopened if it drops |
| 7 | POST | /user-protocols/{up}/{pm}/context |
The taxonomy, once, before the first frame |
| 8 | PATCH | /user-protocols/{up}/{pm}/query |
Only if you configure query |
| 9 | POST | /process-kpn-emo |
Every batch and the Final of each step |
| 10 | GET | /results/{up}/{pm} |
When the position closes, and retrieveResults() |
| 11 | POST | /analyze/stream |
The interpretation, as a stream with progress by phase; the SDK opens it only with interpretation: 'stream' (since 0.38.0) |
| 12 | POST | /analyze |
The interpretation, as a fallback, and client.analyze() |
| 13 | POST | /user-protocols/{up}/{pm}/cancel |
abort() before the last Final; frees the position. Since 0.29.0, a recording or a replay adds ?captureId= to cancel only its own capture: let that query reach Engine (both examples below forward it) |
In our test, a live capture used 8 of them: 1, 2, 3, 6, 7, 9, 10 and 11. The others depend on the options and on what happens.
Routes you must not open
Section titled “Routes you must not open”Your backend calls these with your API key, never the browser: POST /token, /users (creating, listing, updating or deleting people), POST /user-protocols (enrolling), /catalog/* and anything else not in the table. Anything outside the 13 routes should answer 404.
Headers
Section titled “Headers”- To Engine:
Authorization,Content-Type,AcceptandX-Correlation-Id. The SDK sendsX-Correlation-Idonly with/analyzeand/analyze/stream. - Back to the browser:
Content-Type,Cache-Control,X-Correlation-Id(only if Engine sent one),WWW-Authenticate(a401has an empty body; this header is the only hint) andRetry-After(the wait of a429or of a202 ANALYSIS_IN_PROGRESS; without it the SDK falls back to its default). Engine does not returnX-Correlation-Idtoday (measured), so do not rely on it for support: use the one your SDK sent. - Body size: from SDK 0.34.0 a live batch carries at most 300 frames and at most 3 MB of frames, the
Finalincluded. With a camera, a frame is about 19.7 KB of JSON from 0.35.0, so a 3 MB batch holds about 150 frames. Allow at least 4.5 MB. An SDK before 0.34.0 cuts only by count, up to about 9.3 MB per batch: in front of it, allow at least 10 MB (the example below allows 10 MiB, like DevLab’s own gateway). - Serverless functions: a Next.js Pages Router API route (
pages/api) caps the body at 1 MB by default, below a batch, so it answers413until you raise its limit; an App Router route handler (app/…/route.js) has no body parser, so the proxy there applies only its ownmaxBodyBytesand your host’s cap. A Vercel function caps it at 4.5 MB: enough for the current SDK, not for one before 0.34.0. A413is final at the first try (E_UPLOAD_FAILED). The proxy also keeps the event stream open for the whole capture, so prefer a long-running runtime (a container, a VPS, Cloud Run). Behind Firebase Hosting (a rewrite to Cloud Run or Cloud Functions), every request is cut at 60 s and only the__sessioncookie gets through: serve the page and the proxy on the same origin, outside Hosting; a proxy on another origin needscredentials: 'include'in the client (A proxy on another origin; the pitfall). reAnalyze: remove it from the bodies of/analyzeand/analyze/stream, so a page cannot force a new interpretation. It is hygiene, not protection.- Clock: the SDK reads the
Dateheader to know when a position is available. Keep your server’s clock in sync.
If your page and your proxy are in different origins, also send Access-Control-Expose-Headers: X-Correlation-Id, Retry-After and allow authorization, content-type, x-correlation-id. Without Retry-After exposed, the page cannot read the wait of a 429 or of a 202 ANALYSIS_IN_PROGRESS and falls back to its default (createEngineProxy of capture-server exposes it since 0.20.1).
A proxy on another origin
Section titled “A proxy on another origin”Best: the page and the proxy on the same origin (a rewrite, or the proxy under your own domain); then nothing below is needed. When the proxy lives on another origin and decides by your session cookie (createEngineProxy with authorize), it takes two halves, since @neurologyca/capture 0.45.0:
- In the page:
credentials: 'include'increateProtocolClientandcreateRecordingClient(also inurlTokenProvider(url, { credentials: 'include' })if your token endpoint is on that origin;uploadRecordingkeeps its owncredentials). It applies to every request of the client to the proxy, the event stream and the streamed interpretation included. Absent, the browser’s default ('same-origin') applies and the cookie does not travel:authorizesees no session and the proxy answers403. Any other value throwsE_UNKNOWN_OPTIONwhen the client is built. With'include', thetoken.missingwarning no longer comes out for an absolutebaseUrlon another origin. - In the proxy:
cors: { origins: ['https://app.example.com'], credentials: true }: your exact origin (never"*"or"null") andaccess-control-allow-credentials: true. Usecapture-server0.20.1 or later, which also exposesRetry-Afterto that page. - The cookie: the browser only sends the cookies valid for the proxy’s host. On a subdomain of the same site (page on
app.example.com, proxy onapi.example.com), give it aDomainthat covers both (Domain=example.com);SameSite=Laxis enough. On another site (for example a*.run.appaddress) it is a third-party cookie (SameSite=None; Secure), which Safari (also on iOS) blocks by default, and other browsers in private mode: there, serve the proxy under your own domain instead. - No
getTokenbehind a proxy that puts its own token: from another origin, theauthorizationheader does not pass the proxy’s preflight.
Only your site’s session travels: Engine’s key and token stay on your server.
Server-Sent Events
Section titled “Server-Sent Events”/stream/{up} and /analyze/stream are event streams. The proxy must pass every event as it arrives:
- no buffering (
proxy_buffering offin nginx; pipe the body in Node, never read it whole); - no compression middleware on
text/event-stream; - no total timeout on the two streams.
/stream/{up}sends a: pingevery 30 seconds;/analyze/streamcan stay silent for close to a minute before its first event.
Example: Node with Express
Section titled “Example: Node with Express”Express 5 and Node 18 or later. Mount it with app.use('/engine', engineProxy()), behind your own authentication:
// Express 5. Mount it with app.use('/engine', engineProxy()). Put your own authentication in front.import express from 'express'
const ENGINE = process.env.ENGINE_BASEconst ID = '[0-9a-fA-F-]{36}'const USER = '[^/]+'// The 13 routes the browser SDK calls, by method. Everything else answers 404.const ROUTES = [ ['GET', `/user-protocols/${ID}`], ['GET', `/user-protocols/${ID}/mechanics/${ID}`], ['GET', `/user-protocols/${ID}/${ID}/sessions`], ['GET', `/users/${USER}/baseline`], ['POST', `/users/${USER}/baseline`], ['GET', `/stream/${ID}`], ['POST', `/user-protocols/${ID}/${ID}/context`], ['PATCH', `/user-protocols/${ID}/${ID}/query`], ['POST', '/process-kpn-emo'], ['GET', `/results/${ID}/${ID}`], ['POST', '/analyze/stream'], ['POST', '/analyze'], ['POST', `/user-protocols/${ID}/${ID}/cancel`],].map(([method, path]) => ({ method, re: new RegExp(`^${path}$`) }))const allowed = (method, path) => ROUTES.some((r) => r.method === method && r.re.test(path))const isStream = (path) => path === '/analyze/stream' || path.startsWith('/stream/')
export function engineProxy({ engine = ENGINE, timeoutMs = 300_000 } = {}) { const router = express.Router() router.use(express.raw({ type: '*/*', limit: '10mb' })) router.use(async (req, res) => { const path = req.path if (!allowed(req.method, path)) return res.status(404).json({ error: 'route not allowed' }) let body = ['GET', 'HEAD'].includes(req.method) ? undefined : req.body if (path === '/analyze' || path === '/analyze/stream') { // The browser must not force a new interpretation: drop reAnalyze. try { const { re_analyze, reAnalyze, ...safe } = JSON.parse(body.toString('utf8')) body = JSON.stringify(safe) } catch { return res.status(400).json({ error: 'invalid JSON' }) } } const ctrl = new AbortController() const timer = isStream(path) ? null : setTimeout(() => ctrl.abort(), timeoutMs) res.on('close', () => ctrl.abort()) try { const headers = { authorization: req.get('authorization') ?? '', accept: req.get('accept') ?? '*/*' } if (body !== undefined) headers['content-type'] = req.get('content-type') ?? 'application/json' if (req.get('x-correlation-id')) headers['x-correlation-id'] = req.get('x-correlation-id') const query = req.originalUrl.includes('?') ? req.originalUrl.slice(req.originalUrl.indexOf('?')) : '' const r = await fetch(`${engine}${path}${query}`, { method: req.method, headers, body, signal: ctrl.signal }) res.status(r.status) for (const k of ['content-type', 'cache-control', 'x-correlation-id', 'www-authenticate', 'retry-after']) { const v = r.headers.get(k) if (v) res.setHeader(k, v) } if (isStream(path)) res.flushHeaders() // Server-Sent Events: no buffering if (r.body) for await (const chunk of r.body) res.write(chunk) res.end() } catch { if (!res.headersSent) res.status(502).json({ error: 'engine unreachable' }) else res.end() } finally { if (timer) clearTimeout(timer) } }) // A batch over 10 MB answers 413 instead of an HTML error page. router.use((err, _req, res, next) => (err?.type === 'entity.too.large' ? res.status(413).json({ error: 'body too large' }) : next(err))) return router}The code answers 404 outside the 13 routes, removes reAnalyze, forwards X-Correlation-Id to Engine and back only if Engine returns one (it does not today), passes the event streams without buffering, and answers 413 above 10 MB.
Example: nginx
Section titled “Example: nginx”nginx forwards the 13 routes with the same rules. Replace <engine host> with the host of the Engine base URL Neurologyca gives you:
# http { } level: the 13 routes the browser SDK calls, by method.map "$request_method $uri" $engine_route_ok { default 0; "~^GET /engine/user-protocols/[0-9a-fA-F-]{36}$" 1; "~^GET /engine/user-protocols/[0-9a-fA-F-]{36}/mechanics/[0-9a-fA-F-]{36}$" 1; "~^GET /engine/user-protocols/[0-9a-fA-F-]{36}/[0-9a-fA-F-]{36}/sessions$" 1; "~^(GET|POST) /engine/users/[^/]+/baseline$" 1; "~^GET /engine/stream/[0-9a-fA-F-]{36}$" 1; "~^POST /engine/user-protocols/[0-9a-fA-F-]{36}/[0-9a-fA-F-]{36}/(context|cancel)$" 1; "~^PATCH /engine/user-protocols/[0-9a-fA-F-]{36}/[0-9a-fA-F-]{36}/query$" 1; "~^POST /engine/process-kpn-emo$" 1; "~^GET /engine/results/[0-9a-fA-F-]{36}/[0-9a-fA-F-]{36}$" 1; "~^POST /engine/analyze(/stream)?$" 1;}
# server { } levellocation /engine/ { if ($engine_route_ok = 0) { return 404; } proxy_pass https://<engine host>/; proxy_set_header Host <engine host>; proxy_ssl_server_name on; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; # /stream and /analyze/stream are Server-Sent Events client_max_body_size 10m; # batches of frames are large proxy_read_timeout 300s; proxy_send_timeout 300s;}nginx without scripting cannot remove reAnalyze from a body: if you need that, put a small handler in front of /analyze and /analyze/stream.
Check that nothing is missing
Section titled “Check that nothing is missing”Run one capture with the browser’s network tab open:
- every request to
/engine/…answers2xx(or the401of an expired token, which the SDK renews once); - a
404with your proxy’s own body (route not allowedin the Express example) means a route the SDK needs is closed; - the two event streams show events arriving during the capture, not all at the end.
Timeouts for each layer are in Timeouts.