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

@flink-app/firebase-messaging-plugin

v0.13.2

Published

Flink plugin to send Firebase cloud messages

Readme

Firebase Messaging Plugin

A Flink plugin for sending push notifications using Firebase Cloud Messaging (FCM). Send notifications to individual devices or multiple devices with support for both notification and data messages.

Installation

Install the plugin to your Flink app project:

npm install @flink-app/firebase-messaging-plugin

Configuration

Basic Setup

Configure the plugin with your Firebase service account credentials:

import { FlinkApp, FlinkContext } from "@flink-app/flink";
import { firebaseMessagingPlugin } from "@flink-app/firebase-messaging-plugin";

function start() {
  new FlinkApp<AppContext>({
    name: "My app",
    plugins: [
      firebaseMessagingPlugin({
        serviceAccountKey: process.env.FIREBASE_SERVICE_ACCOUNT_KEY_BASE64!,
        exposeEndpoints: false  // Optional: expose POST /send-message endpoint
      })
    ],
  }).start();
}

Plugin Options:

interface FirebaseMessagingPluginOptions {
  serviceAccountKey: string;    // Base64-encoded Firebase service account JSON
  exposeEndpoints?: boolean;    // Optional: expose HTTP endpoint (default: undefined)
  permissions?: {
    send: string;               // Optional: permission required for endpoint
  };
}

Getting Your Service Account Key

  1. Go to Firebase Console > Project Settings > Service Accounts
  2. Click "Generate New Private Key"
  3. Download the JSON file
  4. Base64 encode the JSON file contents:
    cat service-account.json | base64
  5. Store the base64 string in your environment variable

TypeScript Setup

Add the plugin context to your app's context type (usually in Ctx.ts):

import { FlinkContext } from "@flink-app/flink";
import { FirebaseMessagingContext } from "@flink-app/firebase-messaging-plugin";

export interface Ctx extends FlinkContext<FirebaseMessagingContext> {
  // Your other context properties
}

Plugin Context Interface:

interface FirebaseMessagingContext {
  firebaseMessaging: {
    send: (message: Message) => void;
  };
}

Usage in Handlers

Basic Notification

Send a simple push notification to a single device:

import { Handler } from "@flink-app/flink";
import { Ctx } from "../Ctx";

const SendNotification: Handler<Ctx, any, any> = async ({ ctx, req }) => {
  await ctx.plugins.firebaseMessaging.send({
    to: ["device_token_here"],
    notification: {
      title: "New Message",
      body: "You have received a new message"
    },
    data: {}
  });

  return { data: { success: true } };
};

export default SendNotification;

Notification to Multiple Devices

Send the same notification to multiple devices:

await ctx.plugins.firebaseMessaging.send({
  to: [
    "device_token_1",
    "device_token_2",
    "device_token_3"
  ],
  notification: {
    title: "System Update",
    body: "A new version is available"
  },
  data: {
    version: "2.0.0",
    updateUrl: "https://example.com/update"
  }
});

Data-Only Message

Send a data message without notification (silent push):

await ctx.plugins.firebaseMessaging.send({
  to: ["device_token"],
  data: {
    type: "sync",
    timestamp: Date.now().toString(),
    action: "refresh_data"
  }
});

Rich Notification with Custom Data

const SendOrderUpdate: Handler<Ctx, any, any> = async ({ ctx, req }) => {
  const { userId, orderId, status } = req.body;

  // Get user's device tokens from database
  const user = await ctx.repos.userRepo.findById(userId);
  const deviceTokens = user.pushNotificationTokens || [];

  await ctx.plugins.firebaseMessaging.send({
    to: deviceTokens,
    notification: {
      title: "Order Update",
      body: `Your order #${orderId} is now ${status}`
    },
    data: {
      orderId: orderId,
      status: status,
      screen: "order_details",
      timestamp: Date.now().toString()
    }
  });

  return { data: { sent: true } };
};

API Reference

Message Type

interface Message {
  to: string[];  // Array of FCM device tokens

  notification?: {
    title?: string;  // Notification title
    body?: string;   // Notification body text
  };

  data: { [key: string]: string };  // Custom data payload (all values must be strings)
}

Important Notes:

  • The data field is required (can be an empty object {})
  • All values in the data object must be strings
  • notification is optional - omit it for silent data messages
  • The send method processes messages in batches of 500 devices

Context API

// Send a message
ctx.plugins.firebaseMessaging.send(message: Message): void

The send method:

  • Processes devices in batches of 500 (FCM limitation)
  • Logs success/failure for each device to debug logs
  • Handles errors gracefully without throwing

Registered Endpoints

If exposeEndpoints is enabled, the plugin registers:

POST /send-message

Send a push notification via HTTP endpoint.

Request Body:

{
  to: string[];           // Device tokens
  notification?: {
    title?: string;
    body?: string;
  };
  data: { [key: string]: string };
}

Response:

{
  data: {
    failedDevices: string[]  // Currently returns empty array
  }
}

Example:

curl -X POST http://localhost:3000/send-message \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["device_token_123"],
    "notification": {
      "title": "Hello",
      "body": "World"
    },
    "data": {}
  }'

Permissions:

  • Default permission: firebase-messaging:send
  • Can be customized via permissions.send option

Complete Example

Here's a complete example showing different notification scenarios:

import { Handler } from "@flink-app/flink";
import { Ctx } from "../Ctx";

interface NotificationRequest {
  userIds: string[];
  type: "message" | "order" | "reminder" | "alert";
  title: string;
  body: string;
  data?: Record<string, any>;
}

