SegOps AIDocs

TypeScript / JavaScript SDK

Works in Node.js (server-side) and modern browsers. Uses the Fetch API and batches events automatically. Full TypeScript type definitions included.

Which key do I use?#

On your server (Node), use a secret key (sk_…) and pass apiKey alone. In the browser, use a public key (pk_…) and also provide getUser() — the SDK runs the session handshake automatically, exchanging the public key for a short-lived token via POST /api/auth/session/, caching it, refreshing before expiry, and re-minting on a 401.

Warning
Never put an sk_ key in browser code — anyone can read it. The SDK prints a console warning if it detects one. For browsers, use a pk_ key.
typescript
const segops = new SegOpsClient({
  apiUrl: 'https://api.segops.ai',
  apiKey: 'pk_live_...',
  getUser: () => ({ userId: currentUser?.id }), // or { anonymousId } when logged out
});

If the public key requires a signed user_id, produce the signature on your backend with @segops/sdk/server and pass the fields through getUser().

Installation#

bash
npm install @segops/sdk
# or
yarn add @segops/sdk
# or
pnpm add @segops/sdk

Quick Start#

typescript
import { SegOpsClient } from '@segops/sdk';

const segops = new SegOpsClient({
  apiUrl: 'https://api.segops.ai',
  apiKey: 'sk_...',
});

// Track an event
segops.track({
  userId: 'user-123',
  eventType: 'page_viewed',
  payload: { path: '/pricing' },
});

// Track a page view with AI referrer detection (browser only)
segops.trackPageView({ userId: 'user-123' });

// Update user traits
segops.identify({
  userId: 'user-123',
  traits: { email: '[email protected]', plan: 'starter' },
});

// Node.js servers: flush before shutdown
process.on('SIGTERM', async () => {
  await segops.shutdown();
  process.exit(0);
});

Constructor Options#

FieldTypeRequiredDescription
apiUrlstringYesBase URL of your SegOps deployment, e.g. https://api.segops.ai
apiKeystringYesAPI key. A secret key (sk_…) authenticates directly; a public key (pk_…) triggers the session handshake — also provide getUser.
getUser() => UserContextNoRequired with a public key (pk_…). Returns the current user context, exchanged for a short-lived session token. Defaults to anonymous if omitted.
batchbooleanNoSet to false to send every event immediately. Default: true
batchSizenumberNoMax events before an automatic flush. Default: 20
flushIntervalnumberNoFlush interval in milliseconds. Default: 5000
onError(err: Error) => voidNoCalled when a flush fails. Default: console.error

Methods#

track(event)

Enqueue a user event. Non-blocking.

typescript
segops.track({
  userId: 'user-123',
  eventType: 'order_placed',
  occurredAt: '2026-04-25T14:32:00Z', // optional
  payload: {
    order_id: 'ord-456',
    total: 89.95,
    currency: 'USD',
  },
});

identify(context)

Record user traits as a context_identified event. Non-blocking.

typescript
segops.identify({
  userId: 'user-123',
  traits: {
    email: '[email protected]',
    plan: 'starter',
    company: 'Acme Corp',
  },
});

trackPageView(options?) — browser only

Track a page view and automatically detect AI referrer sources. When document.referrer matches a known AI provider domain (ChatGPT, Perplexity, Claude, Gemini, Grok), an additional ai_referral_session event is emitted with source_provider, query_hint, landing_url, and referrer_url in the payload. No-op in Node.js (guards on typeof window === 'undefined').

typescript
// Call on every page navigation (e.g. in a Next.js layout)
segops.trackPageView({ userId: currentUser?.id });

flush()

Flush all queued events immediately. Returns a Promise<void>.

typescript
await segops.flush();

shutdown()

Stop the background flush timer and flush all remaining events. Call before your Node.js process exits to avoid data loss.

typescript
await segops.shutdown();

Browser Usage#

When running in a browser, the SDK automatically flushes when the page becomes hidden (visibilitychange event). No additional setup is needed.

typescript
// Browser / React — create once in a module. Use a public key (pk_…) and
// provide getUser() — the SDK runs the session handshake for you.
import { SegOpsClient } from '@segops/sdk';

export const segops = new SegOpsClient({
  apiUrl: process.env.NEXT_PUBLIC_API_URL!,
  apiKey: process.env.NEXT_PUBLIC_SEGOPS_KEY!, // pk_…
  getUser: () => ({ userId: currentUser?.id }), // or { anonymousId } when logged out
});
Warning
In the browser, always use a public key (pk_…), never a secret key (sk_…). Public keys are safe to embed and are exchanged for short-lived session tokens via the handshake.

TypeScript Types#

typescript
interface SegOpsEvent {
  userId: string;
  eventType: string;
  occurredAt?: string;   // ISO 8601
  payload?: Record<string, unknown>;
}

interface SegOpsContext {
  userId: string;
  traits: Record<string, unknown>;
}

interface UserContext {
  userId?: string;       // authenticated user id; omit for anonymous visitors
  anonymousId?: string;  // stable anonymous/client id
  userIdSig?: string;    // hex HMAC signature from signUserId() on your backend
  userIdTs?: number;     // unix-seconds timestamp paired with userIdSig
}

interface SegOpsPageView {
  userId?: string;  // defaults to 'anonymous'
  path?: string;    // defaults to window.location.pathname
}

interface SegOpsOptions {
  apiUrl: string;
  apiKey: string;
  getUser?: () => UserContext;
  batch?: boolean;
  batchSize?: number;
  flushInterval?: number;
  onError?: (err: Error) => void;
}