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 🙏

© 2024 – Pkg Stats / Ryan Hefner

fcm-cloudflare-workers

v2.0.0

Published

Send multicast notifications through the FCM HTTP v1 API on Cloudflare Workers.

Downloads

210

Readme

FCM Cloudflare Workers

npm version

Send Firebase Cloud Messages (FCM) through the FCM HTTP v1 API on Cloudflare Workers.

This project is a fork of fcm-http2 and has been modified to work with Cloudflare Workers.

Features

  • 🚀 Full support for FCM HTTP v1 API message format
  • 💪 TypeScript support with comprehensive type definitions
  • ⚡️ Optimized for Cloudflare Workers
  • 🔄 Automatic token rotation and caching
  • 📦 Batched message sending support
  • 🎯 Multiple targeting options (token, topic, condition)
  • ✨ Zero dependencies

Installation

npm install fcm-cloudflare-workers

Usage

Initialize FCM

import { FCM, FcmOptions } from 'fcm-cloudflare-workers';

// Init FCM with options (minimal example)
const fcmOptions = new FcmOptions({
    // Pass in your service account JSON private key file (https://console.firebase.google.com/u/0/project/_/settings/serviceaccounts/adminsdk)
    serviceAccount: JSON.parse(env.FIREBASE_SERVICE_ACCOUNT_JSON),
});

// Or, init FCM with access token caching using KV (optional but recommended for performance)
const fcmOptions = new FcmOptions({
    serviceAccount: JSON.parse(env.FIREBASE_SERVICE_ACCOUNT_JSON),
    // Specify a KV namespace
    kvStore: env.MY_KV_NAMESPACE,
    // Specify a key to use for caching the access token
    kvCacheKey: 'fcm_access_token',
});

const fcm = new FCM(fcmOptions);

Send to Single Device

import { EnhancedFcmMessage } from 'fcm-cloudflare-workers';

const message: EnhancedFcmMessage = {
    notification: {
        title: "New Message",
        body: "You have a new message!",
        image: "https://example.com/image.png" 
    },
    data: {
        key: "value",
    },
    // Optional platform-specific configurations
    android: {
        notification: {
            click_action: "OPEN_MESSAGE",
            channel_id: "messages",
            icon: "message_icon"
        }
    },
    apns: {
        payload: {
            aps: {
                badge: 1,
                sound: "default"
            }
        }
    },
    webpush: {
        notification: {
            icon: "https://example.com/icon.png",
            badge: "https://example.com/badge.png",
            actions: [
                {
                    action: "view",
                    title: "View Message"
                }
            ]
        }
    }
};

try {
    await fcm.sendToToken(message, "device-token");
} catch (error) {
    console.error("Error sending message:", error);
}

Send to Multiple Devices

const tokens = [
    "device-token-1",
    "device-token-2",
    "device-token-3"
];

try {
    const unregisteredTokens = await fcm.sendToTokens(message, tokens);
    if (unregisteredTokens.length > 0) {
        console.log("Some tokens are no longer registered:", unregisteredTokens);
    }
} catch (error) {
    console.error("Error sending to multiple devices:", error);
}

Send to Topic

try {
    await fcm.sendToTopic(message, "news");
} catch (error) {
    console.error("Error sending to topic:", error);
}

Send with Condition

try {
    await fcm.sendToCondition(message, "'sports' in topics && 'news' in topics");
} catch (error) {
    console.error("Error sending to condition:", error);
}

Migration Guide

Upgrading from sendMulticast

The sendMulticast method is now deprecated in favor of the new sendToTokens method. Here's how to upgrade your code:

// Old way (deprecated)
import { FCM, FcmMessage } from 'fcm-cloudflare-workers';

const message: FcmMessage = {
    notification: {
        title: "Hello",
        body: "World"
    },
    data: {
        key: "value"
    }
};

const unregisteredTokens = await fcm.sendMulticast(message, tokens);

// New way
import { FCM, EnhancedFcmMessage } from 'fcm-cloudflare-workers';

const message: EnhancedFcmMessage = {
    notification: {
        title: "Hello",
        body: "World"
    },
    data: {
        key: "value"
    },
    // Now you can also use platform-specific configurations
    android: {
        notification: {
            channel_id: "default"
        }
    }
};

const unregisteredTokens = await fcm.sendToTokens(message, tokens);

The new sendToTokens method:

  • Maintains the same batching and performance optimizations as sendMulticast
  • Returns unregistered tokens in the same way
  • Adds support for all FCM HTTP v1 API message properties (android, apns, webpush, etc.)
  • Provides better TypeScript type safety

API Reference

FCM Methods

  • sendToToken(message: EnhancedFcmMessage, token: string): Promise<void> Sends a message to a single device using its FCM token.

  • sendToTokens(message: EnhancedFcmMessage, tokens: string[]): Promise<string[]> Sends a message to multiple devices. Returns an array of tokens that are no longer registered.

  • sendToTopic(message: EnhancedFcmMessage, topic: string): Promise<void> Sends a message to all devices subscribed to a specific topic.

  • sendToCondition(message: EnhancedFcmMessage, condition: string): Promise<void> Sends a message to devices that match the specified condition.

  • sendMulticast(message: FcmMessage, tokens: string[]): Promise<string[]> Deprecated: Use sendToTokens instead. Kept for backward compatibility.

Contributions

This repo is based on previous work by kenble and eladnava.

Support

Please open an issue on this repo if you have any questions or need support.

License

Apache-2.0