npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

townkrier-fcm

v1.0.0-alpha.6

Published

Firebase Cloud Messaging adapter for Townkrier notification system

Downloads

82

Readme

townkrier-fcm

Firebase Cloud Messaging (FCM) push notification adapter for the TownKrier notification system.

Features

  • 📱 Push notifications for iOS and Android
  • 🔔 Rich notifications with images, actions, and badges
  • 🎯 Target specific devices, topics, or user segments
  • 📊 Delivery tracking and analytics
  • 🔄 Automatic retry with exponential backoff
  • 🌐 Multi-language support
  • 🔒 Secure authentication with service account

Installation

npm install townkrier-fcm townkrier-core
# or
pnpm add townkrier-fcm townkrier-core

Quick Start

import { NotificationManager, NotificationChannel } from 'townkrier-core';
import { createFcmChannel } from 'townkrier-fcm';

// Configure the manager with FCM channel
const manager = new NotificationManager({
  defaultChannel: 'push-fcm',
  channels: [
    {
      name: 'push-fcm',
      enabled: true,
      config: {
        projectId: process.env.FIREBASE_PROJECT_ID,
        serviceAccountPath: './firebase-service-account.json',
        // Or use service account key directly:
        // serviceAccountKey: JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT),
      },
    },
  ],
});

// Register the FCM channel factory
manager.registerFactory('push-fcm', createFcmChannel);

// Create a notification
class WelcomePushNotification extends Notification {
  constructor(private userName: string) {
    super();
  }

  via() {
    return [NotificationChannel.PUSH];
  }

  toPush() {
    return {
      token: 'device-fcm-token-here',
      notification: {
        title: 'Welcome! 👋',
        body: `Hi ${this.userName}, thanks for joining!`,
      },
    };
  }
}

// Send the notification
const notification = new WelcomePushNotification('John');
const recipient = {
  [NotificationChannel.PUSH]: {
    token: 'device-fcm-token',
  },
};

await manager.send(notification, recipient);

Configuration

FcmConfig

interface FcmConfig {
  projectId: string; // Required: Firebase project ID
  serviceAccountPath?: string; // Path to service account JSON file
  serviceAccountKey?: object; // Or service account key object
  timeout?: number; // Request timeout (default: 30000ms)
  debug?: boolean; // Enable debug logging (default: false)
}

Getting Service Account Credentials

  1. Go to Firebase Console
  2. Select your project
  3. Go to Project Settings → Service Accounts
  4. Click "Generate New Private Key"
  5. Save the JSON file securely
// Option 1: Using file path
{
  projectId: 'your-project-id',
  serviceAccountPath: './firebase-service-account.json',
}

// Option 2: Using environment variable
{
  projectId: process.env.FIREBASE_PROJECT_ID,
  serviceAccountKey: JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT),
}

Advanced Usage

Rich Notifications with Images

class OrderShippedNotification extends Notification {
  constructor(
    private orderNumber: string,
    private trackingUrl: string,
    private productImage: string,
  ) {
    super();
  }

  via() {
    return [NotificationChannel.PUSH];
  }

  toPush() {
    return {
      token: 'device-token',
      notification: {
        title: '📦 Order Shipped!',
        body: `Order #${this.orderNumber} is on its way`,
        imageUrl: this.productImage,
      },
      data: {
        orderId: this.orderNumber,
        trackingUrl: this.trackingUrl,
        action: 'view_order',
      },
      android: {
        priority: 'high',
        notification: {
          channelId: 'order_updates',
          color: '#FF6B6B',
          sound: 'default',
        },
      },
      apns: {
        payload: {
          aps: {
            badge: 1,
            sound: 'default',
          },
        },
      },
    };
  }
}

Topic-Based Notifications

class NewsAlertNotification extends Notification {
  constructor(private headline: string) {
    super();
  }

  via() {
    return [NotificationChannel.PUSH];
  }

  toPush() {
    return {
      topic: 'news-alerts', // Send to all devices subscribed to this topic
      notification: {
        title: '📰 Breaking News',
        body: this.headline,
      },
    };
  }
}

Conditional Notifications (Multiple Devices)

class SecurityAlertNotification extends Notification {
  via() {
    return [NotificationChannel.PUSH];
  }

  toPush() {
    return {
      condition: "'security-alerts' in topics || 'all-devices' in topics",
      notification: {
        title: '🔒 Security Alert',
        body: 'Unusual activity detected on your account',
      },
      android: {
        priority: 'high',
      },
      apns: {
        payload: {
          aps: {
            'content-available': 1, // Silent notification for background updates
          },
        },
      },
    };
  }
}

Platform-Specific Customization

class ChatMessageNotification extends Notification {
  constructor(
    private senderName: string,
    private message: string,
    private chatId: string,
  ) {
    super();
  }

  via() {
    return [NotificationChannel.PUSH];
  }

  toPush() {
    return {
      token: 'device-token',
      notification: {
        title: this.senderName,
        body: this.message,
      },
      data: {
        chatId: this.chatId,
        type: 'chat_message',
      },
      android: {
        priority: 'high',
        notification: {
          channelId: 'chat_messages',
          color: '#4A90E2',
          sound: 'chat_notification.mp3',
          tag: this.chatId, // Group notifications by chat
        },
      },
      apns: {
        headers: {
          'apns-priority': '10',
        },
        payload: {
          aps: {
            alert: {
              title: this.senderName,
              body: this.message,
            },
            badge: 1,
            sound: 'chat_notification.caf',
            category: 'CHAT_MESSAGE',
            'thread-id': this.chatId, // Group notifications by chat
          },
        },
      },
    };
  }
}

Scheduled Notifications

import { QueueManager } from 'townkrier-queue';

// Schedule notification for future delivery
const queueManager = new QueueManager(queueAdapter, manager);

await queueManager.enqueue(notification, recipient, {
  scheduledFor: new Date(Date.now() + 3600000), // Send in 1 hour
});

Message Types

Data Messages (Silent)

{
  token: 'device-token',
  data: {
    type: 'sync',
    timestamp: Date.now().toString(),
  },
  // No notification field = silent data message
}

Notification Messages

{
  token: 'device-token',
  notification: {
    title: 'New Message',
    body: 'You have a new message',
  },
  // User sees this in notification tray
}

Combined Messages

{
  token: 'device-token',
  notification: {
    title: 'New Message',
    body: 'You have a new message',
  },
  data: {
    messageId: '12345',
    senderId: 'user_789',
  },
  // Both visible notification and background data
}

Device Token Management

Getting Device Tokens

On the client side (iOS/Android):

// React Native example
import messaging from '@react-native-firebase/messaging';

const token = await messaging().getToken();
// Store this token in your backend for the user

Token Refresh

Tokens can change, so handle token refresh:

messaging().onTokenRefresh(async (newToken) => {
  // Update token in your backend
  await updateUserToken(userId, newToken);
});

Topic Management

Subscribe to Topics (Client Side)

import messaging from '@react-native-firebase/messaging';

await messaging().subscribeToTopic('news-alerts');
await messaging().subscribeToTopic('promotions');

Unsubscribe from Topics

await messaging().unsubscribeFromTopic('news-alerts');

Error Handling

import { NotificationFailed } from 'townkrier-core';

eventDispatcher.on(NotificationFailed, async (event) => {
  console.error('Push notification failed:', event.error.message);

  // Handle specific FCM errors
  if (event.error.message.includes('invalid-registration-token')) {
    // Remove invalid token from database
    await removeUserToken(userId);
  } else if (event.error.message.includes('message-rate-exceeded')) {
    // Implement rate limiting
    await delayNextNotification(userId);
  }
});

Common Errors

  • invalid-registration-token - Token is invalid, expired, or deleted
  • registration-token-not-registered - Token not registered
  • message-rate-exceeded - Too many messages to same device
  • invalid-apns-credentials - Invalid iOS certificates

Testing

Test Mode

{
  projectId: 'your-project-id',
  serviceAccountPath: './firebase-service-account.json',
  debug: true, // Enable detailed logging
}

Testing with FCM Console

  1. Go to Firebase Console → Cloud Messaging
  2. Click "Send Test Message"
  3. Enter device token
  4. Test your notification

Testing Locally

Use the Firebase Emulator Suite for local testing:

firebase emulators:start --only messaging

Best Practices

  1. Token Management: Keep device tokens up to date
  2. Handle Token Refresh: Update tokens when they change
  3. Remove Invalid Tokens: Clean up invalid tokens from your database
  4. Respect User Preferences: Allow users to control notification types
  5. Use Topics Wisely: Group users by interests, not individual targeting
  6. Optimize Payload Size: Keep data payloads small (4KB limit)
  7. Test on Real Devices: Emulators don't fully simulate push behavior
  8. Handle Time Zones: Consider user time zones for scheduled notifications
  9. Rate Limiting: Don't overwhelm users with too many notifications
  10. Analytics: Track delivery rates and user engagement

Notification Channels (Android)

For Android 8.0+, create notification channels in your app:

// Android example
NotificationChannel channel = new NotificationChannel(
    "order_updates",
    "Order Updates",
    NotificationManager.IMPORTANCE_HIGH
);
channel.setDescription("Notifications about your orders");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);

iOS Considerations

APNs Certificates

FCM handles APNs certificates automatically, but ensure:

  • Your APNs key is properly configured in Firebase Console
  • Your app has the correct bundle ID
  • Push notification capability is enabled in Xcode

Background Notifications

{
  token: 'device-token',
  apns: {
    payload: {
      aps: {
        'content-available': 1, // Enable background updates
        badge: 0,
      },
    },
  },
  data: {
    type: 'background_sync',
  },
}

Troubleshooting

"Service account not found"

  • Verify service account JSON file exists
  • Check file path is correct
  • Ensure file has proper read permissions

"Project ID mismatch"

  • Verify project ID matches your Firebase project
  • Check service account belongs to correct project

"Invalid token"

  • Token may have expired or been deleted
  • User may have uninstalled the app
  • Remove token from your database

Notifications not received

  • Check device is connected to internet
  • Verify app has notification permissions
  • Check notification channel settings (Android)
  • Verify APNs configuration (iOS)

Pricing

FCM is free for:

  • Unlimited notifications
  • All features

Additional Firebase services may have costs. Check Firebase Pricing.

Related Packages

Examples

See the examples directory for complete working examples:

Resources

License

MIT

Support

Author

Jeremiah Olisa