@developer.notchatbot/webchat v1.0.8
π· WebChat Widget
A beautiful, embeddable chatbot widget built with React, TypeScript, Vite, pnpm and Tailwind CSS that can be easily integrated into any website with just one file.
β¨ Features
- π¦ Single File Bundle: Everything in one file - no separate CSS needed!
- π· TypeScript: Full type safety with strict typing and excellent IntelliSense
- βοΈ React 18: Component-based architecture for maintainability
- π¨ Tailwind CSS: Utility-first styling with prefixed classes (
ncb-) - β‘ Vite: Lightning-fast development and optimized builds
- π¦ pnpm: Efficient package management and faster installs
- π§ Easy Integration: Add to any website with just one script tag
- π¨ Modern Design: Beautiful, responsive UI that works on all devices
- π οΈ Customizable: Configure colors, text, and behavior to match your brand
- β¨ Smooth Animations: Typing indicators and smooth transitions
- π± Mobile Responsive: Optimized for mobile and desktop
- π API Ready: Built-in support for chat API integration
- π« Zero Conflicts: Prefixed CSS classes prevent style conflicts
- π‘οΈ Type Safe: Catch errors at compile time with TypeScript
π¦ Quick Start
1. Add the widget to your website
<div id="webchat-component"></div>
<script src="https://your-cdn.com/webchat-bundle.min.umd.cjs"></script>
<script>
WebChat.initialize({
title: "Customer Support",
placeholder: "Ask us anything...",
primaryColor: "#667eea"
});
</script>2. That's it! π
The chatbot button will appear in the bottom-right corner of your page. CSS is automatically injected!
βοΈ Configuration Options
interface WebChatConfig {
title?: string; // Chat window title
placeholder?: string; // Input placeholder text
primaryColor?: string; // Primary theme color
apiKey?: string; // Your chatbot UID (required for API)
position?: 'bottom-right' | 'bottom-left'; // Widget position
initialMessage?: string; // Custom initial bot message
closeButtonIcon?: 'default' | 'text' | 'custom'; // Close button type
closeButtonText?: string; // Text for close button (when type is 'text')
closeButtonCustomIcon?: string; // Custom icon SVG or URL (when type is 'custom')
marginBottom?: number; // Distance from bottom edge in pixels (default: 16)
marginSide?: number; // Distance from left/right edge in pixels (default: 16)
mobile?: WebChatPositionConfig; // Mobile-specific position settings
desktop?: WebChatPositionConfig; // Desktop-specific position settings
}
interface WebChatPositionConfig {
position?: 'bottom-right' | 'bottom-left';
marginBottom?: number;
marginSide?: number;
}
WebChat.initialize({
title: "Chat Assistant",
placeholder: "Type your message...",
primaryColor: "#007bff",
apiKey: "your-chatbot-uid", // Chatbot UID from admin panel
position: "bottom-right",
initialMessage: "Β‘Hola! π Soy tu asistente virtual. ΒΏEn quΓ© puedo ayudarte hoy?",
closeButtonIcon: "default", // or "text" or "custom"
marginBottom: 20, // Distance from bottom edge (default: 16px)
marginSide: 20, // Distance from side edge (default: 16px)
// Device-specific overrides
mobile: {
position: "bottom-left",
marginBottom: 80,
marginSide: 15
},
desktop: {
position: "bottom-right",
marginBottom: 30,
marginSide: 30
}
});π¨ Customization
Colors
WebChat.initialize({
primaryColor: "#ff6b6b", // Custom brand color
// ... other options
});API Integration
The WebChat widget automatically detects the environment and uses the appropriate API endpoints:
- Development (localhost):
http://localhost:3001/api/webchat - Production (any other domain):
https://next.notchatbot.com/api/webchat
WebChat.initialize({
apiKey: "your-chatbot-uid", // Chatbot UID from your Next.js admin panel
// Endpoints are automatically configured based on environment
// No need to specify apiEndpoint manually
});Manual Endpoint Override (Advanced)
If you need to override the automatic endpoint detection:
// This is handled automatically, but you can check the environment:
import { getChatEndpoint, getConversationEndpoint } from './src/config/endpoints';
console.log('Chat endpoint:', getChatEndpoint());
console.log('Conversation endpoint:', getConversationEndpoint());π¬ Initial Message Customization
Customize the first message your users see when they open the chat:
WebChat.initialize({
title: "MiTienda Support",
// Custom welcome message with your brand's personality
initialMessage: "Β‘Hola! π Soy el asistente de MiTienda.\n\nΒΏBuscas algΓΊn producto especΓfico? Β‘Estoy aquΓ para ayudarte!\n\nPuedes preguntarme sobre:\nβ’ Productos disponibles\nβ’ Precios y ofertas\nβ’ EnvΓos y devoluciones\nβ’ Soporte tΓ©cnico\n\nΒΏEn quΓ© puedo ayudarte hoy? π",
apiKey: "your-api-key"
});β Close Button Customization
Customize the appearance of the close button in the chat header:
Option 1: Default X Icon (SVG)
WebChat.initialize({
closeButtonIcon: "default" // Standard X icon
});Option 2: Custom Text
WebChat.initialize({
closeButtonIcon: "text",
closeButtonText: "CERRAR" // or "β", "CLOSE", etc.
});Option 3: Custom SVG Icon
WebChat.initialize({
closeButtonIcon: "custom",
closeButtonCustomIcon: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>'
});Option 4: Custom Icon from URL
WebChat.initialize({
closeButtonIcon: "custom",
closeButtonCustomIcon: "https://yoursite.com/icons/close-icon.svg"
});π Position and Margins Customization
Control where the chat widget appears on the screen and how much space it has from the edges:
Bottom Right Position (Default)
WebChat.initialize({
position: "bottom-right",
marginBottom: 20, // 20px from bottom edge
marginSide: 25, // 25px from right edge
apiKey: "your-api-key"
});Bottom Left Position
WebChat.initialize({
position: "bottom-left",
marginBottom: 30, // 30px from bottom edge
marginSide: 20, // 20px from left edge
apiKey: "your-api-key"
});Position Examples for Different Layouts
E-commerce Site (avoid cart button)
WebChat.initialize({
position: "bottom-left",
marginBottom: 20,
marginSide: 20,
apiKey: "your-api-key"
});Corporate Website (professional look)
WebChat.initialize({
position: "bottom-right",
marginBottom: 40, // More space from bottom
marginSide: 30, // More space from side
apiKey: "your-api-key"
});Mobile-First Design (more accessible)
WebChat.initialize({
position: "bottom-right",
marginBottom: 80, // Avoid mobile navigation
marginSide: 15, // Less space on mobile
apiKey: "your-api-key"
});π° Cost Optimization
The WebChat widget is optimized to minimize API costs:
- Lazy Loading: Conversation history is only fetched when the chat is opened, not on page load
- Smart Caching: Once loaded, conversation history is cached to avoid duplicate fetches
- Conditional Fetching: Only fetches when a conversation actually exists
This ensures users can visit your e-commerce site without triggering unnecessary API calls.
π±π» Device-Specific Configurations
Configure different positions and margins for mobile and desktop devices:
Complete Device-Specific Setup
WebChat.initialize({
title: "Customer Support",
apiKey: "your-api-key",
// Global fallback settings (used if device-specific not provided)
position: "bottom-right",
marginBottom: 20,
marginSide: 20,
// Desktop-specific settings
desktop: {
position: "bottom-right",
marginBottom: 30, // More space on desktop
marginSide: 40 // More space from edge
},
// Mobile-specific settings
mobile: {
position: "bottom-left", // Different position on mobile
marginBottom: 80, // Avoid mobile navigation bars
marginSide: 15 // Less space on smaller screens
}
});E-commerce Site Example
WebChat.initialize({
title: "Shopping Assistant",
apiKey: "your-api-key",
// Desktop: bottom-right (standard)
desktop: {
position: "bottom-right",
marginBottom: 25,
marginSide: 25
},
// Mobile: bottom-left (avoid cart/menu buttons)
mobile: {
position: "bottom-left",
marginBottom: 90, // Clear mobile navigation
marginSide: 15
}
});Corporate Website Example
WebChat.initialize({
title: "Business Support",
apiKey: "your-api-key",
// Consistent position, different margins
position: "bottom-right", // Global fallback
desktop: {
marginBottom: 40, // Professional spacing
marginSide: 50
},
mobile: {
marginBottom: 70, // Clear mobile UI elements
marginSide: 20
}
});π¨βπ» Developer Guide
π Getting Started
Prerequisites
- Node.js 18+ (for modern React and TypeScript)
- pnpm 8+ (recommended package manager - faster than npm/yarn)
- Git (for version control)
- VS Code (recommended IDE with TypeScript support)
Initial Setup
# 1. Clone the repository
git clone https://github.com/your-username/webchat-widget.git
cd webchat-widget
# 2. Install dependencies with pnpm (much faster than npm)
pnpm install
# 3. Start development server
pnpm devThe development server will start at http://localhost:3000 and automatically open example.html.
π§ Development Workflow
1. Understanding the Codebase Structure
src/
βββ components/ # React TypeScript components
β βββ ChatBot.tsx # Main container component
β βββ ChatButton.tsx # Floating chat button
β βββ ChatWindow.tsx # Chat window container
β βββ ChatHeader.tsx # Window header with close button
β βββ MessageList.tsx # Scrollable message list
β βββ Message.tsx # Individual message bubble
β βββ MessageInput.tsx # Input field with send button
β βββ TypingIndicator.tsx # Animated typing dots
βββ types.ts # TypeScript interfaces and types
βββ index.tsx # Main entry point (exports WebChat API)
βββ vite-env.d.ts # Type declarations for Vite
βββ styles.css # Tailwind CSS directives2. Adding New Features
Step 1: Update Types (if needed)
// src/types.ts
export interface NewFeatureProps {
enabled: boolean;
config?: SomeConfig;
}Step 2: Create/Modify Components
// src/components/NewFeature.tsx
import React from 'react';
import type { NewFeatureProps } from '../types';
const NewFeature: React.FC<NewFeatureProps> = ({ enabled, config }) => {
// Component logic here
return (
<div className="nbc-new-feature">
{/* Use nbc- prefix for all CSS classes */}
</div>
);
};
export default NewFeature;Step 3: Add to Main Component
// src/components/ChatBot.tsx
import NewFeature from './NewFeature';
// Use the new component in ChatBot3. Styling Guidelines
- Always use
nbc-prefix for CSS classes to avoid conflicts - Use Tailwind utilities whenever possible
- Follow the existing pattern for consistent styling
// β
Good - uses nbc- prefix
<div className="nbc-bg-blue-500 nbc-text-white nbc-p-4">
// β Bad - no prefix, will conflict with host site
<div className="bg-blue-500 text-white p-4">4. TypeScript Best Practices
- Define interfaces for all component props
- Use strict typing for functions and variables
- Leverage IntelliSense for better development experience
// β
Good - strict typing
const handleMessage = (message: string): void => {
// Function implementation
};
// β Bad - no typing
const handleMessage = (message) => {
// Function implementation
};ποΈ Building & Compilation
Development Build
# Start development server with hot reload
pnpm dev
# Access at: http://localhost:3000
# Changes are reflected immediatelyProduction Build
# Build for production (TypeScript compilation + bundling)
pnpm build
# Output: dist/webchat-bundle.min.umd.cjs (single file)
# Size: ~159KB (50KB gzipped)Build Process Explanation
- TypeScript Compilation (
tsc) - Type checking and compilation - Vite Bundling - Bundles React, CSS, and all dependencies
- CSS Injection - Inlines CSS into JavaScript for single-file output
- Minification - Optimizes and compresses the output
π§ͺ Testing the Compiled Version
Option 1: Preview Server
# Build and start preview server
pnpm build
pnpm preview
# Access at: http://localhost:4173
# Tests the actual production buildOption 2: Local Testing
# After building, test locally
pnpm build
# Open example/production.html in browser
# Or serve with any static file server
python3 -m http.server 8000
# Then visit: http://localhost:8000/example/production.htmlOption 3: Integration Testing
Create a test HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Widget Test</title>
</head>
<body>
<h1>Testing WebChat Widget</h1>
<div id="chat-test"></div>
<!-- Load your built widget -->
<script src="./dist/webchat-bundle.min.umd.cjs"></script>
<script>
// Test the widget
WebChat.initialize({
elementId: "chat-test",
title: "Test Chat",
placeholder: "Test message...",
primaryColor: "#007bff"
});
</script>
</body>
</html>π¦ Publishing to npm
1. Prepare for Publishing
# 1. Update version in package.json
npm version patch # or minor, major
# 2. Build the production version
pnpm build
# 3. Test the build
pnpm preview2. Configure package.json for npm
{
"name": "@yourorg/webchat-widget",
"version": "1.0.0",
"description": "Embeddable React TypeScript chatbot widget",
"main": "dist/webchat-bundle.min.umd.cjs",
"types": "dist/types/index.d.ts",
"files": [
"dist",
"README.md"
],
"keywords": ["chatbot", "widget", "react", "typescript", "embeddable"],
"repository": {
"type": "git",
"url": "https://github.com/yourorg/webchat-widget.git"
},
"publishConfig": {
"access": "public"
}
}3. Publish to npm
# 1. Login to npm (if not already)
npm login
# 2. Publish the package
npm publish
# 3. Verify publication
npm view @yourorg/webchat-widget4. Using Published Package
<!-- From npm CDN -->
<script src="https://unpkg.com/@yourorg/webchat-widget/dist/webchat-bundle.min.umd.cjs"></script>
<!-- Or install via npm -->
npm install @yourorg/webchat-widgetπ Hosting on unpkg
Automatic unpkg Hosting
Once published to npm, your package is automatically available on unpkg:
<!-- Latest version -->
<script src="https://unpkg.com/@yourorg/webchat-widget"></script>
<!-- Specific version -->
<script src="https://unpkg.com/@yourorg/webchat-widget@1.0.0"></script>
<!-- Direct file access -->
<script src="https://unpkg.com/@yourorg/webchat-widget/dist/webchat-bundle.min.umd.cjs"></script>unpkg URLs Explained
https://unpkg.com/package-name- Latest version, main filehttps://unpkg.com/package-name@version- Specific versionhttps://unpkg.com/package-name/file-path- Direct file accesshttps://unpkg.com/package-name@version/file-path- Version + file
Real-world Integration Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Website with Chat</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>Content goes here...</p>
<!-- Chat widget integration -->
<div id="customer-chat"></div>
<!-- Load from unpkg -->
<script src="https://unpkg.com/@yourorg/webchat-widget@latest"></script>
<script>
WebChat.initialize({
elementId: "customer-chat",
title: "Customer Support",
placeholder: "How can we help you?",
primaryColor: "#007bff",
apiEndpoint: "https://your-api.com/chat",
apiKey: "your-api-key"
});
</script>
</body>
</html>π Deployment Workflow Summary
# Complete workflow from development to deployment
git checkout -b feature/new-feature
# ... make changes ...
git commit -m "Add new feature"
git push origin feature/new-feature
# ... create PR, review, merge ...
# Deployment
git checkout main
git pull origin main
npm version patch
pnpm build
npm publish
git push --tags
# Your widget is now available at:
# https://unpkg.com/@yourorg/webchat-widget@latestπ οΈ Troubleshooting
Common Issues
TypeScript Errors
# Check TypeScript errors
pnpm build # Will show TS errors
# Fix common issues:
# 1. Missing types - add to src/types.ts
# 2. Import errors - check file extensions (.tsx)
# 3. Strict mode - follow TypeScript strict rulesBuild Issues
# Clear cache and rebuild
rm -rf node_modules dist
pnpm install
pnpm buildCSS Conflicts
// Always use nbc- prefix in className
className="nbc-bg-blue-500 nbc-text-white"unpkg Caching
# Force cache refresh
https://unpkg.com/@yourorg/webchat-widget?t=timestampπ οΈ Development
Prerequisites
- Node.js 18+ (for modern React and TypeScript)
- pnpm 8+ (recommended package manager)
Setup
# Clone the repository
git clone https://github.com/your-username/webchat-widget.git
cd webchat-widget
# Install dependencies with pnpm
pnpm install
# Start development server with hot reload
pnpm devBuild for Production
pnpm buildThis creates a single optimized file in the dist/ directory:
webchat-bundle.min.umd.cjs(159KB / 50KB gzipped) - Complete TypeScript bundle with React, Tailwind CSS, and all functionality
Preview Production Build
pnpm previewπ Project Structure
webchat-widget/
βββ src/
β βββ components/ # React TypeScript components
β β βββ ChatBot.tsx # Main chatbot component
β β βββ ChatButton.tsx # Toggle button
β β βββ ChatWindow.tsx # Chat window container
β β βββ ChatHeader.tsx # Window header
β β βββ MessageList.tsx # Message list with scroll
β β βββ Message.tsx # Individual message
β β βββ MessageInput.tsx # Input field
β β βββ TypingIndicator.tsx # Typing animation
β βββ types.ts # TypeScript interfaces and types
β βββ index.tsx # Main entry point (auto-injects CSS)
β βββ vite-env.d.ts # Vite environment types
β βββ styles.css # Tailwind directives
βββ example.html # Development example
βββ example/
β βββ production.html # Production example
βββ dist/ # Built files
β βββ webchat-bundle.min.umd.cjs # Single file TypeScript bundle
βββ tsconfig.json # TypeScript configuration
βββ tsconfig.node.json # Node TypeScript configuration
βββ tailwind.config.js # Tailwind configuration
βββ postcss.config.js # PostCSS configuration
βββ vite.config.js # Vite configuration
βββ package.json # pnpm + React + TypeScript dependenciesπ License
MIT License - see the LICENSE file for details.