fms-notification-sdk
v2.4.0
Published
Production-ready Notification SDK with Topic & Broadcast support
Maintainers
Readme
FMS Notification SDK
A production-ready Notification SDK for Next.js and React applications, fully typed with TypeScript. It supports Firebase Cloud Messaging (FCM) for push notifications and Twilio for SMS, with built-in user management and admin capabilities.
Features
- 🚀 Push Notifications via Firebase Cloud Messaging (FCM).
- 💬 SMS Support via Twilio with dynamic configuration.
- �️ MongoDB Integration for storing notification history, tokens, and user data.
- 👤 User Management: Built-in User schema (
ObjectIdreferences) for seamless user-to-notification mapping. - ⚛️ React Hook (
useFCM) for easy client-side integration. - 🛠 Server Actions: Fully typed functions for sending notifications, broadcasting, and topic management.
- 📜 History API: Fetch push and SMS history with built-in filtering.
- 🛡️ Admin Capabilities: Easily build admin interfaces for targeted messaging.
1. Installation
Option A: Local Development (Recommended)
Pack the SDK:
cd fms-notification-sdk npm run build npm packThis generates a file like
fms-notification-sdk-1.1.16.tgz.Install in your App:
cd ../your-next-app npm install ../fms-notification-sdk/fms-notification-sdk-1.1.16.tgz
Option B: npm (If published)
npm install fms-notification-sdk2. Configuration
Environment Variables (.env.local)
Add these keys to your Next.js application:
# MongoDB Connection
MONGODB_URI=mongodb+srv://...
# --------------------------
# Firebase Admin (Server-Side)
# --------------------------
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxx@your-project-id.iam.gserviceaccount.com
# NOTE: Handle newlines in private key correctly
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
# --------------------------
# Twilio (SMS) - Optional if using SMS
# --------------------------
SMS_BASE_URL=https://api.twilio.com/2010-04-01 # Configurable base URL
TWILIO_ACCOUNT_SID=AC...
TWILIO_AUTH_TOKEN=...
TWILIO_FROM_NUMBER=+1234567890
# --------------------------
# Firebase Client (Public)
# --------------------------
NEXT_PUBLIC_FIREBASE_API_KEY=AIzaSy...
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-app.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-app.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=123456789
NEXT_PUBLIC_FIREBASE_APP_ID=1:123456789:web:abcdef...
NEXT_PUBLIC_FIREBASE_VAPID_KEY=BMk...
# --------------------------
# Mail Settings
# --------------------------
TRANSPORT_ACCOUNT_ID=your-transport-account-objectId3. Initialization (Server-Side)
Create a library file (e.g., src/lib/sdk.ts or .js) to initialize the SDK. This is required to set up MongoDB, Firebase, and Twilio connections.
// src/lib/sdk.ts
import { initNotificationSDK } from "fms-notification-sdk/server";
initNotificationSDK({
mongoUri: process.env.MONGODB_URI!,
firebase: {
projectId: process.env.FIREBASE_PROJECT_ID!,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL!,
privateKey: process.env.FIREBASE_PRIVATE_KEY!,
},
sms: {
providerName: "Twilio",
baseUrl: process.env.SMS_BASE_URL || "https://api.twilio.com/2010-04-01",
accountSid: process.env.TWILIO_ACCOUNT_SID!,
authToken: process.env.TWILIO_AUTH_TOKEN!,
fromNumber: process.env.TWILIO_FROM_NUMBER!,
},
// Used to fetch Zoho OAuth credentials globally for the Transport layer
transportAccountId: process.env.TRANSPORT_ACCOUNT_ID,
});
export * from "fms-notification-sdk/server";4. Usage
A. Sending SMS
The SDK automatically fetches the user's phone number from the User collection using the provided userId.
import { sendSMS } from "@/lib/sdk";
// Triggered from a Server Action or API Route
const result = await sendSMS({
userId: "682498e04eb71f9661a7feb6", // Must be a valid MongoDB ObjectId
message: "Your OTP is 123456",
});
if (result.success) {
console.log("SMS sent!", result.sid);
}B. Sending Push Notifications
import { sendNotification } from "@/lib/sdk";
await sendNotification({
userId: "682498e04eb71f9661a7feb6",
title: "Hello!",
body: "This is a test notification",
type: "success", // 'info' | 'success' | 'warning' | 'error'
data: { url: "/orders/123" },
});C. Fetching History
Fetch user notification history, optionally filtering by category ('push' or 'sms').
import { getNotifications } from "fms-notification-sdk/actions";
// Fetch all notifications (mixed)
const allLogs = await getNotifications("682498e04eb71f9661a7feb6");
// Filter client-side or extend API for specific filtering if needed
const smsLogs = allLogs.filter((n) => n.category === "sms");5. Client-Side Integration (Hooks)
useFCM
Used to receive foreground notifications and manage FCM tokens.
'use client';
import { useFCM } from 'fms-notification-sdk';
export default function Home() {
const { fcmToken, notificationPermission } = useFCM({
firebaseConfig: { ... }, // Public config object
vapidKey: process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY,
onTokenReceived: (token) => console.log('Token:', token),
// Handle foreground messages
onMessageReceived: (payload) => toast(payload.notification.title)
});
return <div>FCM Token: {fcmToken}</div>;
}6. Database Models
The SDK manages the following collections in MongoDB:
users(Usermodel):- Managed by App/SDK: The SDK now includes a User model. You can fetch/use it via
mongoose.models.User. - Fields:
_id(ObjectId),name,email,phone.
- Managed by App/SDK: The SDK now includes a User model. You can fetch/use it via
_glame_notification(Notificationmodel):- Stores history of Push and SMS.
- Fields:
userId(Ref: User),title,message,category('push'|'sms'),type,isRead.
_glame_firebase_token(Tokenmodel):- Stores user FCM tokens.
- Fields:
userId(Ref: User),token,platform,deviceId.
7. Admin Features
You can easily build an Admin Interface to send messages to any user:
// src/app/admin/actions.ts
"use server";
import { sendSMS } from "@/lib/sdk";
export async function sendSmsAction(formData: FormData) {
const userId = formData.get("userId") as string;
const message = formData.get("message") as string;
return await sendSMS({ userId, message });
}