npm.io
8.0.11 • Published 4d ago

@flowengage/react-chatbot

Licence
MIT
Version
8.0.11
Deps
3
Size
3.0 MB
Vulns
0
Weekly
13.9K

@flowengage/react-chatbot

Embeddable AI-powered customer support chat widget — built by FlowEngage.
Add live chat, AI assistant, and agent handoff to any site in minutes. All you need is your Site ID.


Choose how to integrate

Approach Best for What you add
npm package React, Next.js, Vite, Remix, etc. Install the package, wrap your app with FlowEngageProvider, render FlowEngageWidget.
CDN (script tag) Plain HTML, PHP, any CMS, non-React SPAs One <script> tag; styles are bundled into the embed — no separate CSS file.

You need a Site ID from the FlowEngage dashboard (Integration Guide or site settings).


A. npm package (React / Next.js / Vite)

Prerequisites
  • React 18+ and react-dom 18+ in your project (peer dependencies).
  • Node 18+ recommended for local development.
1. Install
npm install @flowengage/react-chatbot
# or
yarn add @flowengage/react-chatbot
pnpm add @flowengage/react-chatbot

Pin a version in production if you prefer reproducible builds:

npm install @flowengage/react-chatbot@^1.0.0
2. Import the stylesheet once

The widget ships its own CSS. Import it at your app entry (or a layout file):

import '@flowengage/react-chatbot/styles.css';
3. Wrap your app and mount the widget

FlowEngageProvider must wrap any component that uses FlowEngageWidget or useFlowEngage.

// e.g. App.jsx, main.jsx, or a root layout wrapper
import { FlowEngageProvider, FlowEngageWidget } from '@flowengage/react-chatbot';
import '@flowengage/react-chatbot/styles.css';

export default function App() {
  return (
    <FlowEngageProvider siteId="YOUR_SITE_ID">
      <YourExistingApp />
      <FlowEngageWidget />
    </FlowEngageProvider>
  );
}
Next.js App Router
  • Put the provider + widget in a Client Component (file with "use client" at the top), or a client wrapper imported from layout.tsx.
  • Keep a single provider tree so chat state is shared.
Yarn / monorepo

Ensure the package resolves once at app level so you do not mount duplicate providers.

Dashboard styling vs code (widgetSettings)

Use only siteId (and optional apiBaseUrl for local dev) on FlowEngageProvider so the widget loads branding, theme, greetings, and recommendations from the FlowEngage dashboard on every page load—same as the CDN embed.

If you also pass config={{ widgetSettings: { ... } }}, those fields act as defaults only; saved dashboard settings override them. Avoid pasting a full widget JSON into your app unless you intentionally want offline defaults; otherwise you would have to update code after each dashboard change.


B. CDN / script tag (no React project required)

The embed build includes React and injects styles automatically. You do not import styles.css when using the script.

Use the hosted script (kept in sync with FlowEngage infrastructure):

<script
  src="https://cdn.flowengage.com/flowengage-embed.js"
  data-site-id="YOUR_SITE_ID"
  defer>
</script>

Place this before </body> on every page where the widget should appear, or in your global theme template.

B2. npm registry CDN (pin a version)

If you prefer to load the same artifact published to npm (useful for pinning or offline mirrors):

<!-- Replace 1.0.0 with the version you want -->
<script
  src="https://cdn.jsdelivr.net/npm/@flowengage/react-chatbot@1.0.0/dist/flowengage-embed.js"
  data-site-id="YOUR_SITE_ID"
  defer>
</script>

Equivalent path on unpkg:

https://unpkg.com/@flowengage/react-chatbot@1.0.0/dist/flowengage-embed.js

Auto-init attributes (data-*)

On the <script> tag:

Attribute Required Description
data-site-id for auto-init Your Site ID from the dashboard.
data-api-url Override API base URL (advanced; usually omit).
data-widget-settings JSON string of runtime widget overrides (theme, branding). Example: '{"theme":{"primaryColor":"#2563EB"}}'
Manual initialization

If you cannot use data-site-id on the script tag:

<script src="https://cdn.flowengage.com/flowengage-embed.js" defer></script>
<script>
  window.addEventListener('load', function () {
    window.FlowEngage.init({
      siteId: 'YOUR_SITE_ID',
      widgetSettings: {
        theme: { primaryColor: '#2563EB', position: 'bottom-right' },
        branding: { headerName: 'Support', chatButtonText: 'Chat' },
      },
    });
  });
</script>
CDN API (window.FlowEngage)
Method Description
FlowEngage.init({ siteId, widgetSettings?, apiBaseUrl? }) Mounts the widget. Safe to call after DOMContentLoaded.
FlowEngage.destroy() Unmounts the widget and removes injected styles/container. Call before init again if you need to reconfigure.

To open/close the panel from custom UI inside a React app, use the npm package and useFlowEngage() (openWidget, closeWidget, etc.). The standalone embed exposes init / destroy only.


