Eve library

In-App Notifications API

Guide

Revision 1

On this page

This document provides comprehensive documentation for the Lilith Notification Service In-App Notifications API, including WebSocket real-time delivery, notification history, and connection management.

Overview#

The In-App Notifications API provides:

  • WebSocket Real-Time Delivery: Live notification push to connected clients
  • Topic/Channel Subscriptions: Filtered notification delivery
  • Notification History: Persistent notification storage with pagination
  • Connection Management: Multi-device support with heartbeat monitoring
  • Read Status Tracking: Mark notifications as read across devices

Table of Contents#

  1. Architecture
  2. WebSocket Authentication
  3. WebSocket Connection
  4. Message Protocol
  5. Subscriptions
  6. Sending Notifications
  7. Notification History
  8. Connection Management
  9. REST Endpoints
  10. SDK Integration

Architecture#

System Components#

text
┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│   Mobile App    │     │    Web App      │     │   Desktop App   │
└────────┬────────┘     └────────┬────────┘     └────────┬────────┘
         │                       │                       │
         │ WebSocket             │ WebSocket             │ WebSocket
         │                       │                       │
         └───────────────────────┼───────────────────────┘
                                 │
                    ┌────────────┴────────────┐
                    │  Notification Service    │
                    │  (WebSocket Server)      │
                    └────────────┬────────────┘
                                 │
         ┌───────────────────────┼───────────────────────┐
         │                       │                       │
┌────────┴────────┐    ┌────────┴────────┐    ┌────────┴────────┐
│    Templates    │    │    History      │    │   Connections   │
└─────────────────┘    └─────────────────┘    └─────────────────┘

Connection Model#

typescript
interface WebSocketConnection {
  id: string; // Unique connection ID
  user_id: string; // User ID
  subscribed_topics: Set<string>; // Topic subscriptions
  subscribed_channels: Set<NotificationChannel>; // Channel subscriptions
  metadata: {
    connected_at: string;
    client_ip?: string;
    user_agent?: string;
    platform?: string;
    last_heartbeat: string;
  };
  state: 'connected' | 'disconnected';
}

WebSocket Authentication#

Environment Variables#

Variable Required Description
WS_SECRET Yes* HMAC secret for token signing

*A default key is used in development/test environments.

Token Structure#

typescript
interface WebSocketAuthPayload {
  user_id: string; // User identifier
  iat: number; // Issued at (Unix timestamp)
  exp: number; // Expiration (Unix timestamp, 24h)
  platform?: string; // Client platform (ios, android, web)
}

Generate Token#

POST /v1/ws/token

typescript
// Request
{
  user_id: "user_123",
  platform: "ios"
}

// Response
{
  token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  expires_in: 86400,  // 24 hours
  user_id: "user_123",
  platform: "ios"
}

Programmatic Token Generation#

typescript
import { generateWsToken, validateWsToken } from '@lilith/notification/helpers';

// Generate token
const token = generateWsToken('user_123', 'ios');

// Validate token
const payload = validateWsToken(token);
if (payload) {
  console.log(payload.user_id); // 'user_123'
}

WebSocket Connection#

Connection URL#

text
wss://api.lilith.app/v1/ws/notifications?token=<auth_token>

Or with Authorization header:

text
wss://api.lilith.app/v1/ws/notifications
Authorization: Bearer <auth_token>

Connection Flow#

text
Client                              Server
  │                                    │
  │──────── WebSocket Connect ────────>│
  │          (with token)              │
  │                                    │
  │<──────── Connected Message ────────│
  │    {connection_id, server_info}    │
  │                                    │
  │──────── Subscribe Message ────────>│
  │    {topics, channels}              │
  │                                    │
  │<──────── Subscribed Message ───────│
  │    {topics, channels}              │
  │                                    │
  │──────── Ping (heartbeat) ─────────>│
  │                                    │
  │<──────── Pong ─────────────────────│
  │                                    │
  │<──────── Notification ─────────────│
  │    {id, content, priority}         │
  │                                    │

Connection Constants#

typescript
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
const CONNECTION_TIMEOUT = 120000; // 2 minutes without heartbeat
const WS_TOKEN_EXPIRY = 86400; // 24 hours

Message Protocol#

Message Envelope#

