Examples

Real-world examples and common use cases for integrating Notifs into your application.

User Notifications

Welcome Email

Send a welcome email when users sign up:

import { Notifs } from '@notifs/sdk'

const notifs = new Notifs({
  apiKey: process.env.NOTIFS_API_KEY
})

// Get webhook once, reuse for multiple sends
const welcomeWebhook = await notifs.webhooks.get('your_welcome_webhook_id')

async function sendWelcomeEmail(user: { email: string; name: string }) {
  await welcomeWebhook.send({
    title: 'Welcome to Our App',
    message: `Hi ${user.name}, thanks for signing up!`,
    data: {
      email: user.email,
      name: user.name,
      signupDate: new Date().toISOString(),
      dashboardUrl: 'https://yourapp.com/dashboard'
    }
  })
}

// Usage
await sendWelcomeEmail({
  email: 'john@example.com',
  name: 'John Doe'
})

Password Reset

Send password reset notifications:

const passwordResetWebhook = await notifs.webhooks.get('your_password_reset_webhook_id')

async function sendPasswordReset(email: string, resetToken: string) {
  const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`

  await passwordResetWebhook.send({
    title: 'Password Reset Request',
    message: 'Click the link below to reset your password',
    data: {
      email,
      resetUrl,
      expiresIn: '1 hour',
      timestamp: new Date().toISOString()
    }
  })
}

Account Updates

Notify users of account changes:

const accountUpdateWebhook = await notifs.webhooks.get('your_account_update_webhook_id')

async function notifyAccountUpdate(
  userId: string,
  change: string,
  details: Record<string, any>
) {
  await accountUpdateWebhook.send({
    title: 'Account Updated',
    message: `Your account ${change.replace('_', ' ')} was successful`,
    data: {
      userId,
      change,
      details,
      timestamp: new Date().toISOString(),
      ipAddress: details.ipAddress
    }
  })
}

// Usage
await notifyAccountUpdate('user_123', 'email_changed', {
  oldEmail: 'old@example.com',
  newEmail: 'new@example.com',
  ipAddress: '192.168.1.1'
})

E-commerce

Order Confirmation

Send order confirmations with details:

interface Order {
  id: string
  customerId: string
  customerEmail: string
  items: Array<{ name: string; quantity: number; price: number }>
  total: number
  status: string
}

const orderWebhook = await notifs.webhooks.get('your_order_webhook_id')

async function sendOrderConfirmation(order: Order) {
  await orderWebhook.send({
    title: 'Order Confirmed',
    message: `Your order #${order.id} has been confirmed`,
    data: {
      orderId: order.id,
      customerEmail: order.customerEmail,
      items: order.items,
      total: order.total,
      orderUrl: `https://yourapp.com/orders/${order.id}`,
      estimatedDelivery: '3-5 business days'
    }
  })
}

Shipping Updates

Track shipment status changes:

const shippingWebhook = await notifs.webhooks.get('your_shipping_webhook_id')

async function sendShippingUpdate(
  orderId: string,
  status: string,
  trackingNumber?: string
) {
  await shippingWebhook.send({
    title: 'Shipping Update',
    message: `Order #${orderId} is now ${status.replace('_', ' ')}`,
    data: {
      orderId,
      status,
      trackingNumber,
      trackingUrl: trackingNumber
        ? `https://tracking.yourapp.com/${trackingNumber}`
        : undefined,
      timestamp: new Date().toISOString()
    }
  })
}

// Usage
await sendShippingUpdate('order_123', 'shipped', 'TRACK123456')
await sendShippingUpdate('order_123', 'out_for_delivery')
await sendShippingUpdate('order_123', 'delivered')

Abandoned Cart

Remind users about abandoned carts:

const cartWebhook = await notifs.webhooks.get('your_cart_webhook_id')

async function sendAbandonedCartReminder(
  userId: string,
  cartItems: Array<{ name: string; price: number }>,
  cartTotal: number
) {
  await cartWebhook.send({
    title: 'You Left Something Behind',
    message: 'Complete your purchase and get 10% off!',
    data: {
      userId,
      cartItems,
      cartTotal,
      cartUrl: 'https://yourapp.com/cart',
      couponCode: 'COMEBACK10'
    }
  })
}

Team Collaboration

Slack Notifications

Send team updates to Slack:

const teamWebhook = await notifs.webhooks.get('your_team_webhook_id')

async function notifyTeam(
  channel: string,
  event: string,
  data: Record<string, any>
) {
  await teamWebhook.send({
    title: `Team Update: ${event.replace('_', ' ')}`,
    message: `New event in ${channel}`,
    data: {
      channel,
      event,
      ...data,
      timestamp: new Date().toISOString()
    }
  })
}

