Last active
January 16, 2021 14:08
-
-
Save GunaShekar02/45f353ac28d4762fb04dbe54d7f45602 to your computer and use it in GitHub Desktop.
Firebase Cloud Messaging - Push Notifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Express = require("express"); | |
const bodyParser = require("body-parser"); | |
const admin = require("firebase-admin"); | |
const serviceAccount = require("./firebase.json"); | |
admin.initializeApp({ | |
credential: admin.credential.cert(serviceAccount), | |
}); | |
const tokens = []; | |
const app = new Express(); | |
const router = Express.Router(); | |
app.use(bodyParser.json()); | |
app.use("/", router); | |
app.listen(3000, () => { | |
console.log(`Server started on port 3000`); | |
}); | |
router.post("/register", (req, res) => { | |
tokens.push(req.body.token); | |
res.status(200).json({ message: "Successfully registered FCM Token!" }); | |
}); | |
router.post("/notifications", async (req, res) => { | |
try { | |
const { title, body, imageUrl } = req.body; | |
await admin.messaging().sendMulticast({ | |
tokens, | |
notification: { | |
title, | |
body, | |
imageUrl, | |
}, | |
}); | |
res.status(200).json({ message: "Successfully sent notifications!" }); | |
} catch (err) { | |
res | |
.status(err.status || 500) | |
.json({ message: err.message || "Something went wrong!" }); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment