@namkhongdeptrai/notification-client
v1.0.3
Published
Real-time notification client SDK with WebSocket and Web Push support
Maintainers
Readme
🔔 Notification Client SDK
Real-time notification client with WebSocket and Web Push support.
Installation
npm install @namkhongdeptrai/notification-client
# or
yarn add @namkhongdeptrai/notification-client
# or
pnpm add @namkhongdeptrai/notification-clientInstall Service Worker (for Web Push)
After installing the package, run this command to copy the service worker to your public folder:
npx notification-client-install-swThis will create public/sw.js in your project. Then register it in your app:
// Register service worker (once at app startup)
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js")
.then((reg) => {
console.log("Service Worker registered:", reg);
})
.catch((err) => {
console.error("Service Worker registration failed:", err);
});
}Quick Start
Vanilla JavaScript/TypeScript
import { NotificationClient } from "@namkhongdeptrai/notification-client";
// 1. Initialize (once at app startup)
NotificationClient.init({
serverUrl: "https://your-notification-server.com",
apiKey: "your-api-key",
debug: true, // optional
});
// 2. Connect with user ID
NotificationClient.connect("user-123");
// 3. Listen for notifications
const unsubscribe = NotificationClient.onNotification((notification) => {
console.log("New notification:", notification);
// Show toast, update UI, etc.
});
// 4. Enable Web Push (optional)
const result = await NotificationClient.enablePush();
if (result.ok) {
console.log("Push enabled!");
}
// 5. Mark as read
await NotificationClient.markAsRead("notification-id");
// 6. Disconnect when done
NotificationClient.disconnect();React
import { NotificationClient } from "@namkhongdeptrai/notification-client";
import {
useNotifications,
NotificationProvider,
NotificationBell,
} from "@namkhongdeptrai/notification-client/react";
// Option 1: Manual initialization
NotificationClient.init({
serverUrl: "https://your-server.com",
apiKey: "your-key",
});
function App() {
const [userId, setUserId] = useState<string | null>(null);
useEffect(() => {
// Connect when user logs in
if (userId) {
NotificationClient.connect(userId);
}
}, [userId]);
return <NotificationList />;
}
function NotificationList() {
const {
isConnected,
notifications,
unreadCount,
markAsRead,
markAllAsRead,
enablePush,
} = useNotifications({
onNotification: (n) => {
// Show toast notification
toast.success(n.title);
},
});
return (
<div>
<h2>🔔 Notifications ({unreadCount} unread)</h2>
{notifications.map((n) => (
<div key={n.id} onClick={() => markAsRead(n.id)}>
<strong>{n.title}</strong>
<p>{n.message}</p>
</div>
))}
</div>
);
}// Option 2: Using Provider
function App() {
const userId = useAuth(); // Your auth hook
return (
<NotificationProvider
serverUrl="https://your-server.com"
apiKey="your-key"
userId={userId}
autoConnect
>
<Header />
<MainContent />
</NotificationProvider>
);
}
function Header() {
return (
<nav>
<NotificationBell onClick={() => navigate("/notifications")} />
</nav>
);
}API Reference
NotificationClient
| Method | Description |
| -------------------------- | -------------------------------------- |
| init(config) | Initialize with server URL and API key |
| connect(userId) | Connect to server as a user |
| disconnect() | Disconnect from server |
| onNotification(callback) | Listen for new notifications |
| markAsRead(id) | Mark a notification as read |
| markAllAsRead() | Mark all notifications as read |
| clearAll() | Clear all notifications locally |
| enablePush() | Enable Web Push notifications |
| disablePush() | Disable Web Push notifications |
| checkPushStatus() | Check current push status |
Properties
| Property | Type | Description |
| --------------- | ---------------- | ------------------------------ |
| isConnected | boolean | Connection status |
| notifications | Notification[] | Current notifications |
| unreadCount | number | Number of unread notifications |
| pushEnabled | boolean | Push notification status |
| currentUserId | string \| null | Connected user ID |
useNotifications Hook
const {
isConnected,
userId,
notifications,
unreadCount,
pushEnabled,
markAsRead,
markAllAsRead,
clearAll,
enablePush,
disablePush,
disconnect,
} = useNotifications({
onNotification: (notification) => {
// Handle new notification
},
});Web Push Setup
- Create a service worker file at
/public/sw.js:
self.addEventListener("push", (event) => {
const data = event.data?.json() || {};
event.waitUntil(
self.registration.showNotification(data.title || "Notification", {
body: data.body || "",
icon: data.icon || "/icon.png",
badge: "/badge.png",
tag: data.tag,
data: data.data,
})
);
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const url = event.notification.data?.url || "/";
event.waitUntil(clients.openWindow(url));
});- Enable push in your app:
const result = await NotificationClient.enablePush();
if (!result.ok) {
console.error("Failed to enable push:", result.reason);
}TypeScript
Full TypeScript support included:
import type {
Notification,
NotificationState,
} from "@anthropic/notification-client";
const handleNotification = (notification: Notification) => {
console.log(notification.title, notification.message);
};License
MIT
