Skip to content

Widget Integration ​

The Nexus notification widget provides real-time in-app notifications for your users. This guide will walk you through integrating the widget into your application step by step.

What is the Nexus Widget? ​

The Nexus widget is a lightweight, embeddable JavaScript component that:

  • 🔔 Displays notifications in a beautiful, floating interface
  • 🔄 Updates in real-time as new notifications arrive
  • 📱 Works on all devices with responsive design
  • 🎨 Matches your brand with customizable themes
  • 📊 Tracks engagement with read receipts and click tracking
  • 🔐 Handles authentication securely with API keys

Prerequisites ​

Before integrating the widget:

Step 1: Quick Integration ​

The fastest way to add the widget is with a script tag:

HTML Integration ​

html
<!DOCTYPE html>
<html>
<head>
    <title>Your App</title>
</head>
<body>
    <!-- Your app content -->
    <div id="app">
        <h1>Welcome to Your App</h1>
        <p>The notification widget will appear in the bottom-right corner.</p>
    </div>

    <!-- Nexus Widget -->
    <script src="https://api.nexus.dev/widget/nexus-widget.js"></script>
    <script>
        NexusWidget.init({
            environmentId: 'your-environment-id',
            subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
            subscriberId: 'current-user-id',
            position: 'bottom-right'
        });
    </script>
</body>
</html>

Self-Hosted Integration ​

If you're running Nexus locally:

html
<!-- Local development -->
<script src="http://localhost:4000/widget/nexus-widget.js"></script>
<script>
    NexusWidget.init({
        environmentId: 'your-environment-id',
        subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
        subscriberId: 'current-user-id',
        apiUrl: 'http://localhost:3001',
        position: 'bottom-right'
    });
</script>

Step 2: Framework Integration ​

React Integration ​

jsx
import { useEffect, useRef } from 'react'

function App() {
  const widgetRef = useRef(null)
  
  useEffect(() => {
    // Load widget script
    const script = document.createElement('script')
    script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
    script.onload = () => {
      // Initialize widget after script loads
      widgetRef.current = window.NexusWidget.init({
        environmentId: 'your-environment-id',
        subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
        subscriberId: getCurrentUserId(), // Your function to get current user
        position: 'bottom-right',
        theme: 'light'
      })
      
      // Listen for widget events
      widgetRef.current.on('notification.clicked', (notification) => {
        console.log('Notification clicked:', notification)
        // Handle navigation or actions
      })
    }
    
    document.head.appendChild(script)
    
    // Cleanup
    return () => {
      if (widgetRef.current) {
        widgetRef.current.destroy()
      }
      script.remove()
    }
  }, [])
  
  // Function to manually add notifications
  const addTestNotification = () => {
    if (widgetRef.current) {
      widgetRef.current.addNotification({
        title: 'Test Notification',
        message: 'This is a test notification added manually',
        channel: 'system'
      })
    }
  }
  
  return (
    <div>
      <h1>My React App</h1>
      <button onClick={addTestNotification}>
        Add Test Notification
      </button>
      {/* Widget will be injected automatically */}
    </div>
  )
}

function getCurrentUserId() {
  // Replace with your authentication logic
  return 'user_123'
}

export default App
jsx
import { Component } from 'react'

class NexusWidgetComponent extends Component {
  constructor(props) {
    super(props)
    this.widgetRef = null
  }
  
  componentDidMount() {
    this.loadWidget()
  }
  
  componentWillUnmount() {
    if (this.widgetRef) {
      this.widgetRef.destroy()
    }
  }
  
  loadWidget = () => {
    const script = document.createElement('script')
    script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
    script.onload = () => {
      this.widgetRef = window.NexusWidget.init({
        environmentId: 'your-environment-id',
        subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
        subscriberId: this.props.userId,
        position: this.props.position || 'bottom-right',
        onNotificationClick: this.handleNotificationClick,
        onWidgetOpen: this.handleWidgetOpen,
        onWidgetClose: this.handleWidgetClose
      })
    }
    
    document.head.appendChild(script)
  }
  
  handleNotificationClick = (notification) => {
    if (this.props.onNotificationClick) {
      this.props.onNotificationClick(notification)
    }
  }
  
  handleWidgetOpen = () => {
    console.log('Widget opened')
  }
  
  handleWidgetClose = () => {
    console.log('Widget closed')
  }
  