Optional: customization (npm)

Pass runtime overrides via config on the provider (merged with dashboard defaults):

<FlowEngageProvider
  siteId="YOUR_SITE_ID"
  config={{
    widgetSettings: {
      theme: {
        primaryColor: '#FF5733',
        position: 'bottom-left',
      },
      branding: {
        headerName: 'Cool Support Assistant',
        chatButtonText: 'Talk to us',
      },
    },
  }}
>
  <FlowEngageWidget />
</FlowEngageProvider>

Props

<FlowEngageProvider>
Prop Type Required Description
siteId string Your Site ID from the FlowEngage dashboard
config object { widgetSettings?: … } merged with server config
<FlowEngageWidget>

No props required. It reads state from the nearest FlowEngageProvider.


Using the useFlowEngage Hook

Access the full widget context in any child component:

import { useFlowEngage } from '@flowengage/react-chatbot';

function MyCustomButton() {
  const { openWidget, isOpen, chatHistory } = useFlowEngage();

  return (
    <button type="button" onClick={() => openWidget({ notifyChatInitiated: true })}>
      Chat ({chatHistory.length} messages)
    </button>
  );
}
Available context values
Value Type Description
status "booting" | "ready" | "error" Widget boot status
isOpen boolean Whether the chat panel is open
chatHistory Message[] Full chat history array
isHumanHandled boolean Whether a live agent has taken over
agentName string | null Active agent's name
agentHeadshot string | null Active agent's avatar URL
isAgentTyping boolean Agent typing indicator
isLoading boolean Waiting for AI response
isVoiceMode boolean Voice mode active
isRateLimited boolean Rate limit hit
openWidget() function Open the chat panel
closeWidget() function Close the chat panel
toggleWidget() function Toggle the panel
sendMessage(msg, category?) function Send a message
setVoiceMode(bool) function Toggle voice mode
notifyRouteChange() function Notify tracker of SPA route change

SPA Route Tracking

For client-side routing (React Router, Next.js App Router, etc.):

import { useFlowEngage } from '@flowengage/react-chatbot';
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function RouteTracker() {
  const { notifyRouteChange } = useFlowEngage();
  const location = useLocation();

  useEffect(() => {
    notifyRouteChange();
  }, [location.pathname]);

  return null;
}

Voice Mode

The widget includes an ElevenLabs-powered voice agent that visitors can interact with hands-free.

Session lifecycle
  1. Visitor clicks "Start Voice" (or auto-starts on voice-enabled sites)
  2. Widget fetches a signed URL from the backend (GET /api/voice/signed-url)
  3. ElevenLabs WebSocket session starts with page-context greeting override
  4. Agent can call client tools: flowengage_navigate, flowengage_highlight, flowengage_list_forms, flowengage_fill_form, flowengage_click_button, end_voice_session
  5. On SPA navigation the session persists — a URL-change tracker sends contextual updates so the agent knows the current page
  6. On hard navigation (page reload), the transcript is saved to sessionStorage and the session auto-resumes on the next page
Voice resume across page reloads

When the agent navigates the visitor to a new page (flowengage_navigate), the widget:

  • Saves the current transcript and a resume flag to sessionStorage
  • Triggers a hard reload or SPA route change
  • On the new page, useLayoutEffect detects the pending resume and re-enters voice_mode
  • The new session loads with a "continue the tour" preamble so the agent picks up where it left off
Requirements
  • ElevenLabs agent must have first_message override enabled in platform settings
  • Backend must have ELEVENLABS_API_KEY configured
  • Visitor must grant microphone permission

How It Works

Your App
   └── <FlowEngageProvider siteId="...">
          │
          ├── Boot:  GET /api/widget/bootstrap  → validates siteId, returns config
          ├── Start: POST /api/ai/chat           → loads chat history
          ├── Chat:  Socket.IO                   → real-time messages & agent handoff
          ├── Voice: GET /api/voice/signed-url   → ElevenLabs WebSocket voice session
          └── Track: Socket.IO events            → visitor session, page views

Backend URLs are resolved by FlowEngage; you normally do not set them unless using apiBaseUrl (advanced).


Getting Your Site ID

  1. Log in to the FlowEngage Dashboard
  2. Open Integration Guide or your site / workspace settings
  3. Copy the Site ID for your website

Building the embed

The CDN embed is an IIFE bundle that includes React, all widget code, and inlined CSS. Build it with:

FLOWENGAGE_API_URL=https://your-api-url npx vite build --config vite.embed.config.js

Output lands in dist/flowengage-embed.js. Copy this file to the CDN or the backend public/ folder for serving.

The FLOWENGAGE_API_URL env var is baked into the bundle at build time — the widget uses it as the default API base URL when no data-api-url attribute is present on the script tag.


License

MIT FlowEngage

Keywords