@data-netmonk/mona-chat-widget
v2.5.1
Published
Mona Chat Widget Component Library
Readme
Mona Chat Widget
Chat widget package developed by Netmonk data & solution team to be imported in Netmonk products
Recent Updates & Breaking Changes
Latest Version Changes:
⚠️ Breaking Changes:
- Removed
typeandagentTypeprops - These parameters are no longer used and have been removed from all components - Renamed
botServerUrltowebhookUrl- For better clarity and consistency webhookUrlis now required - Must be provided as a propauthUrlandusernameare now direct props - No longer part ofdataprop for better clarity and type safetyuserIdis now optional - Widget automatically generates visitor ID for guest users via browser fingerprinting whenuserIdis not provided
✨ New Features:
- Guest user support - Users can chat without logging in
- Automatic visitor ID generation using browser fingerprinting (FingerprintJS + SHA256)
auth: falseflag automatically added to API requests for guest users- Persistent sessions across page reloads for anonymous visitors
- Authentication support - Automatic token management with refresh on 401 errors
- Pass
authUrlas a direct prop - Widget handles token lifecycle automatically
- Pass
- Enhanced user authentication handling - Smart detection of authenticated vs guest users
- Compares
userIdwith visitor ID to determine authentication status - Automatic
authflag management in all API requests
- Compares
- Enhanced data prop - Support for custom variables passed to backend via
dataprop - Improved error handling - Better fallback mechanisms and error messages
- Direct
usernameprop - Pass username as a top-level prop instead of in data string
📝 Migration Guide:
// Old usage (deprecated)
<ChatWidget
userId="user123"
sourceId="source456"
type="prime"
botServerUrl="https://api.example.com"
/>
// Previous version (with data prop)
<ChatWidget
userId="user123"
sourceId="source456"
webhookUrl="https://api.example.com/webhook"
data="authUrl=https://api.example.com/login/chatwidget~username=John"
/>
// New usage - Authenticated user (current - recommended)
<ChatWidget
userId="user123"
sourceId="source456"
webhookUrl="https://api.example.com/webhook"
authUrl="https://api.example.com/login/chatwidget"
username="John"
data="[email protected]~phone=+1234567890"
/>
// New usage - Guest user (without login)
<ChatWidget
sourceId="source456"
webhookUrl="https://api.example.com/webhook"
username="Guest"
/>
// Widget automatically generates visitor ID and adds auth: false flag
// New usage - Conditional (handles both logged-in and guest users)
<ChatWidget
userId={currentUser?.id} // undefined for guests
sourceId="source456"
webhookUrl="https://api.example.com/webhook"
username={currentUser?.name || "Guest"}
/>🚅 Quick start
Prerequisites
Install dependencies
npm install --legacy-peer-depsCopy .env.example
cp .env.example .envPopulate .env
Enable mock mode (optional)
To test the chat widget without a backend server, set
VITE_USE_MOCK_RESPONSES=truein your.envfile. The widget will respond to messages like:- "start", "hello", "hi", "halo" - Greeting messages
- "help", "bantuan" - Help information
- "terima kasih", "thank you" - Acknowledgments
- "bye", "goodbye" - Farewell messages
- And more! Check
src/components/ChatWidget/utils/helpers.jsfor full list
Mock Mode (Demo without Backend)
The chat widget includes a built-in mock mode for testing and demonstrations without requiring a backend server.
To enable mock mode:
- Set
VITE_USE_MOCK_RESPONSES=truein your.envfile - Run the app normally with
npm run dev
Mock responses include:
- Greetings (hello, hi, halo, start) - with interactive buttons
- Help commands
- Device list with clickable buttons (type "devices" or "show devices")
- Thank you acknowledgments
- Farewells
- Time-based greetings (good morning, etc.)
- And automatically falls back to mock mode if backend fails
Interactive Buttons Demo: Type these messages to see button responses:
- "start" - Welcome message with action buttons
- "show devices" or "devices" - List of devices as clickable buttons
- Click any button to trigger the next action
To add custom mock responses:
Edit the mockBotResponses object in src/components/ChatWidget/utils/mockBotResponses.js
For text-only responses:
"trigger": "Response text"For responses with buttons:
"trigger": {
text: "Your message here",
buttons: [
{ title: "Button 1", payload: "action_1" },
{ title: "Button 2", payload: "action_2" },
{ title: "Link Button", url: "https://example.com" }
]
}Storybook
How to run Storybook locally (access at http://localhost:5177)
npm run storybookHow to build Storybook
npm run build-storybookHow to serve Storybook
npm run serve-storybook
Library (how to update and publish)
Commit changes
git add . git commit -m "Your commit message"Update version
npm version patch # for bug fixes (1.0.0 -> 1.0.1)npm version minor # for new features (1.0.0 -> 1.1.0)npm version major # for breaking changes (1.0.0 -> 2.0.0)Build as a library (build file at
/distdirectory)npm run buildCopy declaration file to
/distcp ./src/declarations/index.d.ts ./dist/index.d.tsPublish
npm publish
Library (how to import on your project)
Install package
npm install @data-netmonk/mona-chat-widgetImport styles on your
App.jsxorindex.jsximport "@data-netmonk/mona-chat-widget/dist/style.css";Import & use component
import { ChatWidget } from "@data-netmonk/mona-chat-widget"; function App() { return ( <ChatWidget userId="user123" sourceId="691e1b5952068ff7aaeccffc9" webhookUrl="https://your-backend-url.com" /> ); }
Component Props
Required Props
| Prop | Type | Description |
|------|------|-------------|
| sourceId | string | Required. Source/channel identifier for the chat |
| webhookUrl | string | Required. Backend webhook URL |
Optional Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| userId | string | Generated visitor ID | Unique identifier for the user. Optional - if not provided, a unique visitor ID is automatically generated using browser fingerprinting for guest users |
| authUrl | string | - | Authentication endpoint URL for token-based authentication |
| username | string | - | Username for the session (sent to backend in variables) |
| data | string | - | Additional custom variables in format key1=value1~key2=value2 |
| width | string | "25vw" | Widget width (CSS value) |
| height | string | "90vh" | Widget height (CSS value) |
| right | string | "1.25rem" | Distance from right edge |
| bottom | string | "1.25rem" | Distance from bottom edge |
| zIndex | number | 2000 | CSS z-index for widget positioning |
| position | string | "fixed" | CSS position ("fixed" or "relative") |
| onToggle | function | - | Callback when widget opens/closes: (isOpen: boolean) => void |
Guest User Support
The widget now supports guest users (users who haven't logged in or before logging in). When userId is not provided, the widget automatically generates a unique visitor ID using browser fingerprinting.
How it works:
Browser Fingerprinting: Uses FingerprintJS to generate a unique identifier based on:
- Browser characteristics (user agent, screen resolution, timezone, etc.)
- Incognito/private browsing detection
- Combined into a SHA256 hash for consistency
Automatic Guest Detection: The widget automatically detects guest users and:
- Generates a visitor ID if
userIdis not provided - Adds
auth: falseflag to all API requests for guest users - Uses the visitor ID as the effective user ID throughout the session
- Generates a visitor ID if
Persistent Sessions: The visitor ID remains consistent across page reloads (unless browser fingerprint changes or user clears data)
When to use guest mode:
- Public-facing websites where users can chat without logging in
- Support widgets for anonymous visitors
- Pre-login customer service interactions
- Any scenario where user authentication is optional
When to provide userId:
- Users who are logged into your application
- When you need to track chat history across devices
- When authentication is required for personalized responses
- Enterprise or internal applications
Usage Examples
Basic Usage (Authenticated User)
import { ChatWidget } from "@data-netmonk/mona-chat-widget";
import "@data-netmonk/mona-chat-widget/dist/style.css";
function App() {
return (
<ChatWidget
userId="user123"
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
/>
);
}Guest User (Without Login)
For anonymous visitors or users who haven't logged in:
import { ChatWidget } from "@data-netmonk/mona-chat-widget";
import "@data-netmonk/mona-chat-widget/dist/style.css";
function App() {
return (
<ChatWidget
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
/>
);
}What happens:
- Widget automatically generates a visitor ID using browser fingerprinting
- All API requests include
auth: falsein variables to indicate guest user - No login required - users can start chatting immediately
Conditional userId (Logged in or Guest)
Handle both logged-in users and guests dynamically:
import { ChatWidget } from "@data-netmonk/mona-chat-widget";
import "@data-netmonk/mona-chat-widget/dist/style.css";
function App() {
const currentUser = getCurrentUser(); // Your auth function
return (
<ChatWidget
userId={currentUser?.id} // Provide userId if logged in, undefined if not
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
username={currentUser?.name}
/>
);
}Behavior:
- If
currentUser.idexists → Uses provided userId (authenticated user) - If
currentUser.idisnull/undefined→ Generates visitor ID (guest user) - Backend receives
auth: falseflag only for guest users
With Custom Variables
Pass custom user data like email, phone number, etc. to the backend:
<ChatWidget
userId="user123"
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
username="John Doe"
data="[email protected]"
/>Variables sent to backend:
{
"chat_id": "...",
"session_id": "...",
"user_id": "user123",
"message": "Hello",
"type": "text",
"variables": {
"username": "John Doe",
"telephone_number": "+628123456789",
"email": "[email protected]"
}
}}
#### With Authentication (NEW!)
The widget supports automatic authentication with token refresh on expiry:
```jsx
<ChatWidget
userId="user123"
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
authUrl="https://api.example.com/login/chatwidget"
username="John Doe"
/>How authentication works:
Initial Authentication: When the widget loads (on Launcher mount), if
authUrlis provided as a prop, it automatically calls the auth API:POST {authUrl} Body: { "user_id": "user123" } Response: { "token": "eyJ..." }Session Initialization: After getting the token, the widget calls the init endpoint to establish the session:
POST {webhookUrl}/{sourceId}/init Body: { "session_id": "...", "user_id": "user123", "token": "eyJ...", "username": "John Doe" }Automatic Token Refresh: If the webhook returns 401 Unauthorized (token expired/revoked), the widget automatically:
- Calls the
authUrlagain to get a fresh token - Re-initializes the session with the new token
- Updates the
authTokenin variables - Retries the failed request with the new token
- This happens transparently without user interaction
- Calls the
Combined example with auth and custom variables:
<ChatWidget
userId="user123"
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
authUrl="https://api.example.com/login/chatwidget"
username="John"
data="[email protected]~phone=+628123456789"
/>Auth Flag (auth variable):
The widget automatically adds an auth: false flag to the variables object when the user is a guest (not authenticated):
- When
userId === visitorId(browser fingerprint), the widget addsauth: falseto variables - When
userId !== visitorId(authenticated user), noauthflag is added to variables
Guest user example (userId equals browser fingerprint):
{
"chat_id": "...",
"session_id": "...",
"user_id": "visitor_abc123",
"message": "Hello",
"type": "text",
"variables": {
"username": "Guest",
"auth": false
}
}Authenticated user example (userId is different from browser fingerprint):
{
"chat_id": "...",
"session_id": "...",
"user_id": "user123",
"message": "Hello",
"type": "text",
"variables": {
"username": "John Doe",
"email": "[email protected]"
}
}This auth: false flag is automatically added in:
- Session initialization payload (when guest)
- All message requests (when guest)
- Button postback requests (when guest)
Note: The data prop is for additional custom variables only. Required parameters (userId, sourceId, webhookUrl) and common optional parameters (authUrl, username) should be passed as direct props for better type safety and clarity.
Custom Styling
<ChatWidget
userId="user123" // Optional
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
width="400px"
height="600px"
right="20px"
bottom="20px"
zIndex={9999}
/>Embedded in Layout (Relative Positioning)
<div style={{ display: 'grid', gridTemplateColumns: '1fr 400px' }}>
<div>Main content</div>
<ChatWidget
userId="user123" // Optional
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
position="relative"
width="100%"
height="100vh"
/>
</div>With Toggle Callback
function App() {
const handleToggle = (isOpen) => {
console.log('Chat widget is', isOpen ? 'open' : 'closed');
// Track analytics, update UI, etc.
};
return (
<ChatWidget
userId="user123" // Optional
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
onToggle={handleToggle}
/>
);
}Full-Screen Widget
<ChatWidget
userId="user123" // Optional - supports guest users
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
width="100vw"
height="100vh"
right="0"
bottom="0"
/>Data Prop Format & Helper Function
The data prop allows you to pass additional custom variables via a single string. This is especially useful when you need to dynamically pass user-specific data or pass it through URL parameters.
Format: key=value pairs separated by ~
Example data string:
[email protected]~phone=+1234567890~department=EngineeringNote: authUrl and username are now direct props and should not be included in the data string.
Building Data String Programmatically
Instead of manually constructing the data string, you can create a helper function to build it dynamically. This approach is recommended for production applications as it:
- Prevents syntax errors in the data string format
- Makes the code more maintainable and readable
- Allows for conditional inclusion of parameters
- Handles URL encoding automatically if needed
Create a helper function (src/helpers/chatWidget.js or similar):
/**
* Builds the data string for ChatWidget component
* @param {Object} params - Object containing all parameters
* @param {string} params.email - Optional: User's email address
* @param {string} params.phone - Optional: User's phone number
* @param {Object} params.customFields - Optional: Any additional custom fields as key-value pairs
* @returns {string} Formatted data string for ChatWidget (always returns a string)
*
* @example
* // Returns: "[email protected]~phone=+1234567890~department=Engineering"
* buildChatWidgetData({
* email: "[email protected]",
* phone: "+1234567890",
* customFields: { department: "Engineering" }
* });
*/
export const buildChatWidgetData = ({
email,
phone,
customFields = {}
}) => {
const parts = [];
// Add standard fields
if (email) {
parts.push(`email=${encodeURIComponent(email)}`);
}
if (phone) {
parts.push(`phone=${encodeURIComponent(phone)}`);
}
// Add any custom fields dynamically
// Note: customFields is just a convenience parameter for the helper function
// Each field will be flattened into the string format: key=value~key2=value2
Object.entries(customFields).forEach(([key, value]) => {
if (value) {
parts.push(`${key}=${encodeURIComponent(String(value))}`);
}
});
// Returns a string like: "[email protected]~phone=+1234567890~department=Engineering"
return parts.join("~");
};Important: The customFields parameter is NOT passed as an object to the widget. It's just a convenient way to pass multiple additional fields to the helper function. The function flattens everything into a single string format.
Usage in your application:
import { ChatWidget } from "@data-netmonk/mona-chat-widget";
import "@data-netmonk/mona-chat-widget/dist/style.css";
import { buildChatWidgetData } from "./helpers/chatWidget";
function App() {
// Get user data from your auth system, state, or props
const user = {
id: "user123",
name: "John Doe",
email: "[email protected]",
phone: "+628123456789"
};
// Build the data string with custom variables only
const customData = buildChatWidgetData({
email: user.email,
phone: user.phone,
customFields: {
department: "Engineering",
role: "Developer",
company: "Acme Corp"
}
});
// customData is now a STRING like:
// "[email protected]~phone=%2B628123456789~department=Engineering~role=Developer~company=Acme%20Corp"
return (
<ChatWidget
userId={user.id}
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl="https://api.example.com/webhook"
authUrl="https://api.example.com/login/chatwidget" // Direct prop
username={user.name} // Direct prop
data={customData} // Only additional variables
/>
);
}With conditional authentication:
function App() {
const authUrl = import.meta.env.VITE_CHAT_AUTH_ENABLED === "true"
? import.meta.env.VITE_CHAT_AUTH_URL
: null;
const customData = buildChatWidgetData({
email: getCurrentUser().email,
customFields: {
department: "Sales"
}
});
return (
<ChatWidget
userId={getCurrentUser().id}
sourceId="691e1b5952068ff7aaeccffc9"
webhookUrl={import.meta.env.VITE_WEBHOOK_URL}
authUrl={authUrl} // Direct prop (conditionally set)
username={getCurrentUser().name} // Direct prop
data={customData} // Only additional variables
/>
);
}The helper function handles:
- ✅ Proper formatting with
~separators - ✅ URL encoding for special characters
- ✅ Conditional parameter inclusion (only adds if value exists)
- ✅ Support for dynamic custom fields
- ✅ Type safety and documentation via JSDoc comments
Standalone app (for demonstration)
How to run locally (access at
http://localhost:${PORT}/${APP_PREFIX})npm run devHow to build as a standalone app (build file at
/dist-appdirectory)npm run build-appHow to serve standalone app (access at
http://localhost:${PORT}/${APP_PREFIX})npm run serveHow to run on docker (access at
http://localhost:${PORT}/${APP_PREFIX})docker-compose up --build