  render() {
    return null // Widget is injected into DOM automatically
  }
}

export default NexusWidgetComponent

Vue.js Integration ​

vue
<template>
  <div>
    <h1>My Vue App</h1>
    <button @click="addTestNotification">Add Test Notification</button>
    <!-- Widget will be injected automatically -->
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'

const widget = ref(null)

onMounted(() => {
  loadWidget()
})

onUnmounted(() => {
  if (widget.value) {
    widget.value.destroy()
  }
})

const loadWidget = () => {
  const script = document.createElement('script')
  script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
  script.onload = () => {
    widget.value = window.NexusWidget.init({
      environmentId: 'your-environment-id',
      subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
      subscriberId: getCurrentUserId(),
      position: 'bottom-right'
    })
    
    // Listen for events
    widget.value.on('notification.clicked', handleNotificationClick)
  }
  
  document.head.appendChild(script)
}

const addTestNotification = () => {
  if (widget.value) {
    widget.value.addNotification({
      title: 'Vue Test',
      message: 'This notification was added from Vue',
      channel: 'system'
    })
  }
}

const handleNotificationClick = (notification) => {
  console.log('Notification clicked:', notification)
}

const getCurrentUserId = () => {
  // Your authentication logic
  return 'user_123'
}
</script>
vue
<template>
  <div>
    <h1>My Vue App</h1>
    <button @click="addTestNotification">Add Test Notification</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      widget: null
    }
  },
  
  mounted() {
    this.loadWidget()
  },
  
  beforeDestroy() {
    if (this.widget) {
      this.widget.destroy()
    }
  },
  
  methods: {
    loadWidget() {
      const script = document.createElement('script')
      script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
      script.onload = () => {
        this.widget = window.NexusWidget.init({
          environmentId: 'your-environment-id',
          subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
          subscriberId: this.getCurrentUserId(),
          position: 'bottom-right'
        })
        
        this.widget.on('notification.clicked', this.handleNotificationClick)
      }
      
      document.head.appendChild(script)
    },
    
    addTestNotification() {
      if (this.widget) {
        this.widget.addNotification({
          title: 'Vue Test',
          message: 'This notification was added from Vue',
          channel: 'system'
        })
      }
    },
    
    handleNotificationClick(notification) {
      console.log('Notification clicked:', notification)
    },
    
    getCurrentUserId() {
      return 'user_123'
    }
  }
}
</script>

Angular Integration ​

typescript
import { Injectable } from '@angular/core'

declare global {
  interface Window {
    NexusWidget: any
  }
}

@Injectable({
  providedIn: 'root'
})
export class NexusWidgetService {
  private widget: any = null
  private scriptLoaded = false

  async init(config: {
    environmentId: 'your-environment-id',
    subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
    subscriberId: string
    position?: string
    theme?: string
  }) {
    if (!this.scriptLoaded) {
      await this.loadScript()
      this.scriptLoaded = true
    }

    this.widget = window.NexusWidget.init({
      environmentId: 'your-environment-id',
      subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
      subscriberId: config.userId,
      position: config.position || 'bottom-right',
      theme: config.theme || 'light'
    })

    return this.widget
  }

  addNotification(notification: {
    title: string
    message: string
    channel?: string
    data?: any
  }) {
    if (this.widget) {
      this.widget.addNotification(notification)
    }
  }

  destroy() {
    if (this.widget) {
      this.widget.destroy()
      this.widget = null
    }
  }

  private loadScript(): Promise<void> {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
      script.onload = () => resolve()
      script.onerror = () => reject(new Error('Failed to load Nexus widget'))
      document.head.appendChild(script)
    })
  }
}
typescript
import { Component, OnInit, OnDestroy } from '@angular/core'
import { NexusWidgetService } from './nexus-widget.service'

@Component({
  selector: 'app-root',
  template: `
    <div>
      <h1>My Angular App</h1>
      <button (click)="addTestNotification()">Add Test Notification</button>
    </div>
  `
})
export class AppComponent implements OnInit, OnDestroy {
  constructor(private nexusWidget: NexusWidgetService) {}

  async ngOnInit() {
    await this.nexusWidget.init({
      environmentId: 'your-environment-id',
      subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
      subscriberId: this.getCurrentUserId(),
      position: 'bottom-right'
    })
  }

