Spaces:
Running
Running
| import express from "express"; | |
| import bodyParser from "body-parser"; | |
| import admin from "firebase-admin"; | |
| import fs from "fs"; | |
| // Load Firebase service account key | |
| const serviceAccount = JSON.parse( | |
| fs.readFileSync("./serviceAccountKey.json", "utf-8") | |
| ); | |
| admin.initializeApp({ | |
| credential: admin.credential.cert(serviceAccount), | |
| }); | |
| const app = express(); | |
| app.use(bodyParser.json()); | |
| // Send notification to multiple tokens | |
| app.post("/send", async (req, res) => { | |
| try { | |
| const { tokens, title, body, data } = req.body; | |
| if (!tokens || tokens.length === 0) { | |
| return res.status(400).json({ error: "No tokens provided" }); | |
| } | |
| const message = { | |
| notification: { title, body }, | |
| data: data || {}, // custom key-value data | |
| tokens, | |
| }; | |
| const response = await admin.messaging().sendEachForMulticast(message); | |
| res.json({ success: true, response }); | |
| } catch (error) { | |
| console.error("Error sending notification:", error); | |
| res.status(500).json({ error: error.message }); | |
| } | |
| }); | |
| app.listen(3000, () => { | |
| console.log("🚀 FCM Server running on http://localhost:3000"); | |
| }); | |