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
})
async function sendWelcomeEmail(user: { email: string; name: string }) {
await notifs.webhooks.send('welcome_email', {
email: user.email,
name: user.name,
signupDate: new Date().toISOString(),
dashboardUrl: 'https://yourapp.com/dashboard'
}, {
idempotencyKey: `welcome_${user.email}`,
metadata: { userId: user.id, type: 'welcome' }
})
}
// Usage
await sendWelcomeEmail({
email: 'john@example.com',
name: 'John Doe',
id: 'user_123'
})
Password Reset
Send password reset notifications:
async function sendPasswordReset(email: string, resetToken: string) {
const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`
await notifs.webhooks.send('password_reset', {
email,
resetUrl,
expiresIn: '1 hour',
timestamp: new Date().toISOString()
}, {
idempotencyKey: `reset_${email}_${Date.now()}`,
metadata: { type: 'security', action: 'password_reset' }
})
}
Account Updates
Notify users of account changes:
async function notifyAccountUpdate(
userId: string,
change: string,
details: Record<string, any>
) {
await notifs.webhooks.send('account_update', {
userId,
change,
details,
timestamp: new Date().toISOString(),
ipAddress: details.ipAddress
}, {
idempotencyKey: `update_${userId}_${change}_${Date.now()}`,
metadata: { userId, changeType: change }
})
}
// 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
}
async function sendOrderConfirmation(order: Order) {
await notifs.webhooks.send('order_confirmation', {
orderId: order.id,
customerEmail: order.customerEmail,
items: order.items,
total: order.total,
orderUrl: `https://yourapp.com/orders/${order.id}`,
estimatedDelivery: '3-5 business days'
}, {
idempotencyKey: `order_${order.id}`,
metadata: {
customerId: order.customerId,
orderValue: order.total
}
})
}
Shipping Updates
Track shipment status changes:
async function sendShippingUpdate(
orderId: string,
status: string,
trackingNumber?: string
) {
await notifs.webhooks.send('shipping_update', {
orderId,
status,
trackingNumber,
trackingUrl: trackingNumber
? `https://tracking.yourapp.com/${trackingNumber}`
: undefined,
timestamp: new Date().toISOString()
}, {
idempotencyKey: `shipping_${orderId}_${status}`,
metadata: { orderId, status }
})
}
// 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:
async function sendAbandonedCartReminder(
userId: string,
cartItems: Array<{ name: string; price: number }>,
cartTotal: number
) {
await notifs.webhooks.send('abandoned_cart', {
userId,
cartItems,
cartTotal,
cartUrl: 'https://yourapp.com/cart',
couponCode: 'COMEBACK10' // 10% off incentive
}, {
idempotencyKey: `cart_${userId}_${Date.now()}`,
metadata: { userId, cartValue: cartTotal }
})
}
Team Collaboration
Slack Notifications
Send team updates to Slack:
async function notifyTeam(
channel: string,
event: string,
data: Record<string, any>
) {
await notifs.webhooks.send('team_notification', {
channel,
event,
data,
timestamp: new Date().toISOString(),
user: data.triggeredBy
}, {
metadata: { channel, eventType: event }
})
}
// 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:
async function alertTeam(severity: 'low' | 'medium' | 'high' | 'critical', message: string) {
await notifs.webhooks.send('team_alert', {
severity,
message,
timestamp: new Date().toISOString(),
hostname: process.env.HOSTNAME,
environment: process.env.NODE_ENV
}, {
metadata: { severity, alertType: 'system' }
})
}
// 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:
async function sendTrialExpirationWarning(
userId: string,
email: string,
daysRemaining: number
) {
await notifs.webhooks.send('trial_expiration', {
userId,
email,
daysRemaining,
upgradeUrl: 'https://yourapp.com/upgrade',
features: ['Unlimited projects', 'Priority support', 'Advanced analytics']
}, {
idempotencyKey: `trial_${userId}_${daysRemaining}days`,
metadata: { userId, daysRemaining }
})
}
// Send at 7 days, 3 days, 1 day remaining
await sendTrialExpirationWarning('user_123', 'john@example.com', 7)
Usage Limits
Alert users when approaching limits:
async function sendUsageLimitWarning(
userId: string,
resource: string,
usage: number,
limit: number
) {
const percentage = (usage / limit) * 100
if (percentage >= 80) {
await notifs.webhooks.send('usage_limit_warning', {
userId,
resource,
usage,
limit,
percentage: percentage.toFixed(1),
upgradeUrl: 'https://yourapp.com/upgrade'
}, {
idempotencyKey: `usage_${userId}_${resource}_${Math.floor(percentage)}`,
metadata: { userId, resource, percentage }
})
}
}
// Usage
await sendUsageLimitWarning('user_123', 'API calls', 850, 1000) // 85%
Subscription Changes
Notify about subscription updates:
async function notifySubscriptionChange(
userId: string,
change: 'upgraded' | 'downgraded' | 'cancelled' | 'renewed',
plan: string
) {
await notifs.webhooks.send('subscription_change', {
userId,
change,
plan,
effectiveDate: new Date().toISOString(),
billingUrl: 'https://yourapp.com/billing'
}, {
idempotencyKey: `subscription_${userId}_${change}_${Date.now()}`,
metadata: { userId, change, plan }
})
}
Monitoring & Alerts
Error Tracking
Send error alerts to your team:
async function logError(error: Error, context: Record<string, any>) {
await notifs.webhooks.send('error_alert', {
message: error.message,
stack: error.stack,
context,
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV,
version: process.env.APP_VERSION
}, {
metadata: { errorType: error.name, severity: 'high' }
})
}
// Usage in try-catch
try {
await processPayment(orderId)
} catch (error) {
await logError(error, { orderId, userId })
throw error
}
Performance Monitoring
Alert on performance degradation:
async function alertSlowPerformance(
endpoint: string,
duration: number,
threshold: number
) {
if (duration > threshold) {
await notifs.webhooks.send('performance_alert', {
endpoint,
duration,
threshold,
timestamp: new Date().toISOString(),
severity: duration > threshold * 2 ? 'high' : 'medium'
}, {
metadata: { endpoint, duration, threshold }
})
}
}
// 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:
async function checkServiceHealth() {
try {
const response = await fetch('https://yourapi.com/health')
if (!response.ok) {
await notifs.webhooks.send('service_down', {
service: 'API',
status: response.status,
timestamp: new Date().toISOString()
}, {
metadata: { severity: 'critical', service: 'api' }
})
}
} catch (error) {
await notifs.webhooks.send('service_down', {
service: 'API',
error: error.message,
timestamp: new Date().toISOString()
}, {
metadata: { severity: 'critical', service: 'api' }
})
}
}
// Run every 5 minutes
setInterval(checkServiceHealth, 5 * 60 * 1000)
Batch Operations
Bulk Notifications
Send notifications to multiple users:
async function sendBulkNotifications(
users: Array<{ id: string; email: string }>,
event: string,
data: Record<string, any>
) {
const promises = users.map(user =>
notifs.webhooks.send('bulk_notification', {
userId: user.id,
email: user.email,
event,
...data
}, {
idempotencyKey: `bulk_${event}_${user.id}`,
metadata: { userId: user.id, batchId: Date.now() }
})
)
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',
{ 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 delay = (1000 / rateLimit)
for (const user of users) {
await notifs.webhooks.send(webhookId, {
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, '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, data } = await request.json()
const response = await notifs.webhooks.send(webhookId, 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')
const message = formData.get('message')
await notifs.webhooks.send('contact_form', {
email,
message,
timestamp: new Date().toISOString()
})
return { success: true }
}
Testing
Mock Webhook Sends
// __mocks__/@notifs/sdk.ts
export class Notifs {
webhooks = {
send: jest.fn().mockResolvedValue({
id: 'req_test123',
status: 'queued'
})
}
}
// test.ts
import { Notifs } from '@notifs/sdk'
import { sendWelcomeEmail } from './notifications'
jest.mock('@notifs/sdk')
test('sends welcome email', async () => {
const notifs = new Notifs({ apiKey: 'test' })
await sendWelcomeEmail({ email: 'test@example.com', name: 'Test' })
expect(notifs.webhooks.send).toHaveBeenCalledWith(
'welcome_email',
expect.objectContaining({
email: 'test@example.com',
name: 'Test'
}),
expect.any(Object)
)
})
More Examples
Looking for more examples? Check out: