> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getstrada.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

Strada's Web SDK consists of a global `stradaChat` object that you must [add to your site](/sdks/web/getting-started#script-tag) to use any Web SDK functionality, along with corresponding [settings](#settings) and [actions](#actions).

## Settings

Configure the Web SDK by creating a `stradaSettings` object in the global `window` scope.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id'
    // ... other settings
  };
</script>
<!-- Define the web SDK script afterwards -->
<script src="https://sdk.getstrada.com/web-sdk/latest/strada-chat.js"></script>
```

Alternatively, you can pass settings to the `stradaChat.start` method. (See [Delay widget loading](/sdks/web/getting-started#delay-widget-loading).)

<Note>
  The Web SDK requires that `window.stradaSettings` be defined before the script loads. You must therefore
  define `window.stradaSettings` before the script, or use the `lazy` option and call `start()` manually.
</Note>

Available configuration options:

### organizationId

`organizationId: string;` **(required)**

Your Strada organization ID. You can find this in the Strada dashboard.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id'
  };
</script>
```

### agentId

`agentId: string;` **(required)**

The ID of the agent to load in the chat widget. You can find this in the Strada dashboard.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id'
  };
</script>
```

### agentVariables

`agentVariables?: Record<string, unknown>;`

Pass data that you want to make available to your agent through `agentVariables`. This data can be accessible to the AI agent or be used in your actions.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    agentVariables: {
      first_name: 'John',
      last_name: 'Doe',
      email: 'john@example.com'
    }
  };
</script>
```

### metadata

`metadata?: Record<string, unknown>;`

Use `metadata` to pass information about a user to Strada for attribution and analytics purposes. This data is not accessible to the AI agent during conversations. For passing data that should be available in chat conversations, use [agentVariables](#agentvariables) instead.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    metadata: {
      userId: '12345',
      accountType: 'premium',
      signupDate: '2024-01-15'
    }
  };
</script>
```

To change these values dynamically, pass them to `open()` (see [open action](#open)).

<Note>Meta field keys should not include whitespace, emojis, or special characters.</Note>

### secureMetadata

`secureMetadata?: Record<string, unknown>;`

Use `secureMetadata` to pass sensitive data that requires an extra layer of protection. The values of secure metadata are never revealed in the UI, but they are still accessible through actions.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    secureMetadata: {
      internalUserId: 'usr_12345',
      authToken: 'sensitive-token-value'
    }
  };
</script>
```

<Note>
  Use secure metadata for sensitive identifiers, tokens, or confidential information that your actions need
  but should not be visible in the dashboard.
</Note>

### stradaReadyCallback

`stradaReadyCallback?(params: { isLoaded: boolean }): void;`

Callback invoked when the SDK completes initialization. Useful for asynchronous widget loading scenarios.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    stradaReadyCallback: ({ isLoaded }) => {
      console.log('Strada widget is ready. Chat support is now available.');
    }
  };
</script>
```

### toggleCallback

`toggleCallback?(isOpen: boolean): void;`

Callback triggered whenever the widget opens or closes.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    toggleCallback: (isOpen) => {
      console.log('Chat is now', isOpen ? 'open' : 'closed');
    }
  };
</script>
```

### lazy

`lazy?: boolean;`