// Usage
await notifyTeam('#deployments', 'deployment_completed', {
  environment: 'production',
  version: 'v1.2.3',
  triggeredBy: 'john@example.com',
  duration: '5m 23s'
})

Issue Alerts

Alert team about critical issues:

const alertWebhook = await notifs.webhooks.get('your_alert_webhook_id')

async function alertTeam(severity: 'low' | 'medium' | 'high' | 'critical', message: string) {
  await alertWebhook.send({
    title: `[${severity.toUpperCase()}] System Alert`,
    message,
    data: {
      severity,
      timestamp: new Date().toISOString(),
      hostname: process.env.HOSTNAME,
      environment: process.env.NODE_ENV
    }
  })
}

// Usage
await alertTeam('critical', 'Database connection pool exhausted')
await alertTeam('high', 'API response time exceeded 2s threshold')

SaaS Applications

Trial Expiration

Notify users of trial expiration:

const trialWebhook = await notifs.webhooks.get('your_trial_webhook_id')

async function sendTrialExpirationWarning(
  userId: string,
  email: string,
  daysRemaining: number
) {
  await trialWebhook.send({
    title: 'Your Trial is Ending Soon',
    message: `You have ${daysRemaining} day${daysRemaining === 1 ? '' : 's'} left in your trial`,
    data: {
      userId,
      email,
      daysRemaining,
      upgradeUrl: 'https://yourapp.com/upgrade',
      features: ['Unlimited projects', 'Priority support', 'Advanced analytics']
    }
  })
}

// Send at 7 days, 3 days, 1 day remaining
await sendTrialExpirationWarning('user_123', 'john@example.com', 7)

Usage Limits

Alert users when approaching limits:

const usageWebhook = await notifs.webhooks.get('your_usage_webhook_id')

async function sendUsageLimitWarning(
  userId: string,
  resource: string,
  usage: number,
  limit: number
) {
  const percentage = (usage / limit) * 100

  if (percentage >= 80) {
    await usageWebhook.send({
      title: 'Usage Limit Warning',
      message: `You've used ${percentage.toFixed(1)}% of your ${resource} quota`,
      data: {
        userId,
        resource,
        usage,
        limit,
        percentage: percentage.toFixed(1),
        upgradeUrl: 'https://yourapp.com/upgrade'
      }
    })
  }
}

// Usage
await sendUsageLimitWarning('user_123', 'API calls', 850, 1000) // 85%

Subscription Changes

Notify about subscription updates:

const subscriptionWebhook = await notifs.webhooks.get('your_subscription_webhook_id')

async function notifySubscriptionChange(
  userId: string,
  change: 'upgraded' | 'downgraded' | 'cancelled' | 'renewed',
  plan: string
) {
  await subscriptionWebhook.send({
    title: `Subscription ${change.charAt(0).toUpperCase() + change.slice(1)}`,
    message: `Your subscription has been ${change} to the ${plan} plan`,
    data: {
      userId,
      change,
      plan,
      effectiveDate: new Date().toISOString(),
      billingUrl: 'https://yourapp.com/billing'
    }
  })
}

Monitoring & Alerts

Error Tracking

Send error alerts to your team:

const errorWebhook = await notifs.webhooks.get('your_error_webhook_id')

async function logError(error: Error, context: Record<string, any>) {
  await errorWebhook.send({
    title: `Error: ${error.name}`,
    message: error.message,
    data: {
      stack: error.stack,
      context,
      timestamp: new Date().toISOString(),
      environment: process.env.NODE_ENV,
      version: process.env.APP_VERSION
    }
  })
}

// Usage in try-catch
try {
  await processPayment(orderId)
} catch (error) {
  await logError(error, { orderId, userId })
  throw error
}

Performance Monitoring

Alert on performance degradation:

const perfWebhook = await notifs.webhooks.get('your_performance_webhook_id')

async function alertSlowPerformance(
  endpoint: string,
  duration: number,
  threshold: number
) {
  if (duration > threshold) {
    const severity = duration > threshold * 2 ? 'high' : 'medium'
    await perfWebhook.send({
      title: `[${severity.toUpperCase()}] Slow Response`,
      message: `${endpoint} took ${duration}ms (threshold: ${threshold}ms)`,
      data: {
        endpoint,
        duration,
        threshold,
        timestamp: new Date().toISOString(),
        severity
      }
    })
  }
}

// Usage with middleware
app.use((req, res, next) => {
  const start = Date.now()
  res.on('finish', async () => {
    const duration = Date.now() - start
    await alertSlowPerformance(req.path, duration, 1000) // 1s threshold
  })
  next()
})

Uptime Monitoring

Monitor service health:

const uptimeWebhook = await notifs.webhooks.get('your_uptime_webhook_id')

