Server-side and client-side SDK for Node.js, browsers, and TypeScript
The Ansa SDK provides a type-safe way to interact with the Ansa API from Node.js, browsers, or any JavaScript runtime. It includes both an API client for server-side integrations and helper functions for controlling the widget.
import { AnsaClient } from "@ansa-so/sdk";const ansa = new AnsaClient({ apiKey: process.env.ANSA_API_KEY!,});// Send a message and get a responseconst response = await ansa.chat("agent_abc123", "What are your hours?");console.log(response.message);
import { embedWidget, openWidget, identify } from "@ansa-so/sdk";// Embed the widget (alternative to script tag)embedWidget({ agentId: "agent_abc123",});// Identify the logged-in useridentify({ userId: "user_456", userMetadata: { name: "Jane Smith", email: "jane@example.com", },});// Open the chat when user clicks a buttondocument.getElementById("help-btn")?.addEventListener("click", () => { openWidget("I need help with my account");});
These functions control the embedded widget from your application code. They automatically queue commands if the widget isn’t ready yet, using an internal command queue that processes once the widget is initialized.
The SDK uses a command queue to handle cases where you call widget functions before the widget is fully loaded:
Copy
import { openWidget, identify } from "@ansa-so/sdk";// These calls are safe even before the widget loads// They're queued and executed once the widget is readyidentify({ userId: "user_123", userMetadata: { name: "Jane" }});openWidget("How can I help?");
Under the hood, the SDK checks window.ansa?.isReady() and either executes immediately or queues the command:
Copy
// Internal SDK pattern (for reference)function enqueueOrExecute(command: () => void) { const api = window.ansa; if (api?.isReady?.()) { command(); } else { commandQueue.push(command); startQueueProcessor(); // Polls every 100ms until ready }}
You don’t need to manually wait for the widget—the SDK handles this automatically. But if you need to know when the widget is ready, use window.ansa.onReady() or listen for the ansa:ready event.
import { identify, clearIdentity } from "@ansa-so/sdk";// On login - include auth token for API callsidentify({ userId: "user_123", userMetadata: { name: "Jane Smith", email: "jane@example.com", plan: "pro", authToken: "eyJhbG...", // Passed to HTTP tools via {{userMetadata.authToken}} },});// On logoutclearIdentity();