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().
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.
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.