@synerise/ai-assistant-react
v1.15.0
Published
React wrapper for embedding the Synerise AI Assistant in React applications.
Maintainers
Readme
@synerise/ai-assistant-react
React wrapper for embedding the Synerise AI Assistant in React 18 applications.
Requirements
This package is designed for the Synerise platform. To use it you need:
- An active Synerise tenant and a tracker key
- Network access to
https://api.synerise.com(or your custom Synerise API endpoint) - React 18 in your application
If you don't have a Synerise account, visit synerise.com.
Which package do I need?
| Your stack | Package |
| --- | --- |
| Vanilla JS / no bundler / <script> tag | @synerise/ai-assistant-sdk |
| React 18 | @synerise/ai-assistant-react (this package) |
| Preact | @synerise/ai-assistant-core |
| Build a custom chat UI from primitives | @synerise/ai-assistant-ui |
How packages relate
@synerise/ai-assistant-react ──> @synerise/ai-assistant-core ──> @synerise/ai-assistant-uiThis package is a thin React wrapper around the Preact-based core. The chat UI itself is rendered with Preact under the hood via preact/compat. Most apps don't need to know this, but see the SSR / dual runtime notes below.
Installation
npm install @synerise/ai-assistant-react preact
# or
pnpm add @synerise/ai-assistant-react preact
# or
yarn add @synerise/ai-assistant-react preactPeer dependencies
react^18.3.1react-dom^18.3.1preact^10.26.9— formally a peer of@synerise/ai-assistant-core(this wrapper renders the chat with Preact viapreact/compatunder the hood). Install it alongsidereact/react-domeven though it isn't listed directly in this package'speerDependencies.
Quick start
import { AIAssistant } from "@synerise/ai-assistant-react";
export function AssistantPanel() {
return (
<AIAssistant
apiUrl="https://api.synerise.com/agents/v1/ai-assistant"
context={{ profileId: "user-123" }}
additionalContextValues={{ segment: "premium" }}
displayMode="bordered"
onPromptSuccess={(response) => {
console.log("threadId:", response.meta.threadId);
console.log("messages:", response.data.messages);
}}
onCustomAction={({ actionName, params }) => {
console.log(actionName, params);
}}
/>
);
}What this package provides
AIAssistant— full chat component with built-in lifecycle handlingIcon— icon component (re-exported fromcore/ui)ChatBase— lower-level chat primitive for advanced cases- All exports from
@synerise/ai-assistant-coreare re-exported, so you typically need only one import:
import {
AIAssistant,
assistantApi,
AI_ASSISTANT_ERROR_TYPE,
CHAT_STATE,
type AIAssistantProps,
type AIAssistantRef,
type AIAssistantResponseBody,
type AIAssistantConversation,
} from "@synerise/ai-assistant-react";Important props
| Prop | Type | Description |
| --- | --- | --- |
| apiUrl | string | Base assistant API URL |
| context | Context \| null | Per-request context object. Optional — pass null or omit when unused. |
| additionalContextValues | AdditionalContextValues \| null | Per-request metadata. Optional — pass null or omit when unused. |
| displayMode | "drawer" \| "bordered" | UI layout |
| onPromptSuccess | (response) => void | Required. Called after a successful init/message response |
| onCustomAction | ({ actionName, params }) => void | Called when the assistant emits a custom action |
| threadId | string | Loads an existing conversation when provided |
| stream | boolean | Use SSE instead of regular POST |
| fastMode | boolean | Append fastMode=true query param |
| assistantId | string | Optional assistant configuration ID (UUID). Sent as assistantId query param; falls back to backend default when omitted. |
| authParams | { code, clientUUID } | Auth payload (alternative to XSRF cookie auth) |
| disableXSRFToken | boolean | Skip XSRF token header in fetch calls |
For the full prop surface, see the TypeScript definitions of AIAssistantProps.
Imperative API — AIAssistantRef
AIAssistant is a forwardRef component. Attach a ref to drive a
running chat from outside its tree — typically for a host-owned
"conversation history" UI.
import { useRef } from "react";
import {
AIAssistant,
type AIAssistantRef,
type AIAssistantConversation,
} from "@synerise/ai-assistant-react";
export function AssistantPanel() {
const chatRef = useRef<AIAssistantRef>(null);
const openHistory = async () => {
const conversations = await chatRef.current?.getConversations();
// …render a list. On click:
// await chatRef.current?.loadThread(conv.threadId);
};
return (
<>
<button onClick={openHistory}>History</button>
<AIAssistant
ref={chatRef}
apiUrl="https://api.synerise.com/gen-ai/v3/ai-assistant"
displayMode="bordered"
onPromptSuccess={(response) => console.log(response.meta.threadId)}
/>
</>
);
}| Method | Returns | Description |
| ---------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| loadThread(threadId) | Promise<void> | Replace the active conversation with the messages of an existing thread. 404 → THREAD_NOT_FOUND state. |
| getConversations() | Promise<AIAssistantConversation[]> | List the current user's historical threads. |
You can also pass threadId as a regular prop to mount the component
with an existing thread already loaded.
Storefront page context (PDP)
When the user opens the chat from a product detail page, telling the assistant which product they're viewing lets it resolve "this", "it", "cheaper", "is this any good?" against the right item.
The signal travels per turn under
additionalContextValues.page_context. The React package exposes the
usePageContext hook for state management plus pure helpers
(detectPageContextFromMeta, observePageContext,
StorefrontPageContext) for custom integrations.
usePageContext hook
import { useMemo } from "react";
import {
AIAssistant,
usePageContext,
} from "@synerise/ai-assistant-react";
export function ShoppingChat() {
const [pageContext] = usePageContext({ autoDetect: true });
const additionalContextValues = useMemo(
() => (pageContext ? { page_context: pageContext } : null),
[pageContext],
);
return (
<AIAssistant
apiUrl="https://api.synerise.com/agents/v1/ai-assistant"
displayMode="bordered"
additionalContextValues={additionalContextValues}
onPromptSuccess={(response) => console.log(response.meta.threadId)}
/>
);
}usePageContext({ autoDetect, initial }) returns a [pageContext,
setPageContext] tuple with the same shape as useState. The merge
into additionalContextValues.page_context is your responsibility —
this keeps usePageContext orthogonal to your existing
additionalContextValues state.
| Option | Type | Description |
| --- | --- | --- |
| autoDetect | boolean | When true, reads OG product meta tags at mount (synchronously) and watches <head> for changes. Default false. |
| initial | StorefrontPageContext \| null | Initial value. Takes precedence over auto-detect when set. |
With autoDetect: true, the initial value is read synchronously
during the first render, so the first /chat POST already carries
page_context — no need to defer mounting.
Auto-detect works out of the box with react-helmet, next/head, and
similar libraries that mutate meta tags on navigation. Apps that don't
change meta tags between routes can't be re-detected per-route — fall
back to a manual setter call from your router in that case.
Pure helpers
detectPageContextFromMeta() reads the meta tags once and returns
StorefrontPageContext | null. observePageContext({ onChange })
subscribes and returns a cleanup. Useful when you want to manage state
outside the hook (e.g. global store, multiple <AIAssistant> instances
sharing the same signal).
import {
detectPageContextFromMeta,
observePageContext,
} from "@synerise/ai-assistant-react";Wire shape
The backend expects page_context (snake_case) under
additionalContextValues. The inner object stays camelCase
(pageType, itemId) — the backend's Pydantic model accepts both via
explicit aliases:
{
"additionalContextValues": {
"page_context": { "pageType": "product", "itemId": "SKU-12345" }
}
}Only pageType: "product" is supported today.
Direct API access (without rendering)
You can call the underlying API helpers without mounting any component:
import { assistantApi } from "@synerise/ai-assistant-react";
const initResponse = await assistantApi.initChat({
apiUrl: "https://api.synerise.com/agents/v1/ai-assistant",
context: { profileId: "user-123" },
additionalContextValues: { segment: "premium" },
message: null,
});
const threadId = initResponse?.meta.threadId;
if (threadId) {
await assistantApi.sendChatMessage({
apiUrl: "https://api.synerise.com/agents/v1/ai-assistant",
threadId,
message: "Show me products for trail running",
context: { profileId: "user-123" },
additionalContextValues: { segment: "premium" },
});
}
// Listing historical conversations:
const conversations = await assistantApi.getConversations({
apiUrl: "https://api.synerise.com/gen-ai/v3/ai-assistant",
});
// AIAssistantConversation[] — { threadId, summary, createdAt, … }SSR / dual runtime notes
The chat is rendered with Preact via preact/compat while your host app runs React. This means:
- The
<AIAssistant>component is a React component on the outside (usable like any other), but the chat tree it renders internally is Preact. - You can render this safely on the client — no special setup needed for CSR-only apps.
- For SSR frameworks (Next.js, Remix, etc.) render
<AIAssistant>only on the client. Either:- Wrap it in a dynamic import with
{ ssr: false }, or - Mount it inside
useEffect, or - Guard with
typeof window !== "undefined".
- Wrap it in a dynamic import with
- The chat interacts with the DOM (
document.cookie,fetch) so it cannot run during server rendering.
Troubleshooting
- TypeScript errors about
ReactNodefrom preact vs react — both runtimes ship slightly differentReactNodetypes. The wrapper usesas anyinternally to bridge them. If you re-type slots or callbacks, narrow types explicitly. - "Two React instances" warnings — this is expected: React for your app, Preact (via compat) for the chat. They do not share state. If you see hook errors, ensure you are not calling Preact hooks from React components or vice versa.
document is not definedduring SSR — render only on the client (see SSR / dual runtime notes).- 401 / 403 from API — verify your tracker key, that
apiUrlmatches your tenant, and thatdisableXSRFTokenmatches your tenant's auth flow.
Support
For technical and licensing inquiries: [email protected].
License
Proprietary. See LICENSE.