const SendPushNotification: Handler<Ctx, NotificationRequest, { sent: number }> = async ({
  ctx,
  req
}) => {
  const { userIds, type, title, body, data = {} } = req.body;

  // Collect device tokens from all users
  const users = await ctx.repos.userRepo.findByIds(userIds);
  const deviceTokens: string[] = [];

  for (const user of users) {
    if (user.pushTokens && user.pushTokens.length > 0) {
      deviceTokens.push(...user.pushTokens);
    }
  }

  if (deviceTokens.length === 0) {
    return { data: { sent: 0 } };
  }

  // Convert data values to strings (FCM requirement)
  const stringData: { [key: string]: string } = {};
  for (const [key, value] of Object.entries(data)) {
    stringData[key] = String(value);
  }

  // Add metadata
  stringData.type = type;
  stringData.sentAt = new Date().toISOString();

  // Send notification
  await ctx.plugins.firebaseMessaging.send({
    to: deviceTokens,
    notification: {
      title,
      body
    },
    data: stringData
  });

  return { data: { sent: deviceTokens.length } };
};

export default SendPushNotification;

Best Practices

Device Token Management

Store and manage device tokens properly:

// When user logs in or registers device
const RegisterDeviceToken: Handler<Ctx, any, any> = async ({ ctx, req }) => {
  const { userId, deviceToken } = req.body;

  await ctx.repos.userRepo.update(userId, {
    $addToSet: { pushTokens: deviceToken }  // Avoid duplicates
  });

  return { data: { success: true } };
};

// When user logs out
const RemoveDeviceToken: Handler<Ctx, any, any> = async ({ ctx, req }) => {
  const { userId, deviceToken } = req.body;

  await ctx.repos.userRepo.update(userId, {
    $pull: { pushTokens: deviceToken }
  });

  return { data: { success: true } };
};

Data Payload Conversion

Always convert data values to strings:

// Bad - will fail
data: {
  userId: 123,           // Number
  isActive: true,        // Boolean
  metadata: { foo: "bar" } // Object
}

// Good - all strings
data: {
  userId: "123",
  isActive: "true",
  metadata: JSON.stringify({ foo: "bar" })
}

Notification vs Data Messages

Notification Messages:

  • Display a notification in the system tray
  • Wake up the app when tapped
  • Best for user-facing alerts

Data Messages:

  • Silent delivery to app
  • App handles processing
  • Best for background sync, state updates
// Notification message (user sees it)
{
  notification: { title: "New message", body: "John sent you a message" },
  data: { chatId: "123" }
}

// Data message (silent)
{
  data: { type: "sync", lastSyncTimestamp: "1234567890" }
}

Batch Processing

The plugin automatically handles batching (500 devices per batch), but you should still consider:

// Good - let the plugin handle batching
await ctx.plugins.firebaseMessaging.send({
  to: thousandsOfTokens,  // Plugin splits into batches of 500
  notification: { title: "Update", body: "New feature available" },
  data: {}
});

// Also good - send to specific segments
const activeUsers = await ctx.repos.userRepo.findActive();
const tokens = activeUsers.flatMap(u => u.pushTokens || []);
await ctx.plugins.firebaseMessaging.send({
  to: tokens,
  notification: { title: "Hello active users!", body: "..." },
  data: {}
});

Error Handling

The plugin logs errors internally but doesn't throw. Monitor logs:

// The plugin logs:
// - Success: "[firebaseMessaging] Successfully sent to device {token}"
// - Failure: "[firebaseMessaging] Failed sending to device {token}: {error}"
// - Batch error: "[firebaseMessaging] Failed sending batch: {error}"

// You can wrap sends with try-catch if needed
try {
  await ctx.plugins.firebaseMessaging.send({
    to: deviceTokens,
    notification: { title: "Test", body: "Test" },
    data: {}
  });
} catch (error) {
  console.error("Unexpected error:", error);
}

Troubleshooting

Notifications Not Received

  1. Invalid device tokens - Tokens expire or become invalid

    • Implement token refresh on the client side
    • Remove invalid tokens from your database
  2. Service account permissions - Verify the service account has FCM permissions

    • Check Firebase Console > Project Settings > Service Accounts
    • Ensure "Firebase Admin SDK" role is granted
  3. Base64 encoding - Ensure service account key is properly encoded

    # Verify decoding works
    echo $FIREBASE_SERVICE_ACCOUNT_KEY_BASE64 | base64 -d
  4. App not running - Data messages require the app to be running

    • Use notification messages to wake the app
    • Combine notification + data for best results

Invalid Data Format

Error: "All data values must be strings"

// Fix: Convert all values to strings
data: {
  count: String(42),
  timestamp: new Date().toISOString(),
  metadata: JSON.stringify({ key: "value" })
}

Check Debug Logs

Enable Flink debug mode to see detailed FCM logs:

new FlinkApp<Ctx>({
  name: "My app",
  debug: true,  // Enable debug logging
  plugins: [
    firebaseMessagingPlugin({ ... })
  ]
}).start();

Notes

  • Messages are processed in batches of 500 devices (FCM limitation)
  • All data values must be strings (numbers, booleans, objects must be converted)
  • The plugin uses Firebase Admin SDK v11+
  • Device tokens should be stored securely and updated regularly
  • Invalid/expired tokens are logged but don't stop delivery to other devices
  • The send method is fire-and-forget (doesn't wait for delivery confirmation)