npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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:

  1. Removed type and agentType props - These parameters are no longer used and have been removed from all components
  2. Renamed botServerUrl to webhookUrl - For better clarity and consistency
  3. webhookUrl is now required - Must be provided as a prop
  4. authUrl and username are now direct props - No longer part of data prop for better clarity and type safety
  5. userId is now optional - Widget automatically generates visitor ID for guest users via browser fingerprinting when userId is not provided

New Features:

  1. Guest user support - Users can chat without logging in
    • Automatic visitor ID generation using browser fingerprinting (FingerprintJS + SHA256)
    • auth: false flag automatically added to API requests for guest users
    • Persistent sessions across page reloads for anonymous visitors
  2. Authentication support - Automatic token management with refresh on 401 errors
    • Pass authUrl as a direct prop
    • Widget handles token lifecycle automatically
  3. Enhanced user authentication handling - Smart detection of authenticated vs guest users
    • Compares userId with visitor ID to determine authentication status
    • Automatic auth flag management in all API requests
  4. Enhanced data prop - Support for custom variables passed to backend via data prop
  5. Improved error handling - Better fallback mechanisms and error messages
  6. Direct username prop - 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


  1. Install dependencies

    npm install --legacy-peer-deps
  2. Copy .env.example

    cp .env.example .env
  3. Populate .env

  4. Enable mock mode (optional)

    To test the chat widget without a backend server, set VITE_USE_MOCK_RESPONSES=true in your .env file. 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.js for 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:

  1. Set VITE_USE_MOCK_RESPONSES=true in your .env file
  2. 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


  1. How to run Storybook locally (access at http://localhost:5177)

    npm run storybook
  2. How to build Storybook

    npm run build-storybook
  3. How to serve Storybook

    npm run serve-storybook

Library (how to update and publish)


  1. Commit changes

    git add .
    git commit -m "Your commit message"
  2. 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)
  3. Build as a library (build file at /dist directory)

    npm run build
  4. Copy declaration file to /dist

    cp ./src/declarations/index.d.ts ./dist/index.d.ts
  5. Publish

    npm publish

Library (how to import on your project)


  1. Install package

    npm install @data-netmonk/mona-chat-widget
  2. Import styles on your App.jsx or index.jsx

    import "@data-netmonk/mona-chat-widget/dist/style.css";
  3. 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:

  1. 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
  2. Automatic Guest Detection: The widget automatically detects guest users and:

    • Generates a visitor ID if userId is not provided
    • Adds auth: false flag to all API requests for guest users
    • Uses the visitor ID as the effective user ID throughout the session
  3. 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: false in 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.id exists → Uses provided userId (authenticated user)
  • If currentUser.id is null/undefined → Generates visitor ID (guest user)
  • Backend receives auth: false flag 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:

  1. Initial Authentication: When the widget loads (on Launcher mount), if authUrl is provided as a prop, it automatically calls the auth API:

    POST {authUrl}
    Body: { "user_id": "user123" }
    Response: { "token": "eyJ..." }
  2. 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"
    }
  3. Automatic Token Refresh: If the webhook returns 401 Unauthorized (token expired/revoked), the widget automatically:

    • Calls the authUrl again to get a fresh token
    • Re-initializes the session with the new token
    • Updates the authToken in variables
    • Retries the failed request with the new token
    • This happens transparently without user interaction

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 adds auth: false to variables
  • When userId !== visitorId (authenticated user), no auth flag 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=Engineering

Note: 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)

  1. How to run locally (access at http://localhost:${PORT}/${APP_PREFIX})

    npm run dev
  2. How to build as a standalone app (build file at /dist-app directory)

    npm run build-app
  3. How to serve standalone app (access at http://localhost:${PORT}/${APP_PREFIX})

    npm run serve
  4. How to run on docker (access at http://localhost:${PORT}/${APP_PREFIX})

    docker-compose up --build