fluxchat/sdk

SDK · Stable

JavaScript / TypeScript SDK

v0.1.8 · Stable

The official FluxChat SDK for browser and Node.js. Provides a floating chat widget, a headless ask() client, and knowledge base management.

Installation

terminal
npm install @fluxchat_sdk/sdk
# or
yarn add @fluxchat_sdk/sdk
# or
pnpm add @fluxchat_sdk/sdk

Quickstart

Headless — ask() only

chat.ts
import { FluxChatClient } from '@fluxchat_sdk/sdk';

const client = new FluxChatClient({
  apiKey: process.env.FLUXCHAT_API_KEY!,
});

const { reply, conversationId } = await client.ask({
  message: 'What are your opening hours?',
  context: 'User: Alice, Plan: Pro',  // optional
});

console.log(reply);

Widget (browser)

Drop FluxChatWidget anywhere in your React tree. It renders a floating chat bubble with no additional configuration.

App.tsx
import { FluxChatWidget } from '@fluxchat_sdk/sdk';

export default function App() {
  return (
    <>
      <YourApp />
      <FluxChatWidget apiKey={process.env.VITE_FLUXCHAT_API_KEY!} />
    </>
  );
}

Quick replies — greeting chip row

Pass a quickReplies array to show tap-to-send chips below the greeting message when the panel first opens. Each chip sends that exact text as the user's first message and then disappears.

init.js
FluxChatWidget.init({
  apiKey: 'fc_live_xxx',
  greeting: 'Bonjour ! Comment puis-je vous aider ?',
  quickReplies: [
    'What can you do?',
    'Show me pricing',
    'I need support',
  ],
});

// React component:
<FluxChatWidget
  apiKey={process.env.NEXT_PUBLIC_FLUXCHAT_API_KEY!}
  greeting="Hello! How can I help?"
  quickReplies={['What can you do?', 'Show me pricing', 'Contact sales']}
/>

Chips are horizontally scrollable on mobile, styled with your primaryColor, and removed permanently as soon as the user sends any message (whether via a chip or by typing).

autoCapture — zero-config site intelligence

From v0.1.5, the widget passively captures every page the user visits. From v0.1.7, it also intercepts all fetch() and XMLHttpRequest GET responses (JSON only) and snapshots localStorage — giving the bot full awareness of your app's live data with zero configuration.

any-site.html
<!-- That's it. autoCapture is true by default. -->
<script src="https://cdn.jsdelivr.net/npm/@fluxchat_sdk/sdk/dist/widget.global.js"></script>
<script>
  FluxChatWidget.init({ apiKey: 'fc_live_xxx' });
</script>

<!-- What gets captured automatically (v0.1.7+):
     ✓ Page DOM text  — every URL visited (once per session)
     ✓ fetch() GET    — JSON API responses (/api/clients, /api/products, …)
     ✓ XHR GET        — same filtering as fetch
     ✓ localStorage   — user session data (auth/token keys excluded)

     User visits /dashboard → API calls intercepted
     User asks "how many clients do we have?" → bot reads captured API data -->

Works on static HTML, WordPress, React Router, Vue Router, Angular, Next.js — any site. SPA navigation is intercepted via pushState / replaceState / popstate / hashchange. Captured data is deduplicated by content hash — re-visiting a page with unchanged content does not send a duplicate.

Auto-filtered: auth endpoints (/login, /token, /refresh), static assets, images, and binary responses are never captured.

Set autoCapture: false only if you populate the knowledge base manually (admin import or crawl).

Auto-KB learning — permanent knowledge from captures

From v0.1.7, the FluxChat gateway automatically extracts structured knowledge from every capture and stores it permanently in your organization's knowledge base — no TTL, no re-fetching needed.

flow.txt
SDK captures page / API response
        ↓
Gateway stores raw capture (bot_session_page, TTL 1h)
        ↓  [fire-and-forget, max 2 concurrent per org]
FluxChat AI extracts:
  • title      — "Services and pricing — Acme Corp"
  • content    — "Acme offers web dev ($500–2000), SEO ($300/mo)…"
  • category   — pricing | product | contact | support | …
  • keywords   — ["web dev", "SEO", "pricing", "Acme"]
        ↓
Stored in bot_knowledge (source = 'auto', permanent)
        ↓
Bot answers from permanent KB — even after 1h session TTL expires

Content-change refresh: if the same URL is captured again with different content (e.g. your client list grew), the stale auto-KB entry is replaced automatically. The hash is compared — unchanged content is a no-op.

Auto-generated entries are tagged source: 'auto' in the knowledge base and can be reviewed, edited, or deleted from the admin panel like any manual entry.

platformApi — live data from your own API

The widget can query your platform's REST API in real time to answer questions that require fresh data (orders, events, products, sermons, etc.).

init.js
FluxChatWidget.init({
  apiKey: 'fc_live_xxx',
  platformApi: {
    baseUrl: 'https://api.my-app.com',
    // authTokenKeys: ['member_token', 'admin_token'] // optional override
  },
});
// The widget fetches your OpenAPI/Swagger spec once, scores every GET endpoint
// against each user question, calls the top matches, and injects the results
// into context before sending to FluxChat.
// The user's auth token is read from localStorage automatically.

No manual intent/action setup. No configuration beyond the base URL. If your API has an OpenAPI spec (/openapi.json, /swagger.json, or /api-docs), the bot uses it automatically.

User context injection

Set window.fluxchatContext before the widget loads. The SDK reads it at send-time and includes it in every request so the bot knows who is talking.

context-schema.ts
window.fluxchatContext = {
  user: {
    name: 'Alice Martin',       // display name
    email: 'alice@example.com', // optional
    role: 'admin',              // free string — sent verbatim to the bot
  },
  org: {
    name: 'My Organisation',    // shown in widget header
  },
  // any extra key-value pairs are also forwarded
  plan: 'pro',
  locale: 'fr',
};

React hook — inject on login

FluxChatContextInjector.tsx
import { useEffect } from 'react';
import { useAuth } from '@/hooks/useAuth';

export function FluxChatContextInjector() {
  const { user } = useAuth();

  useEffect(() => {
    if (user) {
      window.fluxchatContext = {
        user: { name: user.name, email: user.email, role: user.role },
        org:  { name: user.orgName },
      };
    }
  }, [user]);

  return null;
}

Framework environment variables

FrameworkEnv fileVariable name
Vite.envVITE_FLUXCHAT_API_KEY
Next.js.env.localNEXT_PUBLIC_FLUXCHAT_API_KEY
Create React App.envREACT_APP_FLUXCHAT_API_KEY
Node / Express.envFLUXCHAT_API_KEY

Framework setup

Next.js (App Router)

app/layout.tsx
import { FluxChatWidget } from '@fluxchat_sdk/sdk';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <FluxChatWidget apiKey={process.env.NEXT_PUBLIC_FLUXCHAT_API_KEY!} />
      </body>
    </html>
  );
}

Vite / React

src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { FluxChatWidget } from '@fluxchat_sdk/sdk';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
    <FluxChatWidget apiKey={import.meta.env.VITE_FLUXCHAT_API_KEY} />
  </React.StrictMode>,
);

Plain HTML (CDN)

index.html
<script src="https://cdn.jsdelivr.net/npm/@fluxchat_sdk/sdk/dist/widget.umd.js"></script>
<script>
  FluxChat.init({ apiKey: 'fc_prod_your_key' });
</script>

API reference

FluxChatClient

client.ts
const client = new FluxChatClient({ apiKey: 'fc_prod_...' });

// Send a message
const { reply, conversationId } = await client.ask({
  message: 'Hello',
  context?: string,          // optional — user/page context
  conversationId?: string,   // optional — omit for stateless
});

// Verify the key
const { organizationId, scopes } = await client.testKey();

FluxChatWidget props

PropTypeDefaultDescription
apiKeystringRequired. Your fc_prod_... key.
baseUrlstringautoOverride API URL (useful for self-hosted).
clientNamestringBrand name shown in the header.
assistantNamestring'Assistant'Assistant display name.
primaryColorstring'#4f46e5'Brand color for header and buttons.
theme'light' | 'dark''light'Initial color theme.
position'right' | 'left''right'Launcher corner.
greetingstringautoFirst message shown to user.
contextstringStatic context sent with every message.
autoContextbooleantrueAuto-inject page title, URL, DOM text and window.fluxchatContext into every message.
autoCapturebooleantruePassively capture every page visited — bot learns your entire site automatically.
platformApi{ baseUrl: string }Your REST API base URL. Widget auto-queries relevant endpoints per message for live data.
quickRepliesstring[][]Tap-to-send chip row shown below the greeting. Chips disappear after the first user message. E.g. ['What can you do?', 'Show me pricing'].
openOnLoadbooleanfalseOpen the panel automatically.

Knowledge base

Manage your bot's knowledge base programmatically. Requires a key with bot:write scope for create/update/delete.

kb.ts
// Create an article
const article = await client.knowledge.create({
  title: 'Opening hours',
  content: 'We are open Mon–Fri 9am–6pm.',
  category: 'general',
  keywords: ['hours', 'schedule'],
});

// Update
await client.knowledge.update(article.id, { content: 'New content' });

// Delete
await client.knowledge.delete(article.id);

// List all (requires admin JWT)
const articles = await client.knowledge.list();

// Get one
const item = await client.knowledge.get(article.id);

TypeScript types

types.ts
export interface AskOptions {
  message: string;
  context?: string;
  conversationId?: string;
}

export interface AskResponse {
  reply: string;
  conversationId: string;
  intent: string | null;
  confidence: number;
}

export interface KBArticle {
  id: string;
  title: string;
  content: string;
  category: string;
  keywords: string[];
  createdAt: string;
  updatedAt: string;
}

export interface FluxChatContext {
  user?: { name?: string; email?: string; role?: string };
  org?:  { name?: string };
  [key: string]: unknown;
}