  ngOnDestroy() {
    this.nexusWidget.destroy()
  }

  addTestNotification() {
    this.nexusWidget.addNotification({
      title: 'Angular Test',
      message: 'This notification was added from Angular',
      channel: 'system'
    })
  }

  private getCurrentUserId(): string {
    // Your authentication logic
    return 'user_123'
  }
}

Svelte Integration ​

svelte
<script>
  import { onMount, onDestroy } from 'svelte'
  
  let widget = null
  
  onMount(async () => {
    // Load widget script
    const script = document.createElement('script')
    script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
    
    script.onload = () => {
      widget = window.NexusWidget.init({
        environmentId: 'your-environment-id',
        subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
        subscriberId: getCurrentUserId(),
        position: 'bottom-right'
      })
      
      widget.on('notification.clicked', handleNotificationClick)
    }
    
    document.head.appendChild(script)
  })
  
  onDestroy(() => {
    if (widget) {
      widget.destroy()
    }
  })
  
  function addTestNotification() {
    if (widget) {
      widget.addNotification({
        title: 'Svelte Test',
        message: 'This notification was added from Svelte',
        channel: 'system'
      })
    }
  }
  
  function handleNotificationClick(notification) {
    console.log('Notification clicked:', notification)
  }
  
  function getCurrentUserId() {
    return 'user_123'
  }
</script>

<main>
  <h1>My Svelte App</h1>
  <button on:click={addTestNotification}>Add Test Notification</button>
</main>

Step 3: Configuration Options ​

Basic Configuration ​

javascript
NexusWidget.init({
  // Required
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'current-user-id',
  
  // Optional
  apiUrl: 'https://api.nexus.dev',        // API base URL
  position: 'bottom-right',              // Widget position
  theme: 'light',                        // light | dark | auto
  channels: ['all'],                     // Enabled channels
  refreshInterval: 30000,                // Auto-refresh interval (ms)
  maxNotifications: 50,                  // Max notifications to display
  sound: false,                          // Enable notification sounds
  browserNotifications: true,            // Request browser notifications
  hideOnClickOutside: true               // Close widget when clicking outside
})

Advanced Configuration ​

javascript
NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user_123',
  
  // Appearance
  position: 'bottom-right',
  theme: 'auto', // Automatically matches system theme
  
  // Behavior
  openBehavior: 'click', // click | hover
  closeOnNotificationClick: false,
  markAsReadOnClick: true,
  
  // Filtering
  channels: ['system', 'social'], // Only show specific channels
  categories: ['transactional'],   // Only show specific categories
  
  // Custom styling
  customCSS: `
    .nexus-widget-button {
      background: linear-gradient(45deg, #ff6b6b, #4ecdc4) !important;
    }
    .nexus-widget-panel {
      font-family: 'Comic Sans MS', cursive !important;
    }
  `,
  
  // Event handlers
  onReady: () => console.log('Widget ready'),
  onNotificationReceived: (notification) => console.log('New notification:', notification),
  onNotificationClick: (notification) => handleNotificationClick(notification),
  onWidgetOpen: () => trackAnalytics('widget_opened'),
  onWidgetClose: () => trackAnalytics('widget_closed'),
  
  // Localization
  locale: 'en-US',
  translations: {
    'en-US': {
      'inbox': 'My Notifications',
      'markAllRead': 'Mark all as read',
      'noNotifications': 'No new notifications'
    },
    'es-ES': {
      'inbox': 'Mis Notificaciones',
      'markAllRead': 'Marcar todo como leído',
      'noNotifications': 'No hay notificaciones nuevas'
    }
  }
})

Step 4: Widget Positioning ​

Position Options ​

javascript
NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user-123',
  position: 'bottom-right'
})
javascript
NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user-123',
  position: 'bottom-left'
})
javascript
NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user-123',
  position: 'top-right'
})
javascript
NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user-123',
  position: 'top-left'
})

Custom Positioning ​

css
/* Override widget position with CSS */
.nexus-widget-container {
  position: fixed !important;
  top: 80px !important;        /* Below your navigation */
  right: 20px !important;
  z-index: 999999 !important;
}

/* Mobile adjustments */
@media (max-width: 768px) {
  .nexus-widget-container {
    bottom: 20px !important;
    top: auto !important;
    left: 50% !important;
    transform: translateX(-50%) !important;
  }
}

Step 5: Custom Styling ​

