> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Support JavaScript API reference Canonical URL: https://posthog.com/docs/support/javascript-api ## On this page - [Check availability](#check-availability) - [Control the widget](#control-the-widget) - [Theme the widget](#theme-the-widget) - [Send a message](#send-a-message) - [Fetch messages](#fetch-messages) - [Mark messages as read](#mark-messages-as-read) - [Fetch tickets](#fetch-tickets) - [Get the current context](#get-the-current-context) - [User identification](#user-identification) - [Build a custom chat UI](#build-a-custom-chat-ui) - [Recover tickets across browsers](#recover-tickets-across-browsers) - [Events captured](#events-captured) - [Persistence](#persistence) - [Error handling](#error-handling) - [Method summary](#method-summary) The `posthog.conversations` JavaScript API gives you full programmatic control over PostHog Support. Use it to build a custom support interface or integrate support into your existing UI. `posthog.conversations` is the namespace for Support's SDK methods. "Conversations" is the code-level name for support tickets and their messages, so you'll see it in method names, captured events, and settings – the product itself is Support. ## Check availability Before calling other methods, check that the API is available: ```javascript if (posthog.conversations.isAvailable()) { // The API is ready to use } ``` `isAvailable()` returns `true` when: - Support is enabled in your project settings - The conversations module has loaded successfully ## Control the widget ```javascript posthog.conversations.show() posthog.conversations.hide() posthog.conversations.open() posthog.conversations.close() ``` - `show()` renders the widget, including the launcher button. It does nothing until the widget bundle has loaded. - `hide()` removes the widget, including the launcher. - `open()` opens the chat panel. It renders the widget first when it is not on the page. - `close()` closes the chat panel and leaves the launcher in place. - `isVisible()` returns `true` when the widget is rendered. `open()` and `close()` need `posthog-js` 1.442.0 or later. If you call them before the widget bundle has loaded, the last call runs once the bundle loads. `open()` does nothing on a domain that is not in **Allowed domains**. See [Set up the widget](https://posthog.com/docs/support/widget.md#show-and-hide-the-widget) for when to use each method. ## Theme the widget Pass `conversations.theme` to `posthog.init()`, or call `setTheme()` later. `setTheme()` merges over the current theme, including the `dark` object, and it is safe to call before the widget loads. Top-level colors apply to the light scheme. Set dark mode colors under `dark`. `posthog.reset()` keeps the theme. Theming needs `posthog-js` 1.444.0 or later. The option list, CSS variables, and precedence are in [Theme the widget](https://posthog.com/docs/support/widget.md#theme-the-widget). ```javascript posthog.init('', { conversations: { theme: { colorScheme: 'auto', primary: '#111827', dark: { primary: '#f9fafb' }, }, }, }) posthog.conversations.setTheme({ colorScheme: 'dark' }) ``` ## Send a message ```javascript // Send a message (creates ticket if none exists) const response = await posthog.conversations.sendMessage('Hello, I need help!') // Send with user identification const response = await posthog.conversations.sendMessage( 'Hello, I need help!', { name: 'John Doe', email: 'john@example.com' } ) // Force start a new conversation (new ticket) const response = await posthog.conversations.sendMessage( 'Starting a new conversation', undefined, // userTraits true // newTicket ) ``` **Parameters:** - `message` (string) – The message text to send - `userTraits` (optional) – Object with `name` and/or `email` for user identification - `newTicket` (optional, boolean) – If `true`, creates a new ticket even if one exists **Response:** ```typescript interface SendMessageResponse { ticket_id: string // ID of the ticket message_id: string // ID of the created message ticket_status: string // 'new' | 'open' | 'pending' | 'on_hold' | 'resolved' created_at: string // ISO timestamp unread_count: number // Unread messages from team (0 after sending) } ``` ## Fetch messages ```javascript // Get messages for the current active ticket const response = await posthog.conversations.getMessages() // Get messages for a specific ticket const response = await posthog.conversations.getMessages('ticket-uuid') // Get messages after a specific timestamp (for pagination) const response = await posthog.conversations.getMessages( 'ticket-uuid', '2024-01-15T10:30:00Z' ) ``` **Response:** ```typescript interface GetMessagesResponse { ticket_id: string ticket_status: string messages: Message[] has_more: boolean // Whether more messages exist unread_count: number // Unread messages from team } interface Message { id: string content: string author_type: 'customer' | 'support' | 'AI' author_name?: string created_at: string // ISO timestamp is_private: boolean // Internal notes (not shown to customer) } ``` ## Mark messages as read ```javascript // Mark messages as read for current ticket await posthog.conversations.markAsRead() // Mark messages as read for a specific ticket await posthog.conversations.markAsRead('ticket-uuid') ``` **Response:** ```typescript interface MarkAsReadResponse { success: boolean unread_count: number // Should be 0 after marking as read } ``` ## Fetch tickets ```javascript // Get all tickets const response = await posthog.conversations.getTickets() // Get tickets with filters const response = await posthog.conversations.getTickets({ status: 'open', limit: 10, offset: 0 }) ``` **Parameters:** - `options` (optional) – Object with any of: - `status` (string) – Filter by status: `new`, `open`, `pending`, `on_hold`, or `resolved` - `limit` (number) – Number of tickets to return (default: 20) - `offset` (number) – Pagination offset (default: 0) **Response:** ```typescript interface GetTicketsResponse { count: number // Total count of tickets results: Ticket[] // Array of tickets } interface Ticket { id: string status: string last_message?: string last_message_at?: string message_count: number created_at: string unread_count?: number } ``` ## Get the current context ```javascript // Get the current active ticket ID (null if no conversation started) const ticketId = posthog.conversations.getCurrentTicketId() // Get the widget session ID (persistent browser identifier) const sessionId = posthog.conversations.getWidgetSessionId() ``` The **widget session ID** is a persistent UUID that: - Stays the same across page loads and browser sessions - Is used for access control (only this browser can access its tickets) - Survives user identification changes (`posthog.identify()`) ## User identification Conversations work with both anonymous and identified users. ### Anonymous users Messages are associated with the widget session ID. Access to the conversation persists across page loads. ### Identified users When you call `posthog.identify()`, the conversation seamlessly continues: - Widget session ID remains the same (user keeps access) - Backend links the ticket to the identified Person - User traits from PostHog are used if not provided in `sendMessage()` ### User traits priority When sending messages, user traits are resolved in this order: 1. Explicitly provided in `sendMessage(message, { name, email })` 2. PostHog person properties (`$name`, `$email`, `name`, `email`) 3. Previously saved traits from the identification form ## Build a custom chat UI You can build a completely custom chat UI using the API while disabling the default widget: ```javascript // In PostHog settings: set widgetEnabled to false // Your custom implementation async function initCustomChat() { // Wait for conversations to be available const checkAvailable = setInterval(() => { if (posthog.conversations.isAvailable()) { clearInterval(checkAvailable) loadExistingMessages() } }, 100) } async function loadExistingMessages() { const ticketId = posthog.conversations.getCurrentTicketId() if (ticketId) { const response = await posthog.conversations.getMessages() renderMessages(response.messages) } } async function sendMessage(text, userEmail) { const response = await posthog.conversations.sendMessage(text, { email: userEmail }) // Add optimistic UI update addMessageToUI({ id: response.message_id, content: text, author_type: 'customer', created_at: response.created_at }) } // Poll for new messages setInterval(async () => { if (posthog.conversations.getCurrentTicketId()) { const response = await posthog.conversations.getMessages() updateMessagesUI(response.messages) } }, 5000) ``` ## Recover tickets across browsers Tickets are tied to the browser's widget session ID, so switching browsers or clearing storage means losing access. You can recover tickets by requesting a recovery link via email. ### Request a recovery link ```javascript await posthog.conversations.requestRestoreLink('user@example.com') ``` This sends an email containing a recovery link to the provided address. The link includes a `ph_conv_restore` token as a query parameter and expires after one hour. **Parameters:** - `email` (string) – The email address used in previous conversations The method is rate limited. If you send too many requests, it throws an error with a 429 status. ### Restore tickets from a recovery link ```javascript const result = await posthog.conversations.restoreFromUrlToken() ``` Reads the `ph_conv_restore` query parameter from the current URL and migrates the associated tickets to the current browser session. After processing, the query parameter is removed from the URL. **Response:** ```typescript interface RestoreResult { status: 'success' migrated_ticket_ids: string[] // IDs of tickets migrated to this session } ``` The default widget calls `restoreFromUrlToken()` automatically on load, so you only need to call this yourself if you're building a custom UI. ## Events captured The conversations module automatically captures these events: | Event | Description | | --- | --- | | `$conversations_loaded` | Conversations API initialized | | `$conversations_widget_loaded` | Widget UI rendered | | `$conversations_message_sent` | User sent a message | | `$conversations_widget_state_changed` | Widget opened/closed | | `$conversations_user_identified` | User submitted identification form | | `$conversations_identity_changed` | User called `posthog.identify()` | ### Workflow trigger events In addition to the widget events above, the following server-side events are captured when ticket or message state changes. These events can be used as [workflow triggers](https://posthog.com/docs/workflows/workflow-builder.md#conversation-event-triggers) to automate support processes. | Event | Description | Properties | | --- | --- | --- | | `$conversation_ticket_created` | A new support ticket was created | – | | `$conversation_ticket_status_changed` | Ticket status was updated | `old_status`, `new_status` | | `$conversation_ticket_priority_changed` | Ticket priority was updated | `old_priority`, `new_priority` | | `$conversation_ticket_assigned` | Ticket was assigned to a user or a role | `assignee_type` (`user`, `role`, or `null` when unassigned), `assignee_id` | | `$conversation_message_sent` | Team member sent a message on a ticket | `message_id`, `message_content`, `author_type`, `author_id` | | `$conversation_message_received` | Customer sent a message on a ticket | `message_id`, `message_content`, `author_type`, `customer_name`, `customer_email` | All workflow trigger events include these base properties: `ticket_id`, `ticket_number`, `channel_source`, `status`, and `priority`. These events integrate with the rest of PostHog – use them in funnels, cohorts, or to trigger other actions. ## Persistence The SDK persists the following data in `localStorage`: - Widget session ID (for access control) - Current ticket ID (to continue conversations) - Widget state (open/closed) - User traits (name/email from identification form) This data is cleared when: - `posthog.reset()` is called - Browser storage is cleared The widget theme is separate. `posthog.reset()` keeps the theme from `posthog.init()` and from `setTheme()`. ## Error handling API methods return `null` if conversations are not available yet. Always check availability or handle null returns: ```javascript // Option 1: Check availability first if (posthog.conversations.isAvailable()) { const response = await posthog.conversations.sendMessage('Hello') } // Option 2: Handle null response const response = await posthog.conversations.sendMessage('Hello') if (response) { console.log('Message sent:', response.message_id) } ``` API calls may also throw errors for: - Network failures - Rate limiting (429 status) - Invalid ticket IDs - Server errors ```javascript try { await posthog.conversations.sendMessage('Hello') } catch (error) { if (error.message.includes('Too many requests')) { // Handle rate limiting - wait and retry } } ``` ## Method summary | Method | Description | Returns | | --- | --- | --- | | `isAvailable()` | Check if conversations API is ready | `boolean` | | `isVisible()` | Check if the widget is rendered | `boolean` | | `show()` | Render the widget, including the launcher | `void` | | `hide()` | Remove the widget, including the launcher | `void` | | `open()` | Open the chat panel. Renders the widget first if it is not on the page | `void` | | `close()` | Close the chat panel. The launcher stays on the page | `void` | | `setTheme(theme)` | Merge a theme patch over the current widget theme | `void` | | `sendMessage(message, userTraits?, newTicket?)` | Send a message | `Promise` | | `getMessages(ticketId?, after?)` | Fetch messages | `Promise` | | `markAsRead(ticketId?)` | Mark messages as read | `Promise` | | `getTickets(options?)` | Fetch tickets list | `Promise` | | `getCurrentTicketId()` | Get current ticket ID | `string \| null` | | `getWidgetSessionId()` | Get widget session ID | `string \| null` | | `requestRestoreLink(email)` | Send a recovery email to restore tickets | `Promise` | | `restoreFromUrlToken()` | Restore tickets from URL recovery token | `Promise` | | `posthog.setIdentity(distinctId, hash)` | Prove ticket ownership with an HMAC from your server. See [identity verification](https://posthog.com/docs/support/widget.md#identity-verification) | `void` | | `posthog.clearIdentity()` | Drop the verified identity on logout so the widget uses the browser session | `void` | `setIdentity()` and `clearIdentity()` are on the main `posthog` instance, not on `posthog.conversations`.