@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-pluginConfiguration
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
- Go to Firebase Console > Project Settings > Service Accounts
- Click "Generate New Private Key"
- Download the JSON file
- Base64 encode the JSON file contents:
cat service-account.json | base64 - 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
datafield is required (can be an empty object{}) - All values in the
dataobject must be strings notificationis optional - omit it for silent data messages- The
sendmethod processes messages in batches of 500 devices
Context API
// Send a message
ctx.plugins.firebaseMessaging.send(message: Message): voidThe 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.sendoption
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
Invalid device tokens - Tokens expire or become invalid
- Implement token refresh on the client side
- Remove invalid tokens from your database
Service account permissions - Verify the service account has FCM permissions
- Check Firebase Console > Project Settings > Service Accounts
- Ensure "Firebase Admin SDK" role is granted
Base64 encoding - Ensure service account key is properly encoded
# Verify decoding works echo $FIREBASE_SERVICE_ACCOUNT_KEY_BASE64 | base64 -dApp 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
sendmethod is fire-and-forget (doesn't wait for delivery confirmation)