typescript
interface WebSocketMessage<T = unknown> {
  type: WebSocketMessageType;
  data: T;
  message_id: string; // Unique message identifier
  timestamp: string; // ISO 8601 timestamp
}

type WebSocketMessageType =
  | 'connected'
  | 'error'
  | 'ping'
  | 'pong'
  | 'subscribe'
  | 'subscribed'
  | 'unsubscribe'
  | 'unsubscribed'
  | 'notification'
  | 'notification_update'
  | 'notification_read'
  | 'ack';

Server Messages#

Connected#

json
{
  "type": "connected",
  "data": {
    "connection_id": "ws-abc123...",
    "user_id": "user_123",
    "server_info": {
      "service": "notification",
      "version": "1.0.0",
      "features": [
        "real_time_notifications",
        "topic_subscriptions",
        "channel_filtering"
      ]
    }
  },
  "message_id": "msg-123...",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Notification#

json
{
  "type": "notification",
  "data": {
    "id": "notif-456",
    "template_id": "welcome_notification",
    "channel": "push",
    "priority": "high",
    "topic": "meditation_reminders",
    "content": {
      "subject": "Time to Meditate",
      "body": "Your daily meditation session is ready."
    },
    "status": "delivered",
    "created_at": "2024-01-01T12:00:00.000Z",
    "metadata": {}
  },
  "message_id": "msg-789...",
  "timestamp": "2024-01-01T12:00:00.000Z"
}

Notification Update#

json
{
  "type": "notification_update",
  "data": {
    "notification_id": "notif-456",
    "status": "read",
    "read": true,
    "updated_at": "2024-01-01T12:05:00.000Z"
  },
  "message_id": "msg-update...",
  "timestamp": "2024-01-01T12:05:00.000Z"
}

Error#

json
{
  "type": "error",
  "data": {
    "code": "unauthorized",
    "message": "Invalid or missing authentication token",
    "details": null
  },
  "message_id": "msg-err...",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Client Messages#

Ping (Heartbeat)#

json
{
  "type": "ping"
}

Response:

json
{
  "type": "pong",
  "data": {
    "timestamp": "2024-01-01T00:00:30.000Z"
  },
  "message_id": "msg-pong...",
  "timestamp": "2024-01-01T00:00:30.000Z"
}

Subscribe#

json
{
  "type": "subscribe",
  "data": {
    "topics": ["meditation_reminders", "course_updates"],
    "channels": ["push", "email"]
  }
}

Response:

json
{
  "type": "subscribed",
  "data": {
    "topics": ["meditation_reminders", "course_updates"],
    "channels": ["push", "email"]
  },
  "message_id": "msg-sub...",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Unsubscribe#

json
{
  "type": "unsubscribe",
  "data": {
    "topics": ["course_updates"],
    "channels": ["email"]
  }
}

Mark Read#

json
{
  "type": "notification_read",
  "data": {
    "notification_ids": ["notif-123", "notif-456"]
  }
}

Response:

json
{
  "type": "ack",
  "data": {
    "notification_ids": ["notif-123", "notif-456"],
    "marked_read": true
  },
  "message_id": "msg-ack...",
  "timestamp": "2024-01-01T00:00:00.000Z"
}

Subscriptions#

Topic Subscriptions#

Filter notifications by topic:

typescript
// Subscribe to specific topics
{
  type: 'subscribe',
  data: {
    topics: ['meditation_reminders', 'course_updates', 'achievements']
  }
}

// Only receive notifications matching subscribed topics
// If no topics subscribed, receive all notifications

Channel Subscriptions#

Filter notifications by channel:

typescript
// Subscribe to specific channels
{
  type: 'subscribe',
  data: {
    channels: ['push']  // Only in-app/push notifications
  }
}

// Available channels: 'push', 'email'

Combined Filtering#

typescript
// Subscribe to meditation reminders via push only
{
  type: 'subscribe',
  data: {
    topics: ['meditation_reminders'],
    channels: ['push']
  }
}

Subscription Management#

typescript
import {
  subscribeConnection,
  unsubscribeConnection,
} from '@lilith/notification/helpers';

// Subscribe
const result = subscribeConnection(state, connectionId, ['topic1'], ['push']);

// Unsubscribe
unsubscribeConnection(state, connectionId, ['topic1']);

// Get subscriptions
const connection = state.wsConnections.get(connectionId);
console.log(Array.from(connection.subscribed_topics));
console.log(Array.from(connection.subscribed_channels));

Sending Notifications#

Send Single Notification#

POST /v1/notifications/send

typescript
// Request
{
  user_id: "user_123",
  template_id: "meditation_reminder",
  channel: "push",
  topic: "meditation_reminders",
  variables: {
    session_name: "Morning Meditation",
    duration: "10 minutes"
  },
  priority: "high"
}

// Response
{
  id: "notif-123",
  user_id: "user_123",
  template_id: "meditation_reminder",
  channel: "push",
  topic: "meditation_reminders",
  priority: "high",
  status: "sent",
  created_at: "2024-01-01T12:00:00.000Z",
  sent_at: "2024-01-01T12:00:00.000Z"
}

Send Batch Notifications#

POST /v1/notifications/send-batch

typescript
// Request
{
  template_id: "weekly_digest",
  channel: "email",
  variables: {
    week_number: 1
  },
  recipients: [
    { user_id: "user_1", email: "user1@example.com", variables: { name: "Sarah" } },
    { user_id: "user_2", email: "user2@example.com", variables: { name: "Mike" } }
  ]
}

// Response
{
  batch_id: "batch-456",
  notifications: [...],
  total_sent: 2,
  total_skipped_unsubscribed: 0,
  total_rate_limited: 0,
  total_recipients: 2,
  created_at: "2024-01-01T12:00:00.000Z"
}

Deliver via WebSocket#

POST /v1/ws/deliver

typescript
// Request
{
  user_id: "user_123",
  notification_id: "notif-789",
  template_id: "meditation_reminder",
  channel: "push",
  topic: "meditation_reminders",
  variables: {
    session_name: "Evening Meditation"
  }
}

// Response
{
  notification_id: "notif-789",
  user_id: "user_123",
  delivered: 2,   // Number of connections that received it
  failed: 0,
  delivered_at: "2024-01-01T20:00:00.000Z"
}

Programmatic Delivery#

typescript
import { deliverNotificationToUser } from '@lilith/notification/routes/websocket';

const result = deliverNotificationToUser(state, userId, notification, {
  subject: 'Hello',
  body: 'World',
});

console.log(`Delivered to ${result.delivered} connections`);

Notification History#

Get User History#

GET /v1/users/:userId/notification-history

Query Parameters:

  • limit - Max notifications to return (default: 50)
  • offset - Pagination offset (default: 0)
  • status - Filter by status (pending, sent, delivered, read, failed)
  • channel - Filter by channel (push, email)
typescript
// Request
GET /v1/users/user_123/notification-history?limit=10&status=sent&channel=push

// Response
{
  notifications: [
    {
      id: "notif-123",
      user_id: "user_123",
      template_id: "meditation_reminder",
      channel: "push",
      status: "sent",
      created_at: "2024-01-01T12:00:00.000Z",
      sent_at: "2024-01-01T12:00:00.000Z"
    }
  ],
  total_count: 45,
  pagination: {
    limit: 10,
    offset: 0,
    has_more: true
  }
}

Notification Status#

typescript
type NotificationStatus =
  | 'pending' // Created, not yet sent
  | 'sent' // Sent to delivery system
  | 'delivered' // Confirmed delivery
  | 'read' // User marked as read
  | 'failed'; // Delivery failed

Connection Management#

Get Connection Statistics#

GET /v1/ws/stats

typescript
// Response
{
  total_connections: 150,
  unique_users: 100,
  connections_by_state: {
    connected: 148,
    disconnected: 2
  },
  generated_at: "2024-01-01T12:00:00.000Z"
}

Get User Connections#

GET /v1/ws/connections/:userId

typescript
// Response
{
  user_id: "user_123",
  connections: [
    {
      id: "ws-abc123...",
      subscribed_topics: ["meditation_reminders"],
      subscribed_channels: ["push"],
      metadata: {
        connected_at: "2024-01-01T10:00:00.000Z",
        client_ip: "192.168.1.1",
        user_agent: "LilithApp/1.0 iOS",
        platform: "ios",
        last_heartbeat: "2024-01-01T11:59:30.000Z"
      },
      state: "connected"
    }
  ],
  total_connections: 1
}

Stale Connection Cleanup#

Connections without heartbeat for 2 minutes are automatically closed:

typescript
import { getStaleConnections } from '@lilith/notification/helpers';

// Run periodically (every 30 seconds)
const staleConnections = getStaleConnections(state);
for (const connectionId of staleConnections) {
  // Close WebSocket and cleanup
}

REST Endpoints#

Summary#

Method Endpoint Description
POST /v1/ws/token Generate WebSocket auth token
GET /v1/ws/stats Get connection statistics
GET /v1/ws/connections/:userId Get user's active connections
POST /v1/ws/deliver Deliver notification via WebSocket
POST /v1/notifications/send Send notification
POST /v1/notifications/send-batch Send batch notifications
GET /v1/users/:userId/notification-history Get notification history
POST /v1/notifications/test Test notification rendering

Test Notification#

POST /v1/notifications/test

typescript
// Request
{
  template_id: "welcome_notification",
  user_id: "user_123",
  channel: "push",
  variables: {
    user_name: "Sarah"
  },
  sandbox: true
}

// Response
{
  id: "test-123",
  template_id: "welcome_notification",
  status: "test_sent",
  rendered_content: {
    subject: "Welcome, Sarah!",
    body: "Welcome to Lilith, Sarah!"
  },
  sent_at: "2024-01-01T12:00:00.000Z"
}

SDK Integration#

TypeScript/JavaScript#

typescript
import { LilithClient } from '@lilith/sdk';

const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
});

// Get WebSocket token
const tokenResponse = await client.notifications.ws.getToken({
  userId: 'user_123',
  platform: 'ios',
});

// Connect to WebSocket
const ws = new WebSocket(
  `wss://api.lilith.app/v1/ws/notifications?token=${tokenResponse.token}`
);

ws.onopen = () => {
  console.log('Connected');

  // Subscribe to topics
  ws.send(
    JSON.stringify({
      type: 'subscribe',
      data: {
        topics: ['meditation_reminders', 'achievements'],
        channels: ['push'],
      },
    })
  );
};

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);

  switch (message.type) {
    case 'connected':
      console.log('Connection ID:', message.data.connection_id);
      break;

    case 'notification':
      console.log('New notification:', message.data);
      // Display notification to user
      break;

    case 'notification_update':
      console.log('Notification updated:', message.data);
      break;
  }
};

