@antzsoft/notification-node-sdk
v1.0.0
Published
Node.js/backend SDK for the Antz Notification Service — send push, email, SMS, WhatsApp, and Telegram from any server-side JavaScript runtime
Readme
@antzsoft/notification-node-sdk
TypeScript/JavaScript SDK for the Antz Notification Service. Send push, email, SMS, WhatsApp, and Telegram notifications, track deliveries, manage webhooks, and verify webhook signatures — all from a single, type-safe client.
Runtime compatibility: Node.js 18+, browsers, and edge runtimes (uses global fetch + Web Crypto API — no Node-only imports).
Installation
npm install @antzsoft/notification-node-sdk
# or
yarn add @antzsoft/notification-node-sdk
# or
pnpm add @antzsoft/notification-node-sdkQuick Start
import { AntzClient } from '@antzsoft/notification-node-sdk';
const client = new AntzClient({
baseUrl: 'https://notifications.example.com',
apiKey: 'ntf_your_key_id',
apiSecret: 'your_api_secret',
});
await client.sendEmail({
to: '[email protected]',
subject: 'Welcome!',
html: '<h1>Thanks for signing up.</h1>',
});Configuration (AntzConfig)
const client = new AntzClient({
// ── Required ──────────────────────────────────────────────────────────
baseUrl: 'https://notifications.example.com', // Your notification server URL
apiKey: 'ntf_xxx', // API key ID (format: ntf_xxx)
// ── Auth ──────────────────────────────────────────────────────────────
apiSecret: 'your-secret', // Sent as X-API-Secret header (almost always required)
// ── Multi-environment ─────────────────────────────────────────────────
tenantEnv: 'production', // Sent as X-Tenant-Env header.
// Only needed for tenants with configMode:'custom'
// and multiple named environments.
// Omit → engine falls back to tenant's defaultEnvironment.
// ── Network ───────────────────────────────────────────────────────────
timeout: 30_000, // Request timeout ms (default: 30 000)
retryAttempts: 3, // Retries on network/5xx (default: 3)
retryDelay: 1_000, // Initial retry delay ms (default: 1 000, doubles each attempt)
maxRetryDelay: 10_000, // Retry delay cap ms (default: 10 000)
// ── Extra headers ─────────────────────────────────────────────────────
headers: { 'X-Request-ID': 'trace-123' }, // Merged into every request
});Instantiate once, reuse everywhere — the client is stateless (no connection pooling):
// lib/notifications.ts
export const notifications = new AntzClient({
baseUrl: process.env.ANTZ_URL!,
apiKey: process.env.ANTZ_API_KEY!,
apiSecret: process.env.ANTZ_API_SECRET!,
tenantEnv: process.env.ANTZ_TENANT_ENV, // optional
});Sending Notifications
All sends are asynchronous: the API queues the event to Kafka; a worker delivers it. Recipient addresses (push tokens, email, phone number, chatId) are passed directly in the channel payload — the service stores no per-user state.
send(request) — full control
const result = await client.send({
type: 'system', // notification type (default: 'system')
channels: ['push', 'email'],
priority: 'high', // 'low' | 'normal' | 'high'
externalRef: 'order-123', // your reference ID for tracking / dedup
idempotencyKey: 'order-123-ship', // server-side deduplication key
push: {
token: 'ExponentPushToken[xxx]',
platform: 'expo',
title: 'Order Shipped',
body: 'Your order is on its way!',
data: { orderId: '123' },
},
email: {
to: '[email protected]',
subject: 'Your order shipped',
html: '<p>Your order is on its way!</p>',
},
});
// result.queued — true if accepted to Kafka
// result.notificationId
// result.topics — Kafka topics: one per channel, 'notif.{priority}.{channel}'
// result.duplicate — true if deduplicated via idempotencyKey/externalRefsendPush(payload, options?)
// Single device — Expo
await client.sendPush({
token: 'ExponentPushToken[xxx]',
platform: 'expo',
title: 'New Message',
body: 'You have a message from Alice',
badge: 1,
sound: 'default',
data: { chatId: 'ch-456' },
});
// Fan-out to multiple devices
await client.sendPush({
tokens: ['ExponentPushToken[aaa]', 'ExponentPushToken[bbb]'],
platform: 'expo',
title: 'Announcement',
body: 'New features available!',
});
// Web push (VAPID) — token is JSON.stringify(pushSubscription.toJSON())
await client.sendPush({
token: '{"endpoint":"https://...","keys":{"p256dh":"...","auth":"..."}}',
platform: 'webpush',
title: 'Browser notification',
body: 'You have a new message',
});
// FCM Web
await client.sendPush({
token: 'fcm-registration-token',
platform: 'web',
title: 'FCM Web',
body: 'Message content',
});
// With send options
await client.sendPush(
{ token: 'ExponentPushToken[xxx]', platform: 'expo', title: 'Hi', body: 'World' },
{ priority: 'high', externalRef: 'msg-789' },
);Push platforms: 'expo' | 'fcm' | 'apns' | 'web' | 'webpush'
sendEmail(payload, options?)
// Inline HTML
await client.sendEmail({
to: '[email protected]',
subject: 'Welcome',
html: '<h1>Welcome!</h1><p>Thanks for joining.</p>',
});
// Plain text
await client.sendEmail({
to: '[email protected]',
subject: 'Your receipt',
text: 'Order total: $49.99',
});
// Server-side Handlebars template
await client.sendEmail({
to: '[email protected]',
subject: 'Your order shipped',
template: 'order-shipped',
templateData: { orderId: '123', trackingUrl: 'https://...' },
});sendSms(payload, options?)
await client.sendSms({
to: '+12125551234', // E.164 format
message: 'Your code is 123456',
});sendWhatsApp(payload, options?)
WhatsApp requires an approved template — free-form messages are not allowed outside the 24-hour customer service window.
// Twilio Content template
await client.sendWhatsApp({
to: '+12125551234',
template: 'HXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', // Twilio Content SID
templateData: { '1': 'tomorrow', '2': '3 PM' }, // numeric string keys
});
// Meta Business template
await client.sendWhatsApp({
to: '+12125551234',
template: 'order_shipped',
templateData: {
headerParams: ['#12345'],
bodyParams: ['12345', 'https://track.example.com/12345'],
},
mediaUrl: 'https://example.com/label.png',
});sendTelegram(payload, options?)
await client.sendTelegram({
chatId: '123456789', // numeric or string
message: '<b>Alert:</b> CPU above 90%',
parseMode: 'HTML', // 'HTML' | 'Markdown' | 'MarkdownV2'
});sendBatch(notifications, options?) — bulk queue
Arrays larger than 100 are automatically split into chunks of 100 and sent sequentially. A failed chunk does not abort subsequent chunks.
const notifications = users.map(user => ({
channels: ['push'] as const,
push: {
token: user.pushToken,
platform: 'expo' as const,
title: 'Announcement',
body: 'New features available!',
},
externalRef: `announce_${user.id}`,
}));
const result = await client.sendBatch(notifications, { chunkSize: 50 });
console.log(`Queued: ${result.totalSent}`);
console.log(`Duplicates: ${result.totalDuplicates}`);
console.log(`Failed: ${result.totalFailed}`);
console.log(`All OK: ${result.success}`);
// Per-chunk detail
for (const chunk of result.chunks) {
if (!chunk.success) console.error('Chunk error:', chunk.error);
}Send Options
All sendX() convenience methods accept a second options argument:
| Field | Type | Description |
|---|---|---|
| type | string | Notification type for template lookup (default: 'system') |
| priority | 'low' \| 'normal' \| 'high' | Kafka topic priority lane (default: 'normal') |
| externalRef | string | Your reference ID — used for tracking and dedup (max 100 chars) |
| idempotencyKey | string | Server-side dedup key — duplicate requests are ignored (max 100 chars) |
| template | string | Override the type-based template lookup with a specific template name |
await client.sendSms(
{ to: '+12125551234', message: 'Code: 123456' },
{ priority: 'high', externalRef: `otp_${userId}_${Date.now()}` },
);Delivery Tracking
Requires an API key with the notifications:read scope.
getDeliveries(filters?)
const result = await client.getDeliveries({
channel: 'email', // 'push' | 'email' | 'sms' | 'whatsapp' | 'telegram'
status: 'failed', // 'pending' | 'sent' | 'delivered' | 'failed' | 'bounced'
startDate: '2024-01-01',
endDate: '2024-01-31',
externalRef: 'order-123', // filter by your reference ID
limit: 50,
offset: 0,
});
// result.data — DeliveryLog[]
// result.pagination — { total, limit, offset, hasMore }getDelivery(id)
const { data } = await client.getDelivery('delivery-id-123');
// data.id, data.channel, data.status, data.provider, data.error, data.createdAtgetDeliveriesByRef(externalRef)
const { data } = await client.getDeliveriesByRef('order-123');
// All delivery logs for this externalRef across all channelsgetDeliveryStats(params?)
const stats = await client.getDeliveryStats({
startDate: '2024-01-01',
endDate: '2024-01-31',
});
// stats.data — { total, pending, sent, delivered, failed, bounced, deliveryRate }
// stats.byChannel — { email: { total, delivered, ... }, push: {...}, ... } (same shape per channel)getDeliveryTrend(params?)
const trend = await client.getDeliveryTrend({ days: 7 });
// trend.data — [{ date: '2024-01-25', delivered: 142, failed: 3 }, ...]getDeliveryFailures(params?)
const { data } = await client.getDeliveryFailures({ limit: 20 });
// Most recent failures, most recent first
// data[0].error — provider error messageWebhook Management
Not usable from a pure API-key backend integration.
admin/api/v1/webhooks/*is guarded byJwtAuthGuardonly — a bare API key (includingadmin:*scope) cannot authenticate to it, no matter what scope is granted. These methods only work if your application also drives a JWT-cookie admin session (dashboard login flow) out of band and forwards its cookies; this SDK does not do that. They're included here for completeness/typing, but webhook management is effectively dashboard-only.
createWebhook(tenantId, data)
const result = await client.createWebhook('tenant-abc', {
name: 'Production delivery events',
url: 'https://your-server.com/webhooks/notifications',
events: ['notification.delivered', 'notification.failed'],
});
// result.webhook — WebhookResponse (id, name, url, events, isActive, ...)
// result.secret — HMAC signing secret — shown ONCE, store it securely
// result.warning — present if secret could not be stored encryptedWebhook events: 'notification.sent' | 'notification.delivered' | 'notification.failed' | 'notification.bounced' | 'notification.*'
listWebhooks(tenantId)
const { data } = await client.listWebhooks('tenant-abc');
// data — WebhookResponse[]getWebhook(webhookId, tenantId)
const { data } = await client.getWebhook('wh-123', 'tenant-abc');updateWebhook(webhookId, tenantId, data)
const { data } = await client.updateWebhook('wh-123', 'tenant-abc', {
url: 'https://new-url.example.com/hooks',
events: ['notification.delivered'],
isActive: true,
});deleteWebhook(webhookId, tenantId)
await client.deleteWebhook('wh-123', 'tenant-abc');rotateWebhookSecret(webhookId, tenantId)
const result = await client.rotateWebhookSecret('wh-123', 'tenant-abc');
// result.secret — new signing secret, shown ONCEtestWebhook(webhookId, tenantId)
Fires a test event to the webhook URL.
const result = await client.testWebhook('wh-123', 'tenant-abc');
// result.success — false if delivery failed
// result.error — reason on failureVerifying Webhook Signatures
When the engine fires a webhook, it includes an X-Webhook-Signature: sha256=<hex> header. Verify it before processing:
import { AntzClient } from '@antzsoft/notification-node-sdk';
// Express.js — use raw body (before JSON.parse)
app.post('/webhooks/notifications', express.raw({ type: 'application/json' }), async (req, res) => {
const signature = req.headers['x-webhook-signature'] as string;
const payload = req.body.toString('utf8'); // raw string, not parsed
const valid = await AntzClient.verifyWebhookSignature(
payload,
signature,
process.env.WEBHOOK_SECRET!,
);
if (!valid) {
return res.status(401).send('Invalid signature');
}
const { event, data } = JSON.parse(payload);
// event: 'notification.sent' | 'notification.delivered' | 'notification.failed' | 'notification.bounced' | 'notification.*'
console.log(`Webhook received: ${event}`, data);
res.status(200).send('OK');
});verifyWebhookSignature is a static async method using the Web Crypto API — works in Node 18+, browsers, and edge runtimes (no Node-only imports).
Utilities
getHealth()
const health = await client.getHealth();
// health.status — 'ok'
// health.timestamp
// health.providers — per-provider status mapgetVapidPublicKey()
Fetch the VAPID public key needed for web push subscription setup (no auth required).
const { configured, key } = await client.getVapidPublicKey();
if (configured) {
// use `key` with pushManager.subscribe({ applicationServerKey: key })
}Error Handling
import {
AntzClient,
ApiError,
NetworkError,
TimeoutError,
ConfigError,
} from '@antzsoft/notification-node-sdk';
try {
await client.sendEmail({ to: '[email protected]', subject: 'Hi', html: '<p>Hello</p>' });
} catch (err) {
if (err instanceof ApiError) {
console.error('Status:', err.statusCode);
console.error('Message:', err.message);
if (err.isValidationError()) {
// 400 — DTO/structural validation errors (types, enums, required fields)
err.validationErrors?.forEach(e => console.error(` ${e}`));
}
if (err.isChannelValidationError()) {
// 422 — a declared channel is missing its required recipient/content field
console.error('Channel payload error:', err.message);
}
if (err.isAuthError()) {
// 401 — bad API key / secret
console.error('Check your apiKey and apiSecret');
}
if (err.isRateLimitError()) {
// 429 — will be retried automatically (up to retryAttempts)
console.error('Rate limited');
}
} else if (err instanceof TimeoutError) {
console.error(`Timed out after ${err.timeout}ms`);
} else if (err instanceof NetworkError) {
console.error('Network error:', err.message);
} else if (err instanceof ConfigError) {
console.error('Config error:', err.message);
}
}Retry behaviour: Network errors and 5xx responses are automatically retried up to retryAttempts times with exponential backoff (capped at maxRetryDelay). 4xx errors (except 429) are never retried.
TypeScript Types
All types are exported from the package root:
import type {
// Config
AntzConfig,
// Channel payloads
PushPayload, EmailPayload, EmailRecipient, Attachment,
SmsPayload, WhatsAppPayload, TelegramPayload, TelegramAttachment,
// Send
SendOptions, SendNotificationRequest,
NotificationResponse,
BatchSendOptions, BatchSendResult, BatchChunkResult, BatchChunkResponse,
// Enums
NotificationChannel, // 'push' | 'email' | 'sms' | 'whatsapp' | 'telegram'
NotificationType, // 'new_message' | 'mention' | 'reaction' | 'group_invite' | 'system'
NotificationPriority, // 'low' | 'normal' | 'high'
PushPlatform, // 'expo' | 'fcm' | 'apns' | 'web' | 'webpush'
// Delivery tracking
DeliveryStatus, DeliveryLog, DeliveryFilters,
DeliveryListResponse, DeliveryStats, DeliveryStatsResponse,
DeliveryTrendPoint, DeliveryTrendResponse,
// Webhooks
WebhookEvent, CreateWebhookDto, UpdateWebhookDto,
WebhookResponse, CreateWebhookResponse, RotateWebhookSecretResponse,
// Health
HealthResponse,
} from '@antzsoft/notification-node-sdk';API Reference Summary
| Method | Description | Required scope |
|---|---|---|
| send(request) | Queue a single notification (any channel) | notifications:send |
| sendBatch(notifications, opts?) | Queue multiple notifications (auto-chunked) | notifications:send |
| sendPush(payload, opts?) | Queue a push notification | notifications:send |
| sendEmail(payload, opts?) | Queue an email | notifications:send |
| sendSms(payload, opts?) | Queue an SMS | notifications:send |
| sendWhatsApp(payload, opts?) | Queue a WhatsApp template message | notifications:send |
| sendTelegram(payload, opts?) | Queue a Telegram message | notifications:send |
| getDeliveries(filters?) | List delivery logs with filters + pagination | notifications:read |
| getDelivery(id) | Get a single delivery log by ID | notifications:read |
| getDeliveriesByRef(externalRef) | Get delivery logs by your external reference | notifications:read |
| getDeliveryStats(params?) | Aggregated stats (total / delivered / failed) | notifications:read |
| getDeliveryTrend(params?) | Day-by-day trend data | notifications:read |
| getDeliveryFailures(params?) | Recent failures with error detail | notifications:read |
| createWebhook(tenantId, data) | Register a webhook endpoint | JWT admin session only — see Webhook Management |
| listWebhooks(tenantId) | List all webhooks for a tenant | JWT admin session only |
| getWebhook(webhookId, tenantId) | Get a single webhook | JWT admin session only |
| updateWebhook(webhookId, tenantId, data) | Update webhook URL / events / status | JWT admin session only |
| deleteWebhook(webhookId, tenantId) | Remove a webhook | JWT admin session only |
| rotateWebhookSecret(webhookId, tenantId) | Rotate the HMAC signing secret | JWT admin session only |
| testWebhook(webhookId, tenantId) | Fire a test event to the webhook URL | JWT admin session only |
| getHealth() | Check service health | none |
| getVapidPublicKey() | Fetch VAPID public key for web push setup | none |
| AntzClient.verifyWebhookSignature(payload, sig, secret) | Static — verify inbound webhook HMAC | n/a |
License
MIT