When set to `true`, this will prevent the widget from loading until the `stradaChat.start(...)` method is called. (See [Delay widget loading](/sdks/web/getting-started#delay-widget-loading).)

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    lazy: true
  };
</script>
```

### hideButton

`hideButton?: boolean;`

Hides the default floating button when set to `true`, allowing you to trigger the widget through custom UI elements.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    hideButton: true
  };
</script>
```

### parentElement

`parentElement?: string;`

CSS selector for a custom DOM element to mount the widget into (e.g. `'#my-container'` or `'.widget-container'`). If not provided, the widget mounts to `document.body` with fixed positioning (floating on desktop, full-screen on mobile).

Use this when you want the chat embedded in a specific part of your layout (e.g. a sidebar or dedicated panel) instead of the default bottom-right overlay. The widget will fill the parent element. Typically used together with `hideButton: true` and your own trigger (e.g. a tab or button) that calls `stradaChat.open()`.

**Requirements:**

* The target element must exist in the DOM when the SDK initializes.
* The container should have `position: relative` and `padding: 0`, `margin: 0` so the widget can fill it correctly.
* Use a string selector only (e.g. `'#id'`, `'.class'`). HTMLElement references are not supported.

If the selector does not match any element, the SDK falls back to `document.body` and logs a console warning.

```html theme={null}
<div id="chat-panel" style="position: relative; width: 100%; height: 500px; padding: 0; margin: 0;"></div>

<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    parentElement: '#chat-panel',
    hideButton: true
  };
</script>
<script src="https://sdk.getstrada.com/web-sdk/latest/strada-chat.js"></script>
```

```javascript theme={null}
// Open the widget when user clicks your UI
document.getElementById('open-chat').addEventListener('click', () => {
  window.stradaChat.open();
});
```

<Note>
  **Single Page Applications:** The widget mounts once on initial page load. If your application uses
  client-side routing (React Router, Vue Router, etc.), keep the widget in a layout container that persists
  across route changes. The `parentElement` cannot be changed dynamically after the widget initializes.
</Note>

### darkMode

`darkMode?: boolean;`

Enables dark mode theme for the widget. Defaults to `false`.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    darkMode: true
  };
</script>
```

To toggle dark mode dynamically after initialization, use the [setDarkMode](#setdarkmode) action.

### widgetUrl

`widgetUrl?: string;`

Specifies a custom widget URL. Unless directed by a Strada team member, you should not change this value.

### getUserToken

`getUserToken?(): Promise<string | null>;`

Function that retrieves a JWT token from your backend for user authentication. Returns a token to establish a verified user identity for the chat session.

```html theme={null}
<script>
  window.stradaSettings = {
    organizationId: 'your-org-id',
    agentId: 'your-agent-id',
    getUserToken: async () => {
      // Make a request to your API to get a fresh JWT token
      const response = await fetch('/api/strada-token');
      const { token } = await response.json();
      return token;
    }
  };
</script>
```

<Info>
  The `getUserToken` function should return a Promise that resolves to a JWT token string, or `null` if
  authentication should be skipped.
</Info>

## Actions

All actions are called through the global `stradaChat` object.

### start

`start(settings: StradaSettings): Promise<void>;`

Initializes the SDK. Automatically called on load unless `lazy` mode is enabled, in which case you must call this method manually.

```javascript theme={null}
window.stradaChat.start({
  organizationId: 'your-org-id',
  agentId: 'your-agent-id',
  metadata: {
    userId: '12345',
    accountType: 'premium'
  }
});
```

### open

`open(options?: { agentId?: string; agentVariables?: Record<string, unknown>; metadata?: Record<string, unknown>; secureMetadata?: Record<string, unknown> }): Promise<void>;`

Opens the widget. You can optionally pass context to switch agents or update variables.

**Field-Level REPLACE Semantics:**

* Each field you provide **REPLACES** that entire field (no merging)
* Fields you omit **keep their current value**
* Pass `{}` to clear a field

```javascript theme={null}
// Open with current context (no changes)
window.stradaChat.open();

// Switch agents (keeps current variables/metadata)
window.stradaChat.open({ agentId: 'sales-agent-id' });

// Update variables (REPLACES all variables)
window.stradaChat.open({
  agentVariables: {
    userId: '123',
    screenName: 'checkout',
    cartTotal: 99.99
  }
});

// Switch agents AND update variables
window.stradaChat.open({
  agentId: 'sales-agent-id',
  agentVariables: {
    userId: '123',
    intent: 'upgrade'
  }
});

// Clear variables (empty object = fresh start)
window.stradaChat.open({
  agentVariables: {}
});