Theme Customization ​

javascript
NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user-123',
  theme: 'custom',
  customTheme: {
    // Colors
    primary: '#667eea',
    secondary: '#764ba2',
    background: '#ffffff',
    surface: '#f8fafc',
    text: '#1f2937',
    textSecondary: '#6b7280',
    border: '#e5e7eb',
    success: '#10b981',
    warning: '#f59e0b',
    error: '#ef4444',
    
    // Typography
    fontFamily: 'Inter, system-ui, sans-serif',
    fontSize: '14px',
    fontWeight: '400',
    
    // Spacing
    borderRadius: '8px',
    padding: '16px',
    
    // Animation
    animationDuration: '200ms',
    animationEasing: 'ease-in-out'
  }
})

CSS Overrides ​

css
/* Custom widget styling */
.nexus-widget-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3) !important;
}

.nexus-widget-button:hover {
  transform: scale(1.05) !important;
}

.nexus-widget-panel {
  border-radius: 16px !important;
  backdrop-filter: blur(10px) !important;
  background: rgba(255, 255, 255, 0.95) !important;
}

.nexus-widget-notification {
  border-radius: 8px !important;
  margin-bottom: 8px !important;
}

.nexus-widget-notification.unread {
  background: linear-gradient(90deg, #f0f9ff 0%, #e0f2fe 100%) !important;
  border-left: 3px solid #0ea5e9 !important;
}

/* Dark mode support */
@media (prefers-color-scheme: dark) {
  .nexus-widget-panel {
    background: rgba(31, 41, 55, 0.95) !important;
    border: 1px solid #374151 !important;
  }
  
  .nexus-widget-notification {
    color: #f9fafb !important;
  }
}

Step 6: Event Handling ​

Available Events ​

javascript
const widget = NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user-123'
})

// Widget lifecycle events
widget.on('ready', () => {
  console.log('Widget is ready')
})

widget.on('open', () => {
  console.log('Widget opened')
  // Track analytics
  analytics.track('Notification Widget Opened')
})

widget.on('close', () => {
  console.log('Widget closed')
})

// Notification events
widget.on('notification.received', (notification) => {
  console.log('New notification received:', notification)
  
  // Show browser notification
  if (Notification.permission === 'granted') {
    new Notification(notification.title, {
      body: notification.message,
      icon: '/path/to/icon.png'
    })
  }
})

widget.on('notification.clicked', (notification) => {
  console.log('Notification clicked:', notification)
  
  // Handle navigation
  if (notification.data?.url) {
    window.location.href = notification.data.url
  }
  
  // Track engagement
  analytics.track('Notification Clicked', {
    notificationId: notification.id,
    channel: notification.channel
  })
})

widget.on('notification.read', (notificationId) => {
  console.log('Notification marked as read:', notificationId)
})

// Settings events
widget.on('settings.clicked', () => {
  console.log('Settings button clicked')
  // Open your app's notification preferences page
  window.location.href = '/settings/notifications'
})

// Error events
widget.on('error', (error) => {
  console.error('Widget error:', error)
  // Report to error tracking service
  errorReporting.captureException(error)
})

Custom Event Handlers ​

javascript
// Handle specific notification types
widget.on('notification.clicked', (notification) => {
  switch (notification.channel) {
    case 'order':
      // Navigate to order details
      router.push(`/orders/${notification.data.orderId}`)
      break
      
    case 'message':
      // Open chat or messaging interface
      openChat(notification.data.conversationId)
      break
      
    case 'system':
      // Show system alert modal
      showSystemAlert(notification)
      break
      
    default:
      console.log('Unknown notification type:', notification.channel)
  }
})

// Handle notification actions
widget.on('notification.action', (notification, action) => {
  console.log('Notification action triggered:', action)
  
  switch (action.type) {
    case 'approve':
      handleApproval(notification.data.requestId)
      break
      
    case 'view':
      viewDetails(notification.data.itemId)
      break
      
    case 'dismiss':
      dismissNotification(notification.id)
      break
  }
})

Step 7: API Methods ​

Programmatic Control ​

javascript
const widget = NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user-123'
})

// Add notification manually
widget.addNotification({
  id: 'custom-123',
  title: 'Custom Notification',
  message: 'This notification was added programmatically',
  channel: 'system',
  timestamp: new Date().toISOString(),
  read: false,
  data: {
    url: '/custom-page',
    action: 'view'
  }
})

