@antzsoft/notification-node-sdk
v1.1.1
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'
Rich push — interactive actions and data-only delivery
// iOS action buttons via categoryId, Android via channelId + dataOnly
await client.sendPush({
tokens: ['ExponentPushToken[android]', 'ExponentPushToken[ios]'],
title: 'Alice',
body: 'Hey, are you free?',
priority: 'high', // defaults to 'high' when omitted
categoryId: 'message', // iOS category — must match one the app registered
channelId: 'messages', // Android channel (Android 8+); ignored on iOS
interruptionLevel: 'active', // iOS: active | time-sensitive | passive | critical
devices: [ // per-token platform → enables per-platform payloads
{ token: 'ExponentPushToken[android]', platform: 'android' },
{ token: 'ExponentPushToken[ios]', platform: 'ios' },
],
data: { title: 'Alice', body: 'Hey, are you free?' },
});
// Data-only: no notification block, so your app's background handler renders it.
// Required to attach Android action buttons.
await client.sendPush({
tokens: ['ExponentPushToken[android]'],
title: 'Alice',
body: 'Hey, are you free?',
dataOnly: true,
channelId: 'messages',
// ⚠️ Duplicate display fields into `data` — with no notification block the OS
// renders nothing, so the handler must read them from here.
data: { title: 'Alice', body: 'Hey, are you free?' },
});
// Web Push without serializing the PushSubscription yourself
await client.sendPush({
platform: 'webpush',
subscriptions: [{ endpoint: 'https://...', p256dh: 'BNc...', auth: 'A1B2...' }],
title: 'Daily digest',
body: '3 new mentions',
});| Field | Type | Notes |
|---|---|---|
| categoryId | string | iOS category; no buttons appear unless the app registered it |
| channelId | string | Android channel (Android 8+); ignored on iOS |
| interruptionLevel | 'active' \| 'time-sensitive' \| 'passive' \| 'critical' | iOS only, default active |
| dataOnly | boolean | Suppress the notification block. Explicit value always wins over tenant config. |
| priority | 'high' \| 'normal' \| 'low' | Defaults to high when omitted |
| devices | { token, platform?, provider? }[] | Per-token platform; required for per-platform shaping |
| subscriptions | { endpoint, p256dh, auth }[] | Structured Web Push subs, merged with tokens |
dataOnlycaveat. Setting it without duplicatingtitle/bodyintodataproduces a push that arrives silently and displays nothing — while still reporting success. Per-platform shaping additionally needsdevices[]and tenant config (dataOnlyPlatforms/perPlatformPayloads); without both, all native tokens get one identical payload.
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',
});For MSG91, message is ignored — pass the registered Flow template_id and
its variables instead:
await client.sendSms({
to: '+12125551234',
template: '651a1b2c3d4e5f6a7b8c9d0e', // MSG91 Flow template_id (or a stored slug)
templateData: { VAR1: '123456' }, // keys must match the Flow template
});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'
});sendWithAttachments(notification, uploads) — multipart attachments
Uploads attachments as multipart/form-data instead of embedding them as base64.
Prefer this for anything sizeable: base64 inflates the payload by ~33%, and the
10 MB per-file cap is applied after decoding.
import { readFile } from 'node:fs/promises';
const pdf = await readFile('./invoice.pdf');
await client.sendWithAttachments(
{
type: 'system',
channels: ['email'],
email: {
to: '[email protected]',
subject: 'Your invoice',
html: '<p>Invoice attached.</p>',
// Declare the attachment by filename — no `content`/`url` here.
attachments: [{ filename: 'invoice.pdf' }],
},
},
{
email: [{ filename: 'invoice.pdf', content: pdf, contentType: 'application/pdf' }],
},
);content accepts Uint8Array, ArrayBuffer, or Blob. contentType is
optional and defaults to application/octet-stream.
Only email and telegram accept attachments, at most 10 files per channel
(UPLOAD_MAX_FILES_PER_REQUEST), each up to 10 MB (UPLOAD_MAX_FILE_SIZE_BYTES).
Rules enforced by the server — the SDK pre-checks the first two so you fail fast, before the bytes go over the wire:
| Rule | Result if violated |
|---|---|
| Every uploaded filename must match a declared attachments[].filename | 400 |
| Filenames must be unique per channel per request | 400 |
| A declared attachment that is uploaded must NOT also set content/url | 400 |
There is no batch equivalent — POST /notifications/queue is the only endpoint
that accepts multipart, so send attachment-bearing notifications one at a time.
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' | 'pending_receipt' | '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 header — a raw lowercase
hex HMAC-SHA256 digest with no sha256= prefix. 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) as WebhookEventPayload;
// event: 'notification.sent' | 'notification.delivered' | 'notification.failed' | 'notification.bounced'
console.log(`Webhook received: ${event}`, data);
// Push failures report permanently dead device tokens. The service stores no
// tokens and deactivates nothing on your behalf — prune them yourself or you
// will keep sending to uninstalled apps indefinitely.
if (data.invalidTokens?.length) {
await deactivateTokens(data.invalidTokens);
}
res.status(200).send('OK');
});Inbound webhook payload
WebhookEventPayload is exported for typing your handler:
{
event: WebhookEvent;
timestamp: string; // ISO 8601, also sent as X-Webhook-Timestamp
data: {
notificationId?: string;
channel?: string;
provider?: string;
status?: string;
messageId?: string;
error?: string;
invalidTokens?: string[]; // dead push tokens — prune these client-side
metadata?: Record<string, any>;
};
}invalidTokens carries tokens the provider reported as permanently dead (Expo
DeviceNotRegistered, FCM/APNs invalid-token, web-push 410 Gone).
Subscribe to notification.*, not just notification.failed. This field also appears on
notification.delivered — a fan-out where some tokens succeed and others are dead is delivered
(the notification did arrive somewhere), but the dead tokens still need pruning. Branch on
data.invalidTokens?.length, never on the event name. Note that most Expo
DeviceNotRegistered errors arrive asynchronously via receipts rather than on the send
itself, so these events can land minutes later (receipt polling is on by default).
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 — 'healthy' | 'degraded'
// health.timestamp
//
// The fields below are returned ONLY when the engine runs with
// HEALTH_EXPOSE_DETAILS=true. By default they are undefined, so that this
// public endpoint does not disclose the deployment's stack:
// health.version — service version
// health.providers — per-provider status map
// health.dependencies — MongoDB / Redis / Kafka status
//
// A degraded service responds 503 either way, so uptime checks that only
// look at the HTTP status work with details disabled.getVapidPublicKey()
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 |
| sendWithAttachments(notification, uploads) | Queue one notification, uploading attachments as multipart | notifications:send |
| getHealth() | Check service health (status + timestamp; detail only when HEALTH_EXPOSE_DETAILS=true) | 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