// Update multiple fields at once
window.stradaChat.open({
  agentVariables: { userId: '123', page: 'billing' },
  metadata: { tier: 'premium', source: 'webapp' }
});
```

<Note>
  **REPLACE Semantics:** Providing `agentVariables: { page: 'checkout' }` REPLACES all variables with just `{ page: 'checkout' }`. To keep existing variables, include them explicitly or omit the field entirely.
</Note>

<Note>
  Changing `agentVariables` creates a new chat context. Each unique combination of `agentId` +
  `agentVariables` represents a different conversation.
</Note>

### close

`close(): Promise<void>;`

Closes the chat widget.

```javascript theme={null}
window.stradaChat.close();
```

## Context-Based Chat System

The widget maintains separate chats for each unique context. Context is determined by the combination of `organizationId`, `agentId`, and `agentVariables`.

### How it works

* Each unique context creates or accesses a separate chat
* Changing variables creates a new context = different chat
* Same variables returns to the same chat (history preserved)

### Updating variables dynamically

To update variables after initialization, pass them to `open()`.

```javascript theme={null}
// Initial setup
window.stradaSettings = {
  organizationId: 'your-org-id',
  agentId: 'your-agent-id',
  agentVariables: { userId: '123' }
};

// User navigates to checkout page - update variables
window.stradaChat.open({
  agentVariables: {
    userId: '123',
    page: 'checkout',
    cartTotal: 99.99
  }
}); // Opens/creates chat for checkout context

// User returns to home page - update variables again
window.stradaChat.open({
  agentVariables: { userId: '123' }
}); // Returns to original chat (same context)
```

<Warning>
  Each unique combination of variables creates a separate chat. If you want to continue an existing
  conversation, ensure you pass the exact same variables.
</Warning>

### setDarkMode

`setDarkMode(enabled: boolean): void;`

Toggles dark mode dynamically. Useful for syncing the widget theme with your application's theme.

```javascript theme={null}
// Enable dark mode
window.stradaChat.setDarkMode(true);

// Disable dark mode
window.stradaChat.setDarkMode(false);

// Match system preference
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
window.stradaChat.setDarkMode(prefersDark);

// Listen for system theme changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
  window.stradaChat.setDarkMode(e.matches);
});
```

### subscribeEvent

`subscribeEvent(eventKey: string, callback: (data: object, context: object) => void): Promise<number>`

Registers a callback for SDK events. Returns a subscription ID for later removal.

```javascript theme={null}
window.stradaChat.subscribeEvent('strada:ready', (data, context) => {
  console.log('Widget is ready:', data);
});
```

For best results, register event subscriptions inside `stradaReadyCallback` to ensure the SDK is loaded and no events are missed:

```javascript theme={null}
window.stradaSettings = {
  organizationId: 'your-org-id',
  agentId: 'your-agent-id',
  stradaReadyCallback: () => {
    window.stradaChat.subscribeEvent('strada:ready', (data) => {
      console.log('Widget loaded:', data);
    });
  }
};
```

The following are the events that you can currently subscribe to:

| Event key      | Data                    | Description                                                         |
| :------------- | :---------------------- | :------------------------------------------------------------------ |
| `strada:ready` | `{ isLoaded: boolean }` | Triggered when the widget has finished loading and is ready to use. |

### unsubscribeEvent

`unsubscribeEvent(subscriptionId: number): void;`

Removes an event subscription using its subscription ID.

```javascript theme={null}
const subscriptionId = await window.stradaChat.subscribeEvent('strada:ready', (data) => {
  console.log('Widget is ready:', data);
});

// Later, unsubscribe
window.stradaChat.unsubscribeEvent(subscriptionId);
```

## Type Signatures

The SDK actions commonly use the following type signatures.

### StradaSettings

```typescript theme={null}
{
  organizationId: string;
  agentId: string;
  agentVariables?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
  secureMetadata?: Record<string, unknown>;
  stradaReadyCallback?: (params: { isLoaded: boolean }) => void;
  toggleCallback?: (isOpen: boolean) => void;
  lazy?: boolean;
  hideButton?: boolean;
  parentElement?: string;
  darkMode?: boolean;
  widgetUrl?: string;
  getUserToken?: () => Promise<string | null>;
}
```

### StradaEventKey

```typescript theme={null}
type StradaEventKey = 'strada:ready';
```

### EventCallback

```typescript theme={null}
type EventCallback<K extends StradaEventKey> = (data: StradaEventData[K], context: EventContext) => void;
```
