Skip to the documentation
All documentation pages ↓

JavaScript SDK

npm install nexguard: send events, verify webhooks, sign requests, read incidents.

Install

The package is nexguard on npm. It has no dependencies — it uses the global fetch and node:crypto — and needs Node.js 18 or later. TypeScript types are included. Keep keys on the server, never in browser or mobile code.

Shell
npm install nexguard

Send events

JavaScript
import { NexGuardClient, EventType } from "nexguard";

const client = new NexGuardClient({
  apiKey: process.env.NEXGUARD_API_KEY,               // ngk_…
  signingSecret: process.env.NEXGUARD_SIGNING_SECRET, // optional until the key enforces signing
  baseUrl: "https://securiteagi.com",  // the default
  timeoutMs: 5000,                    // per attempt
  maxRetries: 3,
});

await client.send({
  eventId: "login-8f21",                  // stable: your own record id
  eventType: EventType.LOGIN_SUCCESS,
  source: "portal-web",
  subjectId: "user-42",                   // subjectType defaults to "user"
  payload: { ip: "203.0.113.7", device_id: "d-1" },
});

await client.sendBatch(events);           // 1 to 100 events, all-or-nothing
  • Methods. send(event) posts to POST /api/v1/events; sendBatch(events) posts 1 to 100 events to POST /api/v1/events/batch and refuses an empty or larger batch before any request; sendQuietly(event) resolves true or false instead of rejecting on a delivery failure.
  • Retries. Network errors, timeouts, 429 (Retry-After is the minimum wait) and 5xx are retried with exponential backoff and jitter, up to maxRetries times. Other 4xx responses are never retried. Each attempt has a fresh timestamp and nonce but the same body and eventId, so a retry cannot double-count.
  • Forbidden fields. Passwords, tokens, card numbers and the like are refused before any request, with ForbiddenFieldError; sendQuietly does not swallow it. The list is the one in Sending events.
  • Plain HTTP to anything but a local address is refused when the client is constructed.
JavaScript
import { NexGuardError, ForbiddenFieldError } from "nexguard";

try {
  await client.sendBatch(events);
} catch (error) {
  if (error instanceof ForbiddenFieldError) throw error;  // a bug in the integration
  if (error instanceof NexGuardError) {
    // error.status is undefined if NexGuard never answered.
    // error.requestId is the X-Request-ID to quote to support.
    console.error(error.status, error.requestId, error.retryable);
  }
}

Verify a webhook

verifyWebhook checks the X-NexGuard-Signature, X-NexGuard-Timestamp and X-NexGuard-Nonce headers of a webhook against your signing secret. It throws SignatureError when the signature does not match, the timestamp is outside the 300-second window, or seenNonce reports a replay. Pass the raw body, before JSON parsing.

JavaScript
import express from "express";
import { verifyWebhook, SignatureError } from "nexguard";

const app = express();
const seen = new Map(); // nonce -> time; use a shared store with several servers

app.post("/nexguard/webhook", express.raw({ type: "application/json" }), (req, res) => {
  try {
    verifyWebhook({
      secret: process.env.NEXGUARD_WEBHOOK_SECRET,
      headers: req.headers,
      body: req.body,                       // the raw Buffer, not parsed JSON
      seenNonce: (nonce) => {
        const was = seen.has(nonce);
        seen.set(nonce, Date.now());
        return was;
      },
    });
  } catch (error) {
    if (error instanceof SignatureError) return res.sendStatus(401);
    throw error;
  }
  const notification = JSON.parse(req.body);
  // ...open a ticket, page somebody...
  res.sendStatus(204);
});

Sign a request yourself

For a key that enforces signing and a client that is not NexGuardClient, signedHeaders(secret, body) returns X-Timestamp, X-Nonce and X-Signature for exactly the bytes you send. The scheme is described in Authentication.

JavaScript
import { signedHeaders } from "nexguard";

const body = JSON.stringify(event);
await fetch("https://securiteagi.com/api/v1/events", {
  method: "POST",
  headers: {
    "X-API-Key": process.env.NEXGUARD_API_KEY,
    "Content-Type": "application/json",
    ...signedHeaders(process.env.NEXGUARD_SIGNING_SECRET, body),
  },
  body,
});

Reading incidents

Reading is a separate, read-only key with its own scopes. The SDK does not wrap it; a plain fetch is enough, and the response shapes are in Reading data.

JavaScript
// Reading is plain HTTP: the SDK sends events, it has no read methods.
// The key needs the incidents:read scope.
const response = await fetch(
  "https://securiteagi.com/api/v1/public/incidents?status=open&limit=25",
  { headers: { "X-API-Key": process.env.NEXGUARD_API_KEY } },
);
if (response.status === 429) {
  const wait = Number(response.headers.get("Retry-After") ?? 60);
  // wait, then retry
}
if (!response.ok) {
  const problem = await response.json();   // application/problem+json
  throw new Error(`NexGuard ${problem.status}: ${problem.detail} (${problem.request_id})`);
}
const { incidents, page } = await response.json();
// page.next_cursor is null when you have everything

We use only the cookies needed to sign you in securely and to remember your language and display choices. No analytics, advertising or third-party cookies.

Cookie policy