// Mark notification as read
widget.markAsRead('notification-id')

// Mark all notifications as read
widget.markAllAsRead()

// Clear all notifications
widget.clearAll()

// Get notification count
const unreadCount = widget.getUnreadCount()
console.log('Unread notifications:', unreadCount)

// Get all notifications
const notifications = widget.getNotifications()
console.log('All notifications:', notifications)

// Update user information
widget.updateUser({
  subscriberId: 'new-user-id',
  firstName: 'John',
  lastName: 'Doe',
  email: '[email protected]'
})

// Refresh notifications
widget.refresh()

// Show/hide widget
widget.show()
widget.hide()

// Open/close widget
widget.open()
widget.close()

// Destroy widget
widget.destroy()

Widget State Management ​

javascript
// Check widget state
console.log('Is widget open?', widget.isOpen())
console.log('Is widget visible?', widget.isVisible())
console.log('Is widget initialized?', widget.isInitialized())

// Subscribe to state changes
widget.on('state.changed', (state) => {
  console.log('Widget state changed:', state)
  
  // Persist state to localStorage
  localStorage.setItem('widget-state', JSON.stringify(state))
})

// Restore widget state
const savedState = localStorage.getItem('widget-state')
if (savedState) {
  widget.setState(JSON.parse(savedState))
}

Step 8: Testing the Integration ​

Basic Functionality Test ​

javascript
// Test script to verify widget functionality
async function testWidget() {
  console.log('Testing Nexus Widget...')
  
  // 1. Check if widget is loaded
  if (typeof window.NexusWidget === 'undefined') {
    console.error('❌ Widget script not loaded')
    return
  }
  console.log('✅ Widget script loaded')
  
  // 2. Initialize widget
  const widget = window.NexusWidget.init({
    environmentId: 'your-environment-id',
    subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
    subscriberId: 'test-user-123'
  })
  
  // 3. Test adding notification
  widget.addNotification({
    title: 'Test Notification',
    message: 'If you see this, the widget is working!',
    channel: 'system'
  })
  console.log('✅ Test notification added')
  
  // 4. Test event handling
  widget.on('notification.clicked', () => {
    console.log('✅ Event handling works')
  })
  
  // 5. Test API methods
  const count = widget.getUnreadCount()
  console.log(`✅ Unread count: ${count}`)
  
  console.log('🎉 Widget test completed!')
}

// Run test when page loads
document.addEventListener('DOMContentLoaded', testWidget)

Integration with Your Backend ​

javascript
// Example: Sync widget with your application state
class NotificationManager {
  constructor(userId, subscriberHash) {
    this.userId = userId
    this.widget = NexusWidget.init({
      environmentId: 'your-environment-id',
      subscriberId: userId,
      subscriberHash // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
    })
    
    this.setupEventHandlers()
    this.syncWithBackend()
  }
  
  setupEventHandlers() {
    // Mark as read in your backend when user clicks
    this.widget.on('notification.read', async (notificationId) => {
      try {
        await fetch(`/api/notifications/${notificationId}/read`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('auth-token')}`
          }
        })
      } catch (error) {
        console.error('Failed to mark notification as read:', error)
      }
    })
    
    // Handle notification clicks
    this.widget.on('notification.clicked', (notification) => {
      this.handleNotificationAction(notification)
    })
  }
  
  async syncWithBackend() {
    try {
      // Fetch notifications from your backend
      const response = await fetch('/api/notifications', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('auth-token')}`
        }
      })
      
      const notifications = await response.json()
      
      // Add them to the widget
      notifications.forEach(notification => {
        this.widget.addNotification(notification)
      })
      
    } catch (error) {
      console.error('Failed to sync notifications:', error)
    }
  }
  
  handleNotificationAction(notification) {
    // Route to different pages based on notification type
    const routes = {
      'order-update': () => this.navigateToOrder(notification.data.orderId),
      'message': () => this.openChat(notification.data.chatId),
      'system-alert': () => this.showSystemModal(notification),
      'friend-request': () => this.openFriendRequests()
    }
    
    const handler = routes[notification.type]
    if (handler) {
      handler()
    } else {
      console.log('No handler for notification type:', notification.type)
    }
  }
  
  navigateToOrder(orderId) {
    window.location.href = `/orders/${orderId}`
  }
  
  openChat(chatId) {
    // Your chat opening logic
    console.log('Opening chat:', chatId)
  }
  
  showSystemModal(notification) {
    // Your modal display logic
    console.log('Showing system modal:', notification)
  }
  
  openFriendRequests() {
    window.location.href = '/friends/requests'
  }
}

