Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
219 changes: 193 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
# @ciscode/notification-kit

> A flexible, type-safe notification system for NestJS applications supporting multiple channels (Email, SMS, Push) with pluggable providers.
> A lightweight, delivery-focused notification library for NestJS. Send notifications through multiple channels (Email, SMS, Push, WhatsApp) with pluggable providers. **Your app manages content and templates, NotificationKit handles delivery.**

[![npm version](https://img.shields.io/npm/v/@ciscode/notification-kit.svg)](https://www.npmjs.com/package/@ciscode/notification-kit)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)

## ✨ Features

- 🚀 **Multi-Channel Support** - Email, SMS, and Push notifications in one unified interface
- 🎯 **Lightweight & Focused** - Does one thing well: delivers notifications. No bloat, no unnecessary dependencies.
- 🚀 **Multi-Channel Support** - Email, SMS, Push, and WhatsApp notifications in one unified interface
- 🔌 **Pluggable Providers** - Support for multiple providers (Twilio, AWS SNS, Firebase, Nodemailer, etc.)
- 📱 **WhatsApp Support** - Send WhatsApp messages with media support via Twilio API
- 🎯 **NestJS First** - Built specifically for NestJS with dependency injection support
- 📦 **Framework Agnostic Core** - Clean architecture with framework-independent domain logic
- 🔄 **Retry & Queue Management** - Built-in retry logic and notification state management
- 📊 **Event System** - Track notification lifecycle with event emitters
- 🎨 **Template Support** - Handlebars and simple template engines included
- 💾 **Flexible Storage** - MongoDB, PostgreSQL, or custom repository implementations
- ✅ **Fully Tested** - Comprehensive test suite with 133+ tests
- 🔒 **Type Safe** - Written in TypeScript with full type definitions

> **📐 Design Philosophy**: NotificationKit is a **delivery library**, not a content management system. Your application should manage templates, content, and business logic. NotificationKit focuses solely on reliable multi-channel delivery.

## 📦 Installation

```bash
Expand All @@ -39,6 +42,9 @@ npm install twilio # Twilio
npm install @aws-sdk/client-sns # AWS SNS
npm install @vonage/server-sdk # Vonage

# For WhatsApp
npm install twilio # Twilio WhatsApp API

# For push notifications (choose one)
npm install firebase-admin # Firebase
npm install @aws-sdk/client-sns # AWS SNS
Expand Down Expand Up @@ -148,7 +154,132 @@ POST /notifications/:id/retry
POST /notifications/:id/cancel
```

## 📚 Documentation
## � WhatsApp Support
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The section header contains a replacement character ("## � WhatsApp Support" / "## �📚 Documentation"), which will render incorrectly in Markdown. Replace it with a valid UTF-8 emoji/title (e.g., "## WhatsApp Support" or "## 📱 WhatsApp Support").

Suggested change
## WhatsApp Support
## 📱 WhatsApp Support

Copilot uses AI. Check for mistakes.

NotificationKit now supports WhatsApp messaging via Twilio's WhatsApp API with full media and template support!

### Setup WhatsApp Sender

```typescript
import { TwilioWhatsAppSender, MockWhatsAppSender } from "@ciscode/notification-kit";

// For production (real Twilio API)
NotificationKitModule.register({
senders: [
new TwilioWhatsAppSender({
accountSid: process.env.TWILIO_ACCOUNT_SID,
authToken: process.env.TWILIO_AUTH_TOKEN,
fromNumber: process.env.TWILIO_WHATSAPP_FROM, // e.g., '+14155238886'
templates: {
orderShipped: "order_shipped_v1",
welcomeMessage: "welcome_v2",
},
}),
],
// ... other config
});

// For development/testing (no credentials needed)
NotificationKitModule.register({
senders: [new MockWhatsAppSender({ logMessages: true })],
// ... other config
});
```

### Send WhatsApp Messages

#### Basic Text Message

```typescript
await notificationService.send({
channel: NotificationChannel.WHATSAPP,
priority: NotificationPriority.HIGH,
recipient: {
id: "user-123",
phone: "+14155551234", // E.164 format required
},
content: {
title: "Order Update",
body: "Your order #12345 has been shipped!",
},
});
```

#### WhatsApp with Media (Images/PDFs/Videos)

```typescript
await notificationService.send({
channel: NotificationChannel.WHATSAPP,
recipient: {
id: "user-456",
phone: "+447911123456",
},
content: {
title: "Invoice Ready",
body: "Your invoice is attached",
data: {
mediaUrl: "https://example.com/invoice.pdf",
},
},
});
```

#### WhatsApp with Templates

```typescript
await notificationService.send({
channel: NotificationChannel.WHATSAPP,
recipient: {
id: "user-789",
phone: "+212612345678",
},
content: {
title: "OTP Code",
body: "Your verification code is {{code}}",
templateId: "otp_verification",
templateVars: {
code: "123456",
expiryMinutes: "5",
},
},
});
```

### WhatsApp Requirements

- **Phone Format**: Must be E.164 format (`+[country code][number]`)
- ✅ Valid: `+14155551234`, `+447911123456`, `+212612345678`
- ❌ Invalid: `4155551234`, `+1-415-555-1234`, `+1 (415) 555-1234`
- **Twilio Account**: Required for production use
- **WhatsApp Opt-in**: Recipients must opt-in to receive messages (send "join [code]" to Twilio number)
- **Media Support**: Images, videos, audio, PDFs (max 16MB for videos, 5MB for images)
- **Templates**: Some message types require pre-approved WhatsApp templates

### Testing WhatsApp Without Twilio

Use `MockWhatsAppSender` for development:

```typescript
const mockSender = new MockWhatsAppSender({ logMessages: true });

// Simulates sending and logs to console
// No actual API calls or credentials needed
```

Console output example:

```
═══════════════════════════════════════════
📱 [MockWhatsApp] Simulating WhatsApp send
═══════════════════════════════════════════
To: +14155551234
Recipient ID: user-123

💬 Message: Your order has been shipped!
═══════════════════════════════════════════
```

## �📚 Documentation

### Core Concepts

Expand All @@ -157,6 +288,7 @@ POST /notifications/:id/cancel
- **EMAIL** - Email notifications via SMTP providers
- **SMS** - Text messages via SMS gateways
- **PUSH** - Mobile push notifications
- **WHATSAPP** - WhatsApp messages via Twilio or Meta Business API
- **WEBHOOK** - HTTP callbacks (coming soon)

#### Notification Status Lifecycle
Expand Down Expand Up @@ -188,6 +320,11 @@ CANCELLED
- **AwsSnsSender** - AWS SNS for SMS
- **VonageSmsSender** - Vonage (formerly Nexmo)

#### WhatsApp Senders

- **TwilioWhatsAppSender** - Twilio WhatsApp API (supports media & templates)
- **MockWhatsAppSender** - Mock sender for testing without credentials

#### Push Notification Senders

- **FirebasePushSender** - Firebase Cloud Messaging (FCM)
Expand Down Expand Up @@ -281,14 +418,7 @@ NotificationKitModule.registerAsync({
}),
],
repository: new MongooseNotificationRepository(/* connection */),
templateEngine: new HandlebarsTemplateEngine({
templates: {
welcome: {
title: "Welcome {{name}}!",
body: "Hello {{name}}, thanks for joining {{appName}}!",
},
},
}),
// templateEngine: optional - most apps manage templates in backend
eventEmitter: new InMemoryEventEmitter(),
}),
inject: [ConfigService],
Expand Down Expand Up @@ -317,37 +447,74 @@ eventEmitter.on("*", (event) => {
});
```

### Template Rendering
### Content Management

> ⚠️ **Best Practice**: Manage templates and content in your backend application, not in NotificationKit. Your app knows your business logic, user preferences, and localization needs better than a delivery library.

**Recommended Approach** (Render in Your Backend):

```typescript
import { HandlebarsTemplateEngine } from "@ciscode/notification-kit/infra";
@Injectable()
export class NotificationService {
constructor(
private templateService: TemplateService, // Your template service
private notificationKit: NotificationService, // From NotificationKit
) {}

const templateEngine = new HandlebarsTemplateEngine({
templates: {
async sendWelcomeEmail(user: User) {
// 1. Your backend renders the template
const content = await this.templateService.render("welcome", {
name: user.name,
appName: "MyApp",
});

// 2. NotificationKit delivers it
await this.notificationKit.send({
channel: NotificationChannel.EMAIL,
recipient: { id: user.id, email: user.email },
content: {
title: content.subject,
body: content.text,
html: content.html,
},
});
}
}
```

**Built-in Template Engine** (Optional, for simple use cases):

NotificationKit includes optional template engines for quick prototyping:

```typescript
import { SimpleTemplateEngine } from "@ciscode/notification-kit/infra";

// Only use for demos/prototyping
NotificationKitModule.register({
templateEngine: new SimpleTemplateEngine({
Comment on lines +489 to +494
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This example imports from @ciscode/notification-kit/infra, but the package exports only the root entry (.). Update the README to import SimpleTemplateEngine from @ciscode/notification-kit (or add subpath exports if intended).

Copilot uses AI. Check for mistakes.
welcome: {
title: "Welcome {{name}}!",
body: "Hello {{name}}, welcome to {{appName}}!",
html: "<h1>Welcome {{name}}!</h1><p>Thanks for joining {{appName}}!</p>",
},
},
}),
});

// Use in notification
// Send using template
await notificationService.send({
channel: NotificationChannel.EMAIL,
recipient: { id: "user-123", email: "user@example.com" },
content: {
templateId: "welcome",
templateVars: {
name: "John Doe",
appName: "My App",
},
templateVars: { name: "John", appName: "MyApp" },
},
});
```

### Webhook Handling

> **Note**: Built-in templates are optional and best suited for prototyping. Production apps should manage templates in the backend for flexibility, versioning, and localization. See [Template Configuration Guide](./docs/TEMPLATE_CONFIGURATION.md) for details.

````


Enable webhook endpoints to receive delivery notifications from providers:

```typescript
Expand All @@ -356,7 +523,7 @@ NotificationKitModule.register({
webhookSecret: process.env.WEBHOOK_SECRET,
// ... other options
});
```
````

Webhook endpoint: `POST /notifications/webhook`

Expand Down
Loading
Loading