// Send heartbeat every 25 seconds
setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'ping' }));
  }
}, 25000);

// Mark notifications as read
function markAsRead(notificationIds: string[]) {
  ws.send(
    JSON.stringify({
      type: 'notification_read',
      data: { notification_ids: notificationIds },
    })
  );
}

// Get notification history
const history = await client.notifications.getHistory('user_123', {
  limit: 20,
  channel: 'push',
});

React Native Hook#

typescript
import { useEffect, useRef, useState } from 'react';

function useNotifications(userId: string) {
  const [connected, setConnected] = useState(false);
  const [notifications, setNotifications] = useState([]);
  const wsRef = useRef<WebSocket | null>(null);

  useEffect(() => {
    async function connect() {
      const { token } = await api.getWsToken(userId);
      const ws = new WebSocket(
        `wss://api.lilith.app/v1/ws/notifications?token=${token}`
      );

      ws.onopen = () => setConnected(true);
      ws.onclose = () => setConnected(false);

      ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        if (message.type === 'notification') {
          setNotifications((prev) => [message.data, ...prev]);
        }
      };

      wsRef.current = ws;
    }

    connect();
    return () => wsRef.current?.close();
  }, [userId]);

  const markRead = (ids: string[]) => {
    wsRef.current?.send(
      JSON.stringify({
        type: 'notification_read',
        data: { notification_ids: ids },
      })
    );
  };

  return { connected, notifications, markRead };
}

Error Codes#

Code Description
unauthorized Invalid or missing authentication token
connection_not_found Connection ID not found
invalid_message Could not parse message
unknown_message_type Unrecognized message type
no_connections No active connections for user
missing_user_id user_id is required
missing_fields Required fields missing


Questions?#

  • Technical Support: api-support@lilith.app
  • Documentation: GitHub Issues