// Initialize when user logs in
document.addEventListener('DOMContentLoaded', () => {
  const userId = getCurrentUserId()
  // Rendered into the page by your backend; never put your API key in browser code
  const subscriberHash = document.querySelector('meta[name="nexus-subscriber-hash"]')?.content
  
  if (userId && subscriberHash) {
    new NotificationManager(userId, subscriberHash)
  }
})

Troubleshooting ​

Common Issues ​

1. Widget Not Appearing ​

javascript
// Check if script loaded correctly
if (typeof window.NexusWidget === 'undefined') {
  console.error('Nexus Widget script not loaded')
  
  // Manually load script
  const script = document.createElement('script')
  script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
  script.onload = () => console.log('Script loaded successfully')
  script.onerror = () => console.error('Failed to load script')
  document.head.appendChild(script)
}

2. CORS Issues (Self-Hosted) ​

javascript
// Ensure your API server allows the widget domain
// In your API server configuration:
app.use(cors({
  origin: ['http://localhost:3000', 'https://yourdomain.com'],
  credentials: true
}))

3. Authentication Issues ​

javascript
// Verify API key and user ID
NexusWidget.init({
  environmentId: 'your-environment-id',
  subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
  subscriberId: 'user_123',    // Ensure this matches your subscriber ID
  debug: true            // Enable debug logging
})

4. Styling Conflicts ​

css
/* Reset conflicting styles */
.nexus-widget-container * {
  box-sizing: border-box !important;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
}

/* Override z-index conflicts */
.nexus-widget-container {
  z-index: 999999 !important;
}

Best Practices ​

1. Performance Optimization ​

javascript
// Lazy load the widget
function loadWidgetWhenNeeded() {
  // Only load widget when user is likely to interact
  const events = ['scroll', 'click', 'keydown']
  
  const loadWidget = () => {
    const script = document.createElement('script')
    script.src = 'https://api.nexus.dev/widget/nexus-widget.js'
    script.onload = () => {
      NexusWidget.init({
        environmentId: 'your-environment-id',
        subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
        subscriberId: getCurrentUserId()
      })
    }
    document.head.appendChild(script)
    
    // Remove event listeners after loading
    events.forEach(event => {
      document.removeEventListener(event, loadWidget, { passive: true })
    })
  }
  
  events.forEach(event => {
    document.addEventListener(event, loadWidget, { passive: true })
  })
}

// Call when page loads
loadWidgetWhenNeeded()

2. Error Handling ​

javascript
try {
  const widget = NexusWidget.init({
    environmentId: 'your-environment-id',
    subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
    subscriberId: 'user-123'
  })
  
  widget.on('error', (error) => {
    console.error('Widget error:', error)
    
    // Report to error tracking
    if (window.Sentry) {
      window.Sentry.captureException(error)
    }
    
    // Fallback: show browser notification
    if (Notification.permission === 'granted') {
      new Notification('Notification System Error', {
        body: 'There was an issue with notifications. Please refresh the page.',
        icon: '/error-icon.png'
      })
    }
  })
  
} catch (error) {
  console.error('Failed to initialize Nexus Widget:', error)
}

3. User Privacy ​

javascript
// Respect user's notification preferences
async function initializeWidget() {
  const userPreferences = await getUserNotificationPreferences()
  
  if (!userPreferences.inAppNotifications) {
    console.log('User has disabled in-app notifications')
    return
  }
  
  NexusWidget.init({
    environmentId: 'your-environment-id',
    subscriberHash: subscriberHash, // signed by your backend: see /widget/installation#sign-the-subscriber-on-your-server
    subscriberId: getCurrentUserId(),
    channels: userPreferences.enabledChannels,
    browserNotifications: userPreferences.browserNotifications
  })
}

Next Steps ​

Now that you have the widget integrated:

  1. Customize the appearance to match your brand
  2. Set up webhook endpoints to sync with your backend
  3. Create notification workflows for different user actions
  4. Implement analytics tracking for notification engagement
  5. Test across different devices and browsers

Getting Help ​