A configurable chatbot setup for quick integration of RAG-powered Q&A and rating system
npm install @snf/qa-bot-coreA simple React chatbot component for Q&A applications with built-in rating system.
Pre-configured wrapper around react-chatbotify - Just provide your API endpoints and you're done.
``bash`
npm install @snf/qa-bot-core
#### Basic Usage
Just provide required props:
`jsx
import QABot from '@snf/qa-bot-core';
function App() {
return (
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={true}
/>
);
}
`
#### Full Configuration
Customize appearance and behavior:
`jsx
qaEndpoint="https://your-api.com/chat"
ratingEndpoint="https://your-api.com/rating"
welcomeMessage="Hello! How can I help you today?"
// Authentication (required)
isLoggedIn={true}
allowAnonAccess={false}
actingUser="user@example.com"
loginUrl="/login"
// Window control
open={false}
onOpenChange={(isOpen) => console.log('Chat is now', isOpen ? 'open' : 'closed')}
// Branding
primaryColor="#24292e"
secondaryColor="#586069"
botName="Demo Assistant"
logo="https://github.com/github.png"
// Messages
placeholder="Type your message here..."
errorMessage="Sorry, something went wrong"
tooltipText="Ask me anything!"
// Layout
embedded={false}
// Footer
footerText="Powered by Demo Corp"
footerLink="https://demo.com"
/>
`
`javascript
import { qaBot } from '@snf/qa-bot-core';
const bot = qaBot({
target: document.getElementById('bot-container'),
apiKey: 'your-api-key',
qaEndpoint: 'https://your-api.com/chat',
ratingEndpoint: 'https://your-api.com/rating',
welcomeMessage: "Hello! How can I help you today?",
isLoggedIn: true,
primaryColor: '#24292e',
secondaryColor: '#586069',
botName: 'Demo Assistant',
logo: 'https://github.com/github.png'
});
// Programmatic control
bot.openChat();
bot.closeChat();
bot.addMessage('Hello from code!');
bot.destroy();
`
`html`
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| apiKey | string | ✅ | API key for your Q&A service |qaEndpoint
| | string | ✅ | Q&A API endpoint URL |welcomeMessage
| | string | ✅ | Initial greeting message |isLoggedIn
| | boolean | ✅ | Whether the user is logged in. Controls header icon and Q&A access gating |ratingEndpoint
| | string | ❌ | Rating API endpoint URL (enables thumbs up/down) |allowAnonAccess
| | boolean | ❌ | Allow Q&A access even when not logged in (default: false) |actingUser
| | string | ❌ | Acting user identifier sent to backend as X-Acting-User header and acting_user body field |loginUrl
| | string | ❌ | Login URL for the login button when not logged in (default: /login) |open
| | boolean | ❌ | Control chat window open/closed state |onOpenChange
| | function | ❌ | Callback when chat window state changes: (open: boolean) => void |primaryColor
| | string | ❌ | Main theme color (default: #1a5b6e) |secondaryColor
| | string | ❌ | Secondary theme color (default: #107180) |botName
| | string | ❌ | Bot display name (default: Q&A Bot) |logo
| | string | ❌ | Bot avatar URL (default: /chat-icon.svg) |placeholder
| | string | ❌ | Input placeholder text |errorMessage
| | string | ❌ | Error state message |tooltipText
| | string | ❌ | Tooltip text for chat toggle |embedded
| | boolean | ❌ | Embedded mode (default: false) |footerText
| | string | ❌ | Footer text |footerLink
| | string | ❌ | Footer link URL |customFlow
| | Flow | ❌ | Custom flow steps to merge with built-in Q&A flow (see Custom Flows section) |onAnalyticsEvent
| | function | ❌ | Analytics callback: (event: QABotAnalyticsEvent) => void |
The bot manages authentication state through the isLoggedIn prop:
- Logged in (isLoggedIn={true}): Shows user icon in header, Q&A is fully accessible
- Not logged in (isLoggedIn={false}): Shows login button in header, Q&A is gated (prompts to log in)
Example:
`jsx
const [userLoggedIn, setUserLoggedIn] = useState(false);
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={userLoggedIn}
loginUrl="https://your-app.com/login"
/>
`
When the user is not logged in (isLoggedIn={false}):loginUrl
- The login button appears in the chat header
- Clicking it opens the in a new tab
- Q&A flow is gated and prompts users to log in
When the user is logged in (isLoggedIn={true}):
- A user icon appears in the chat header
- Users can ask questions normally
#### Anonymous Access
If you want to allow Q&A access without requiring login, use the allowAnonAccess prop:
`jsx`
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={false}
allowAnonAccess={true}
/>
This bypasses the login gate for Q&A while still showing the login button in the header. Note that custom flows (if any) are unaffected by this setting.
Control the chat window open/closed state programmatically:
`jsx
const [chatOpen, setChatOpen] = useState(false);
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={true}
open={chatOpen}
onOpenChange={setChatOpen}
/>
`
The open prop provides two-way binding:open={true}
- Setting opens the chat windowopen={false}
- Setting closes the chat windowonOpenChange
- User interactions (clicking open/close buttons) trigger
You can also control the bot imperatively using a ref:
`jsx
const botRef = useRef();
apiKey="your-api-key"
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={true}
/>
// Available methods:
botRef.current.openChat(); // Open the chat window
botRef.current.closeChat(); // Close the chat window
botRef.current.toggleChat(); // Toggle chat window state
botRef.current.addMessage("Hello!"); // Inject a message into the chat
botRef.current.setBotEnabled(false); // Change enabled state
`
The bot supports two display modes:
Floating Mode (default):
- Shows as a toggle button in the bottom-right corner
- Chat window can be opened/closed by clicking the button
- Overlays on top of page content
Embedded Mode:
- Displays inline within your page layout
- Always visible (no toggle button)
- Takes full width of its container
- Chat window cannot be closed
Example of embedded mode:
`jsx`
Customer Support
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={true}
embedded={true}
/>
Note: When embedded={true}, the open and onOpenChange props are ignored, and the imperative methods openChat(), closeChat(), and toggleChat() have no effect.
You can extend the bot with custom flow steps using the customFlow prop. This allows you to add ticket creation, feedback forms, or other interactive workflows that merge with the built-in Q&A flow.
`jsx
import QABot from '@snf/qa-bot-core';
const myCustomFlow = {
submit_ticket: {
message: "I'll help you submit a ticket. What's the issue?",
path: "ticket_details"
},
ticket_details: {
message: "Thanks! Your ticket has been submitted.",
path: "start"
}
};
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={true}
customFlow={myCustomFlow}
/>
`
Custom flows are merged into the flow object, so your custom steps can reference built-in steps and vice versa.
#### Flow Settings Utility
When building custom flows, you may encounter a react-chatbotify quirk where chatDisabled state persists across step transitions. The applyFlowSettings utility helps manage this:
`javascript
import { applyFlowSettings } from '@snf/qa-bot-core';
const myFlow = {
choose_option: {
message: "Select an option:",
options: ["Option A", "Option B"],
path: "next_step"
},
next_step: {
message: "You selected an option!",
path: "start"
}
};
// Auto-disable chat input on steps with options/checkboxes
const processedFlow = applyFlowSettings(myFlow, {
disableOnOptions: true
});
customFlow={processedFlow}
/>
`
The disableOnOptions: true setting automatically sets chatDisabled: true for steps that have options or checkboxes, and chatDisabled: false for steps without them (unless you've explicitly set chatDisabled yourself).
#### History Tracking for Custom Flows
When building custom flows, you may want certain important messages to be saved in session history so they can be restored when a user revisits a previous session. By default, messages defined with the message: property in flow steps may not be tracked in history.
Use the withHistory and withHistoryFn helpers to ensure messages are tracked:
`javascript
import { withHistory, withHistoryFn } from '@snf/qa-bot-core';
const myFlow = {
// Static message - use withHistory()
ask_email: {
message: withHistory("Please enter your email address:"),
path: "next_step"
},
// Dynamic message - use withHistoryFn()
show_summary: {
message: withHistoryFn(() => {
const data = getFormData();
return Summary:\nName: ${data.name}\nEmail: ${data.email};
}),
options: ["Submit", "Cancel"],
path: "submit"
},
// Success message with important data (e.g., ticket links)
success: {
message: withHistoryFn(() => generateSuccessMessage(result)),
options: ["Back to Menu"],
path: "start"
}
};
`
When to use these helpers:
- withHistory(string) - For static messages you want restored in historywithHistoryFn(fn)
- - For dynamic/computed messages (summaries, API responses with links)
Tip: You don't need to wrap every message - only the important ones that would be valuable when restoring a session (like ticket confirmations, summaries, or API responses).
The bot automatically manages conversation sessions with unique session IDs:
- Each bot instance generates a unique session ID when mounted
- The session ID is included in API request headers (X-Session-ID)
- A "New Chat" button in the footer allows users to start fresh conversations
- Clicking "New Chat" generates a new session ID and clears the conversation history
- This allows your backend to track conversation continuity and user journeys
Session Headers Sent to API:
``
X-Session-ID: qa_bot_session_abc123
X-Query-ID: query_xyz789
The session ID persists across page refreshes, but clicking "New Chat" creates a completely new session. This is useful for:
- Starting a new topic without the bot referencing previous context
- Resetting conversation state
- Allowing users to have multiple distinct conversations
The bot fires analytics events via an optional callback prop, allowing you to wire up GTM, GA4, or any analytics provider without adding dependencies to the library.
`jsx`
qaEndpoint="https://your-api.com/chat"
welcomeMessage="Hello! How can I help you today?"
isLoggedIn={true}
onAnalyticsEvent={(event) => {
// Push to GTM dataLayer
window.dataLayer?.push({
event: event.type,
...event
});
}}
/>
Event Types:
| Event | When Fired | Key Fields |
|-------|------------|------------|
| chatbot_open | Chat window opened | sessionId |chatbot_close
| | Chat window closed | sessionId, messageCount, durationMs |chatbot_new_chat
| | User clicks "New Chat" | sessionId, previousMessageCount |chatbot_question_sent
| | User submits question | sessionId, queryId, questionLength |chatbot_answer_received
| | API returns response | sessionId, queryId, responseTimeMs, responseLength, hasMetadata |chatbot_answer_error
| | API call fails | sessionId, queryId, errorType |chatbot_rating_sent
| | User rates response | sessionId, queryId, rating |chatbot_login_prompt_shown
| | Login gate displayed | sessionId |
All events include type and timestamp. The sessionId is auto-injected when available.
TypeScript:
`typescript`
import type { QABotAnalyticsEvent, QABotAnalyticsEventType } from '@snf/qa-bot-core';
The bot includes a lightweight logging utility that's disabled by default but can be enabled at runtime for troubleshooting. Logs are controlled via localStorage, making it easy to debug in any environment (including production) without rebuilding.
Enable debug logging:
`javascript`
localStorage.setItem('QA_BOT_DEBUG', 'true');
Disable debug logging (default):
`javascript`
localStorage.removeItem('QA_BOT_DEBUG');
When enabled, you'll see styled console output for:
- Library version on load
- Session lifecycle events (CREATED, RESET, RESTORED)
- History operations (message tracking, session restore)
- Message tracking (which messages are being saved to history)
Errors and warnings always display regardless of the debug flag.
Your Q&A endpoint should accept POST requests:
`json
POST /your-qa-endpoint
Content-Type: application/json
X-API-KEY: your-api-key
{
"query": "User's question here"
}
`
And return:
`json`
{
"response": "Bot's answer with markdown support",
"sessionId": "session_123",
"queryId": "query_456"
}
For thumbs up/down feedback:
`json
POST /your-rating-endpoint
Content-Type: application/json
X-API-KEY: your-api-key
{
"sessionId": "session_123",
"queryId": "query_456",
"rating": 1 // 1 for 👍, 0 for 👎
}
`
The project includes an interactive demo that showcases all features:
`bashInstall dependencies
npm install
The demo runs at
http://localhost:3000 and includes:Configuration Status
- Shows which environment variables are configured
- Displays API endpoints for verification
Dynamic Props
- Toggle
isLoggedIn prop to simulate login/logout states
- Toggle open prop to control chat window state
- Toggle embedded prop to switch between floating and embedded modesComponent API
- Test the imperative
addMessage() method
- Inject custom messages into the chatEnvironment Variables
Create a
.env file in the project root:`bash
REACT_APP_API_KEY=your-api-key
REACT_APP_QA_ENDPOINT=https://your-api.com/chat
REACT_APP_RATING_ENDPOINT=https://your-api.com/rating # optional
`$3
`bash
Build library
npm run build:lib
``MIT License