Push notifications are one of the best ways to engage users in real-time. In this tutorial, you'll learn how to create a basic push notification system using Node.js and Firebase Cloud Messaging (FCM).
Open your terminal and run these commands:
mkdir push-server cd push-server npm init -y
npm install firebase-admin express body-parser`
Download the serviceAccountKey.json
file from your Firebase project by going to Firebase Console > Project Settings > Service Accounts and generate a new private key. Place this file inside your Node.js project folder.
Create an index.js
file and add this code:
admin.initializeApp({ credential: admin.credential.cert(serviceAccount),
});
app.use(bodyParser.json());
app.post('/send', async (req, res) => { const { token, title, body } = req.body; const message = { notification: { title, body },
token,
}; try { const response = await admin.messaging().send(message);
res.status(200).send({ success: true, response });
} catch (error) {
res.status(500).send({ success: false, error });
}
});
app.listen(port, () => { console.log(`Server running on http://localhost:${port}`);
});
Use a tool like Postman or cURL to send a POST request:
POST http://localhost:3000/send
Content-Type: application/json
{ "token": "YOUR_DEVICE_FCM_TOKEN", "title": "Hello!", "body": "This is a test notification from Node.js!" }
On your frontend (mobile app or web client), use Firebase SDK to request and get a unique device token.
For Web (JavaScript), example code:
import { getMessaging, getToken } from "firebase/messaging"; const messaging = getMessaging(); getToken(messaging, { vapidKey: 'YOUR_PUBLIC_VAPID_KEY' })
.then((currentToken) => { if (currentToken) { console.log("Device Token:", currentToken);
}
});
Never expose your Firebase service account key in frontend code. Keep all push notification logic on your backend server to protect your credentials.
You have built a basic push notification server using Node.js and Firebase! Next steps you might consider:
Pro tip: Combine push notifications with analytics to measure delivery rates and user engagement.
2025-05-16