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");
});
@elye
Copy link

elye commented Sep 10, 2023

Great reference!!

If you don't mind explain, what's the use of

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

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

I commented them out, and the code still work.

@adityathakurxd
Copy link
Author

cors

Hi, I am not very good with backend side of things, but I was getting CORS issue on deployment, to solve which had added this.

More on this:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors

This is not an error but a security measure to secure users or the website which you are accessing from a potential security breach. This breach may occur due to incomplete or improper HTTP headers on the client-side implementation (eg. missing authorization data such as API key).

@chiranjeevkapoor
Copy link

chiranjeevkapoor commented Sep 30, 2023

app.use(cors({origin: "" }));
it lets your server receive request from everywhere, you can replace the "
" with a url to only let your server receive requests from that origin.

@mikelantzelo
Copy link

mikelantzelo commented Nov 15, 2023

i follow the instructions but still get the error:
"code": "app/invalid-credential",
"message": "Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND"." Can you hlep me?

@abjerry97
Copy link

try adding this

import admin from "firebase-admin";
import serviceAccount from "path/to/serviceAccountKey.json"";

initializeApp({
credential: admin.credential.cert(serviceAccount),
projectId: "your project_id",
});

@mikelantzelo
Copy link

try adding this

import admin from "firebase-admin"; import serviceAccount from "path/to/serviceAccountKey.json"";

initializeApp({ credential: admin.credential.cert(serviceAccount), projectId: "your project_id", });

Can you provide the full code? I have not much experience on this

@abjerry97
Copy link

import { initializeApp, applicationDefault } from "firebase-admin/app";
import { getMessaging } from "firebase-admin/messaging";
import express, { json } from "express";
import cors from "cors";
import admin from "firebase-admin";
import serviceAccount from "path/to/serviceAccountKey.json" assert { type: "json" };

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: admin.credential.cert(serviceAccount),
projectId: "your project_id",
});

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");
});
`

@mikelantzelo
Copy link

mikelantzelo commented Nov 16, 2023

import { initializeApp, applicationDefault } from "firebase-admin/app"; import { getMessaging } from "firebase-admin/messaging"; import express, { json } from "express"; import cors from "cors"; import admin from "firebase-admin"; import serviceAccount from "path/to/serviceAccountKey.json" assert { type: "json" };

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: admin.credential.cert(serviceAccount), projectId: "your project_id", });

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"); }); `

Thank you for your answer. I replaced:
import serviceAccount from "path/to/serviceAccountKey.json" assert { type: "json" };
with
import { readFileSync } from "fs";
const serviceAccount = JSON.parse(readFileSync("./path.json"));
and everything works great now! BIG THANKS FOR YOUR HELP!!!

@mikelantzelo
Copy link

the line:
const receivedToken = req.query.fcmToken
returns undefined when trying to pass the token to body. Can someone help me?

@HackX-IN
Copy link

the line: const receivedToken = req.query.fcmToken returns undefined when trying to pass the token to body. Can someone help me?

try to pass using req.body.fcmtoken

@kuldipkoladiya
Copy link

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

@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