Skip to main content
Enable web push notifications in the browser to send timely, engaging messages to users.
** Track your campaigns:** The SDK automatically tracks delivery, opens, and clicks. For advanced tracking customization and implementation details, see Push Notification Tracking.

Prerequisites

  1. HTTPS: Web push requires a secure context (HTTPS)
  2. Service Worker: A service worker file to handle push events
  3. API Key: Your Zixflow API key
  4. User Permission: Users must grant notification permission

Step 1: Install Dependencies

npm install @zixflow/analytics-browser

Step 2: Create Service Worker

Create a file public/sw.js (or public/zixflow-sw.js):
// Service Worker for Zixflow Web Push Notifications

self.addEventListener('install', (event) => {
  console.log('[SW] Installing service worker')
  self.skipWaiting()
})

self.addEventListener('activate', (event) => {
  console.log('[SW] Activating service worker')
  event.waitUntil(self.clients.claim())
})

self.addEventListener('push', (event) => {
  console.log('[SW] Push event received')

  if (!event.data) {
    console.warn('[SW] Push event has no data')
    return
  }

  let data
  try {
    data = event.data.json()
  } catch (e) {
    console.error('[SW] Failed to parse push data:', e)
    return
  }

  const title = data.title || 'Notification'
  const options = {
    body: data.body || '',
    icon: data.icon || '/icon.png',
    badge: data.badge || '/badge.png',
    image: data.image,
    data: data,
    tag: data.tag || 'zixflow-push',
    requireInteraction: data.requireInteraction || false,
    actions: data.actions || []
  }

  event.waitUntil(
    self.registration.showNotification(title, options)
  )
})

self.addEventListener('notificationclick', (event) => {
  console.log('[SW] Notification clicked:', event.action)

  event.notification.close()

  const clickedUrl = event.action
    ? event.notification.data.actions?.[event.action]?.url
    : event.notification.data.url || '/'

  event.waitUntil(
    clients.openWindow(clickedUrl).then((windowClient) => {
      if (windowClient) {
        windowClient.focus()
      }
    })
  )
})

Step 3: Initialize Web Push Plugin

import { AnalyticsBrowser } from '@zixflow/analytics-browser'

// Initialize analytics with web push
const analytics = AnalyticsBrowser.load({
  apiKey: 'YOUR_API_KEY',
  plugins: [
    {
      name: 'WebPush',
      settings: {
        apiHost: 'api-events.zixflow.com/v1',  // Optional
        protocol: 'https',                      // Optional
        swUrl: '/sw.js',                 // Path to service worker
        autoSubscribe: false,            // Don't auto-request permission
        onNotificationClick: (url, action, data) => {
          // Handle notification clicks when app is open
          console.log('Notification clicked:', url, action, data)
          // Navigate to URL or perform action
          window.location.href = url
        }
      }
    }
  ]
})

Step 4: Request Push Permission

Request permission on user action (e.g., button click):
// HTML
<button id="subscribe-btn">Enable Notifications</button>

// JavaScript
document.getElementById('subscribe-btn').addEventListener('click', async () => {
  try {
    await analytics.plugins.WebPush.subscribeToPush()
    console.log('Push notifications enabled')
  } catch (err) {
    console.error('Failed to enable push notifications:', err)
  }
})

Step 5: Identify Users

Associate push subscription with user:
// After user logs in
analytics.identify('user@example.com', {
  email: 'user@example.com',
  first_name: 'John'
})

// The push subscription is automatically linked to the user

Web Push API Reference

Subscribe to Push

// Request permission and subscribe
await analytics.plugins.WebPush.subscribeToPush()

Unsubscribe from Push

// Unsubscribe from push notifications
await analytics.plugins.WebPush.unsubscribeFromPush()

Check Subscription Status

// Check if user is subscribed
const subscription = await analytics.plugins.WebPush.getSubscription()
console.log('Subscription:', subscription)

Web Push Best Practices

  1. Request permission thoughtfully - Only ask after explaining value
  2. Use user gestures - Request permission on button clicks, not page load
  3. Provide unsubscribe option - Let users easily disable notifications
  4. Test on HTTPS - Web push requires secure context
  5. Handle errors gracefully - Permission can be denied or blocked
  6. Use meaningful content - Provide value in notifications
  7. Deep link properly - Navigate users to relevant content

Web Push Troubleshooting

Permission Denied

Problem: User denied notification permission Solution:
  • Explain value before requesting permission
  • Guide users to browser settings to re-enable
  • Provide clear unsubscribe option

Service Worker Not Registered

Error: Failed to register service worker Solution:
// Check service worker registration
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(reg => console.log('SW registered:', reg))
    .catch(err => console.error('SW registration failed:', err))
}

Push Not Received

Checklist:
  • HTTPS enabled (required for web push)
  • Service worker registered successfully
  • User granted notification permission
  • User identified with analytics.identify()
  • Push subscription active
  • Browser supports web push