@miafoo/fcm-web-push
TypeScript icon, indicating that this package has built-in type declarations

1.6.6 • Public • Published

npm version

A very minimal web push notification server using Firebase Cloud Messaging (FCM) for Node (and Electron).

Installation

npm install @miafoo/fcm-web-push

Prerequisites

  1. Firebase App ID
  2. Firebase Project ID
  3. Firebase API Key
  4. Firebase VAPID/Key Pair

You can find the first 3 in the Firebase Console when you create a new "Web app". The VAPID/Key pair can be found in the "Web configuration" section on the "Cloud Messaging" tab.

Usage

See examples folder for more complete examples than the one below.

import { register, FcmClient } from "@miafoo/fcm-web-push"

// Restore persistentIds from the previous session.
const previousPersistentIds: string[] = readPersistentIdsFromDisk()
const newPersistentIds: string[] = []

// Register the app with Firebase. Ideally you would store this registration
// and restore it next time you run the app.
// You can use the `encodeRegistration` and `decodeRegistration` functions
// to easily save and restore the registration as JSON strings.
// Note: Registration can take several seconds.
const registration = await register({
  apiKey: "xxxx",
  projectId: "xxxx",
  appId: "xxxx",
  vapidKey: "xxxx",
})

const client = new FcmClient({
  registration,
})

client.on("connect", () => {
  console.log("Connecting...")
})

client.on("connected", () => {
  console.log("Connected!")
})

client.on("disconnected", () => {
  console.log("Disconnected!")
})

client.on("message", (message) => {
  // Store the `persistentId`!
  newPersistentIds.push(message.persistentId)
  console.log(message)
})

// Pass in the `previousPersistentIds` to mark them seen, otheriwse they
// will be received again every time the client connects.
await client.connect(previousPersistentIds)
// Note: The `connect` promise resolves when the socket is closed.
// You can also close the socket manually by disconnecting:
client.disconnect()

// Save the new persistent ids so we can mark them seen next time we run.
writePersistentIdsToDisk(newPersistentIds)

Acknowledgements

Package Sidebar

Install

npm i @miafoo/fcm-web-push

Weekly Downloads

43

Version

1.6.6

License

MIT

Unpacked Size

400 kB

Total Files

39

Last publish

Collaborators

  • miafoo