Flink plugin to send Firebase cloud messages
npm install @flink-app/firebase-messaging-pluginA 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.
Install the plugin to your Flink app project:
``bash`
npm install @flink-app/firebase-messaging-plugin
Configure the plugin with your Firebase service account credentials:
`typescript
import { FlinkApp, FlinkContext } from "@flink-app/flink";
import { firebaseMessagingPlugin } from "@flink-app/firebase-messaging-plugin";
function start() {
new FlinkApp
name: "My app",
plugins: [
firebaseMessagingPlugin({
serviceAccountKey: process.env.FIREBASE_SERVICE_ACCOUNT_KEY_BASE64!,
exposeEndpoints: false // Optional: expose POST /send-message endpoint
})
],
}).start();
}
`
Plugin Options:
`typescript`
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
};
}
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:
`bash`
cat service-account.json | base64
5. Store the base64 string in your environment variable
Add the plugin context to your app's context type (usually in Ctx.ts):
`typescript
import { FlinkContext } from "@flink-app/flink";
import { FirebaseMessagingContext } from "@flink-app/firebase-messaging-plugin";
export interface Ctx extends FlinkContext
// Your other context properties
}
`
Plugin Context Interface:
`typescript`
interface FirebaseMessagingContext {
firebaseMessaging: {
send: (message: Message) => void;
};
}
Send a simple push notification to a single device:
`typescript
import { Handler } from "@flink-app/flink";
import { Ctx } from "../Ctx";
const SendNotification: Handler
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;
`
Send the same notification to multiple devices:
`typescript`
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"
}
});
Send a data message without notification (silent push):
`typescript`
await ctx.plugins.firebaseMessaging.send({
to: ["device_token"],
data: {
type: "sync",
timestamp: Date.now().toString(),
action: "refresh_data"
}
});
`typescript
const SendOrderUpdate: Handler
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 } };
};
`
`typescript
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 {})data
- All values in the object must be stringsnotification
- is optional - omit it for silent data messagessend
- The method processes messages in batches of 500 devices
`typescript`
// 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
If exposeEndpoints is enabled, the plugin registers:
Send a push notification via HTTP endpoint.
Request Body:
`typescript`
{
to: string[]; // Device tokens
notification?: {
title?: string;
body?: string;
};
data: { [key: string]: string };
}
Response:
`typescript`
{
data: {
failedDevices: string[] // Currently returns empty array
}
}
Example:
`bash`
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:sendpermissions.send
- Can be customized via option
Here's a complete example showing different notification scenarios:
`typescript
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
}
const SendPushNotification: Handler
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;
`
Store and manage device tokens properly:
`typescript
// When user logs in or registers device
const RegisterDeviceToken: Handler
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
const { userId, deviceToken } = req.body;
await ctx.repos.userRepo.update(userId, {
$pull: { pushTokens: deviceToken }
});
return { data: { success: true } };
};
`
Always convert data values to strings:
`typescript
// 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 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
`typescript
// 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" }
}
`
The plugin automatically handles batching (500 devices per batch), but you should still consider:
`typescript
// 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: {}
});
`
The plugin logs errors internally but doesn't throw. Monitor logs:
`typescript
// 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);
}
`
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
`bash`
# 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
Error: "All data values must be strings"
`typescript`
// Fix: Convert all values to strings
data: {
count: String(42),
timestamp: new Date().toISOString(),
metadata: JSON.stringify({ key: "value" })
}
Enable Flink debug mode to see detailed FCM logs:
`typescript`
new FlinkApp
name: "My app",
debug: true, // Enable debug logging
plugins: [
firebaseMessagingPlugin({ ... })
]
}).start();
- 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)