Skip to content

Instantly share code, notes, and snippets.

@adityathakurxd
Last active February 27, 2024 20:21
Show Gist options
  • Save adityathakurxd/b7750a19edfd4197cd566086aeb4e2bb to your computer and use it in GitHub Desktop.
Save adityathakurxd/b7750a19edfd4197cd566086aeb4e2bb to your computer and use it in GitHub Desktop.
Node Server code to use Firebase Admin SDK to send out push notifications. When a post endpoint is hit on the Node JS server, it delivers a notification to a Flutter app using Firebase Messaging.
import {initializeApp, applicationDefault } from 'firebase-admin/app';
import { getMessaging } from "firebase-admin/messaging";
import express, { json } from "express";
import cors from "cors";
process.env.GOOGLE_APPLICATION_CREDENTIALS;
const app = express();
app.use(express.json());
app.use(
cors({
origin: "*",
})
);
app.use(
cors({
methods: ["GET", "POST", "DELETE", "UPDATE", "PUT", "PATCH"],
})
);
app.use(function(req, res, next) {
res.setHeader("Content-Type", "application/json");
next();
});
initializeApp({
credential: applicationDefault(),
projectId: 'potion-for-creators',
});
app.post("/send", function (req, res) {
const receivedToken = req.body.fcmToken;
const message = {
notification: {
title: "Notif",
body: 'This is a Test Notification'
},
token: "YOUR FCM TOKEN HERE",
};
getMessaging()
.send(message)
.then((response) => {
res.status(200).json({
message: "Successfully sent message",
token: receivedToken,
});
console.log("Successfully sent message:", response);
})
.catch((error) => {
res.status(400);
res.send(error);
console.log("Error sending message:", error);
});
});
app.listen(3000, function () {
console.log("Server started on port 3000");
});
@HackX-IN
Copy link

the line: import serviceAccount from "path/to/serviceAccountKey.json" assert { type: "json" }; returns Cannot find package 'path'

You need to import your own service file , which you have downloaded from firebase

@faekbank2024
Copy link

faekbank2024 commented Feb 20, 2024

Hi everyone:

I am getting an error:
Error: Exactly one of topic, token or condition is required
at validateMessage (/opt/render/project/src/node_modules/firebase-admin/lib/messaging/messaging-internal.js:53:15)
at Messaging.send (/opt/render/project/src/node_modules/firebase-admin/lib/messaging/messaging.js:185:50)
at file:///opt/render/project/src/index.js:47:6
at Layer.handle [as handle_request] (/opt/render/project/src/node_modules/express/lib/router/layer.js:95:5)
at next (/opt/render/project/src/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/opt/render/project/src/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/opt/render/project/src/node_modules/express/lib/router/layer.js:95:5)
at /opt/render/project/src/node_modules/express/lib/router/index.js:284:15
at Function.process_params (/opt/render/project/src/node_modules/express/lib/router/index.js:346:12)
at next (/opt/render/project/src/node_modules/express/lib/router/index.js:280:10)

When I tried to chatgpt it, not much useful information was received. This is how my code looks:
` import {initializeApp, applicationDefault } from 'firebase-admin/app';
 import { getMessaging } from "firebase-admin/messaging";
 import express from "express";
 import cors from "cors";


 process.env.GOOGLE_APPLICATION_CREDENTIALS;

 const app = express();
 app.use(express.json());

 app.use(
  cors({
     origin: "*",
         })
     );

app.use(
   cors({
       methods: ["GET", "POST", "DELETE", "UPDATE", "PUT", "PATCH"],
     })
 );

 app.use(function(req, res, next) {
 res.setHeader("Content-Type", "application/json");
  next();
 });


 initializeApp({
 credential: applicationDefault(),
 projectId: 'faekbank-app',
 }); 

 app.post("/send", function (req, res) {
  const receivedToken = req.body.fcmToken;

  const message = {
   notification: {
    title: "Notif",
    body: 'This is a Test Notification'
   },
    token: receivedToken,
   };

  getMessaging()
   .send(message)
  .then((response) => {
    res.status(200).json({
      message: "Successfully sent message",
      token: receivedToken,
    });
    console.log("Successfully sent message:", response);
  })
  .catch((error) => {
    res.status(400);
    res.send(error);
    console.log("Error sending message:", error);
  });


 });

 app.listen(3000, function () {
 console.log("Server started on port 3000");
  }); `

Can someone help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment