Skip to content

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

License

Notifications You must be signed in to change notification settings

miafoo/fcm-web-push

Repository files navigation

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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published