async function checkServiceHealth() {
  try {
    const response = await fetch('https://yourapi.com/health')
    if (!response.ok) {
      await uptimeWebhook.send({
        title: '[CRITICAL] Service Down',
        message: `API returned status ${response.status}`,
        data: {
          service: 'API',
          status: response.status,
          timestamp: new Date().toISOString()
        }
      })
    }
  } catch (error) {
    await uptimeWebhook.send({
      title: '[CRITICAL] Service Unreachable',
      message: `API health check failed: ${error.message}`,
      data: {
        service: 'API',
        error: error.message,
        timestamp: new Date().toISOString()
      }
    })
  }
}

// Run every 5 minutes
setInterval(checkServiceHealth, 5 * 60 * 1000)

Batch Operations

Bulk Notifications

Send notifications to multiple users:

const bulkWebhook = await notifs.webhooks.get('your_bulk_webhook_id')

async function sendBulkNotifications(
  users: Array<{ id: string; email: string }>,
  event: string,
  data: Record<string, any>
) {
  const promises = users.map(user =>
    bulkWebhook.send({
      title: data.title || `New ${event.replace('_', ' ')}`,
      message: data.message,
      data: {
        userId: user.id,
        email: user.email,
        event,
        ...data
      }
    })
  )

  const results = await Promise.allSettled(promises)

  // Log failures
  results.forEach((result, index) => {
    if (result.status === 'rejected') {
      console.error(`Failed to send to ${users[index].email}:`, result.reason)
    }
  })

  return results
}

// Usage
await sendBulkNotifications(
  [{ id: 'user_1', email: 'user1@example.com' }],
  'product_launch',
  { title: 'New Product Launch', productName: 'New Widget', launchDate: '2024-02-01' }
)

Rate-Limited Batch

Send with rate limiting:

async function sendRateLimitedBatch(
  users: Array<{ id: string; email: string }>,
  webhookId: string,
  rateLimit: number // requests per second
) {
  const webhook = await notifs.webhooks.get(webhookId)
  const delay = 1000 / rateLimit

  for (const user of users) {
    await webhook.send({
      title: 'Notification',
      data: {
        userId: user.id,
        email: user.email
      }
    })

    // Wait before next request
    await new Promise(resolve => setTimeout(resolve, delay))
  }
}

// Send to 10 users per second
await sendRateLimitedBatch(users, 'your_webhook_id', 10)

Next.js Integration

API Route

// app/api/webhooks/send/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { Notifs } from '@notifs/sdk'

const notifs = new Notifs({
  apiKey: process.env.NOTIFS_API_KEY!
})

export async function POST(request: NextRequest) {
  try {
    const { webhookId, title, message, data } = await request.json()

    const webhook = await notifs.webhooks.get(webhookId)
    const response = await webhook.send({ title, message, data })

    return NextResponse.json(response)
  } catch (error) {
    return NextResponse.json(
      { error: error.message },
      { status: 500 }
    )
  }
}

Server Action

// app/actions.ts
'use server'

import { Notifs } from '@notifs/sdk'

const notifs = new Notifs({
  apiKey: process.env.NOTIFS_API_KEY!
})

export async function sendNotification(formData: FormData) {
  const email = formData.get('email') as string
  const message = formData.get('message') as string

  const webhook = await notifs.webhooks.get('your_contact_form_webhook_id')
  await webhook.send({
    title: 'New Contact Form Submission',
    message: `Message from ${email}`,
    data: {
      email,
      message,
      timestamp: new Date().toISOString()
    }
  })

  return { success: true }
}

Testing

Mock Webhook Sends

// __mocks__/@notifs/sdk.ts
const mockSend = jest.fn().mockResolvedValue({
  message: 'Webhook processed successfully',
  notificationId: 'notif_test123',
  servicesExecuted: true
})

const mockWebhook = {
  id: 'webhook_test123',
  name: 'Test Webhook',
  send: mockSend
}

export class Notifs {
  webhooks = {
    get: jest.fn().mockResolvedValue(mockWebhook),
    create: jest.fn().mockResolvedValue(mockWebhook),
    list: jest.fn().mockResolvedValue([mockWebhook])
  }
}

export { mockSend, mockWebhook }

// test.ts
import { Notifs, mockSend } from '@notifs/sdk'
import { sendWelcomeEmail } from './notifications'

jest.mock('@notifs/sdk')

test('sends welcome email', async () => {
  await sendWelcomeEmail({ email: 'test@example.com', name: 'Test' })

  expect(mockSend).toHaveBeenCalledWith(
    expect.objectContaining({
      title: expect.any(String),
      data: expect.objectContaining({
        email: 'test@example.com',
        name: 'Test'
      })
    })
  )
})

More Examples

Looking for more examples? Check out: