'How to send push notifications with node and capacitor

I have Angular application with Capacitor (without Ionic) and I need to send push notifications to the user app from Node.js backend. How would I do that? Any article, source or example would be much appreciable?

Here is capacitor.config.ts file

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'xxx.xxxxxxx.xxx',
  appName: 'ABC',
  webDir: 'dist/abc',
  bundledWebRuntime: false,
  plugins: {
    PushNotifications: {
      presentationOptions: ["badge", "sound", "alert"],
    },
  },
};

export default config;

I have seen many artcles etc. on push notifications with Capacitor and Firebase but couldn't find a single source on my requirement.



Solution 1:[1]

The best and easiest solution so far is to implement it with firebase. There are primarily two parts to this entire setup

  • Configure Capacitor and Firebase to be able to receive notifications

For this I suggest you follow this tutorial word by word.

  • Code the nodejs implementation to send push notifications from the server

For this, follow the firebase official documentation

As a reference, here is how you can handle the nodejs part, this triggers push notifications successfully.

const admin = require("firebase-admin");

admin.initializeApp({
    credential: admin.credential.applicationDefault(),
    databaseURL: <Your-Firebase-DB-URL>
});

async function sendNotification(tokens, title, body, data = {}) {
    message = {
        notification: {
            title: title,
            body: body,
        },
        data: data
    }
    options = {
        priority: 'high'
    }
    result = await admin.messaging().sendToDevice(tokens, message, options)
    return result;
}

module.exports = { sendNotification };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chetan Bansal