# Node / TypeScript SDK

> The official sightradar package for Node, Deno and browsers. No runtime dependencies, built-in fetch, full TypeScript types.

Source: https://sightradar.com/docs/sdks/node

```bash
npm install sightradar
```

Published on npm as [sightradar](https://www.npmjs.com/package/sightradar). MIT licensed. Uses the built-in `fetch` (Node 18 or newer, Deno, browsers) and ships full types.

**Keep keys server-side.**
The package runs in a browser, but an API key spends your credits. Call it from your backend and expose your own endpoints to the client. See [Authentication](/docs/authentication#keep-keys-off-the-client).

## Authenticate

```ts
import { SightRadar } from "sightradar";

const sr = new SightRadar({ apiKey: "frs_..." }); // or new SightRadar() with SIGHTRADAR_API_KEY
```

## Core workflow

```ts
// 1. Create a collection to hold faces.
await sr.createCollection("event-2026");

// 2. Index faces from photos (URL, connected-storage key, or an uploaded file).
await sr.index("event-2026", { url: "https://example.com/group.jpg" });
await sr.index("event-2026", { file: buffer, filename: "photo.jpg", photoId: "img-42" });

// 3. Search the collection with one selfie.
const result = await sr.search("event-2026", { url: "https://example.com/selfie.jpg" });
for (const m of result.matches) console.log(m.photo_id, m.score);
```

## Stateless operations

```ts
// Detect and quality-gate faces in an image. Nothing is stored.
const det = await sr.detect({ url: "https://example.com/photo.jpg" });
console.log(det.detected_face_count, det.gated_face_count);

// 1:1 verification between two faces.
const cmp = await sr.compare({
  sourceUrl: "https://example.com/a.jpg",
  targetUrl: "https://example.com/b.jpg",
});
console.log(cmp.match, cmp.similarity);
```

## Selfies and search by id

```ts
const reg = await sr.registerSelfie("event-2026", { userId: "u_42", url: "https://example.com/selfie.jpg" }); // userId is required
const hits = await sr.searchById("event-2026", reg.point_id!, { limit: 50 });
```

## Deleting and restoring

```ts
const receipt = await sr.deleteCollection("event-2026");          // soft: receipt.restorable === true
await sr.restoreCollection("event-2026");
await sr.deleteCollection("event-2026", { compliance: true });   // audited erasure, not restorable
const st = await sr.deletionStatus("event-2026");                // st.phase === "completed" && st.verified_zero
await sr.deletePhoto("event-2026", "img-42");                    // one photo's faces; restorePhoto undoes a soft delete
```

## Batches and webhooks

```ts
const wh = await sr.registerWebhook({ url: "https://your.app/webhooks/sightradar" }); // wh.secret is returned once
const batch = await sr.submitBatch({
  collectionId: "event-2026",
  op: "index",
  photos: [{ url: "https://example.com/1.jpg", external_id: "img-1" }],
  webhookEndpointId: wh.webhook_endpoint_id,
});
const status = await sr.getBatch(batch.batch_id);         // succeeded / failed / pending counts
const page = await sr.getBatchPhotos(batch.batch_id);     // per-photo results, keyset paginated

import { verifyWebhookSignature } from "sightradar";
const ok = verifyWebhookSignature({
  secret: storedSecret,
  timestamp: req.headers["x-sightradar-timestamp"],
  signature: req.headers["x-sightradar-signature"],
  body: rawBody,
});
```

## Retries and idempotency

Retries are off by default. `new SightRadar({ maxRetries: 3 })` retries `429`, `502` and `503` with backoff, but only for GETs and for calls that carry an `idempotencyKey`, so a retry can never double-charge. Pass `idempotencyKey` on `index` and `registerSelfie`.

## Account

```ts
console.log((await sr.wallet()).balance_credits);
console.log(await sr.usage(30));
```

## Image inputs

Index, search, detect and register-selfie accept exactly one image source:

| Field    | Meaning                                                                          |
| -------- | -------------------------------------------------------------------------------- |
| `url`    | a public image URL                                                               |
| `gcsKey` | an object key in a storage bucket connected to your account                      |
| `file`   | a `Blob`/`File` (browser) or `Buffer`/`Uint8Array` (Node), uploaded as multipart |

`search` additionally accepts `embedding` (a 512-number array). `registerSelfie` also requires `userId` and accepts `selfieId`.

## Errors

Every non-2xx response rejects with a typed error:

```ts
import { NotFoundError, AuthenticationError } from "sightradar";

try {
  await sr.describeCollection("missing");
} catch (e) {
  if (e instanceof NotFoundError) console.log(e.statusCode, e.message);
}
```

Error classes: `SightRadarError` (base), `AuthenticationError` (401), `InsufficientCreditsError` (402), `NotFoundError` (404), `RateLimitError` (429). See [errors and status codes](/docs/errors).

## Method reference

| Method                                                                                                   | Endpoint                                       |
| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `createCollection`, `listCollections`, `describeCollection`, `collectionMetrics`                         | [Collections](/docs/api/collections)           |
| `deleteCollection(id, { immediate, compliance, intent })`, `restoreCollection(id)`, `deletionStatus(id)` | collection delete lifecycle                    |
| `deletePhoto(id, photoId, { immediate, compliance })`, `restorePhoto(id, photoId)`                       | per-photo faceprints                           |
| `index`                                                                                                  | `POST /v1/collections/{id}/index`              |
| `search`                                                                                                 | `POST /v1/collections/{id}/search`             |
| `searchById`                                                                                             | `POST /v1/collections/{id}/search-by-id`       |
| `registerSelfie`                                                                                         | `POST /v1/collections/{id}/selfies`            |
| `detect`                                                                                                 | `POST /v1/detect`                              |
| `compare`                                                                                                | `POST /v1/compare`                             |
| `submitBatch`, `getBatch`, `getBatchPhotos`, `listBatches`                                               | [Batch](/docs/api/batch)                       |
| `registerWebhook`, `listWebhooks`, `deleteWebhook`, `verifyWebhookSignature`                             | [Webhooks](/docs/api/webhooks)                 |
| `wallet`, `usage`                                                                                        | [Wallet and usage](/docs/api/wallet-and-usage) |

Every response type is exported (`SearchResult`, `Match` with `score` and a deprecated `similarity` alias, `IndexResult`, `SelfieResult`, `DeletionReceipt`, `DeletionStatus`, `Batch`, `BatchPhotosPage`, `Webhook`, and more). Requires Node 18 or newer; current release 1.1.0.
