📢 Introduction
Push notifications are a great way to engage users, whether it's sending updates, order confirmations, or alerts. This guide will walk you through building a complete push notification system using:
✅ Firebase Cloud Messaging (FCM) for sending web push notifications
✅ React (TypeScript) for handling push notifications in the frontend
✅ Azure Functions (C#) for backend notification processing
✅ Entity Framework Core (EF Core) & SQL Server for logging requests and sent messages
By the end of this guide, your system will:
✅ Send notifications based on events (e.g., order placed)
✅ Track notifications sent & received (great for analytics and debugging)
✅ Handle user interactions when notifications are clicked
📌 Step 1: Setting Up Firebase Cloud Messaging (FCM)
💰 Firebase Pricing (2024)
Firebase provides a free Spark plan and a pay-as-you-go Blaze plan:
| Feature | Spark (Free) | Blaze (Pay-as-you-go) |
|---|---|---|
| Cloud Messaging | Free | Free |
| Monthly Notifications | Unlimited | Unlimited |
| Stored Data | Free up to 1GB | $0.026/GB |
| Outbound Network | Free up to 1GB | $0.12/GB |
💡 For most use cases, Firebase FCM is free unless you're sending millions of notifications!
1️⃣ Create a Firebase Project
- Visit the Firebase Console and create a new project.
- Navigate to Project Settings (gear icon).
- Under General → Your Apps, click Add App → Web App.
- Register your app and save the Firebase configuration details.
2️⃣ Configure Firebase for Web Push
- Go to Project Settings → Cloud Messaging.
- Scroll to Web Configuration and click Generate Key Pair.
- Save your Public VAPID Key (needed in React).
📌 Step 2: Integrating FCM in React (TypeScript)
Why Do We Need This?
We need to:
✅ Request user permission for notifications
✅ Retrieve the FCM token
✅ Handle push notifications when received
1️⃣ Install Firebase SDK
npm install firebase
This installs Firebase libraries needed for messaging.
2️⃣ Create firebase.ts (Firebase Configuration)
import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
const firebaseConfig = { /* Add your Firebase config here */ };
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export { messaging, getToken, onMessage };
This initializes Firebase and enables the FCM messaging service.
3️⃣ Handle User Opt-In (NotificationService.ts)
export const requestNotificationPermission = async (): Promise<string | null> => {
const permission = await Notification.requestPermission();
if (permission !== "granted") return null;
const token = await getToken(messaging, { vapidKey: "YOUR_PUBLIC_VAPID_KEY" });
return token;
};
📌 Why is this important?
- This function asks the user for permission.
- If granted, it retrieves the FCM token needed for push notifications.
4️⃣ Register the Service Worker (firebase-messaging-sw.js)
importScripts("https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging.js");
firebase.initializeApp({ /* Your Firebase Config */ });
const messaging = firebase.messaging();
self.addEventListener("notificationclick", (event) => {
event.notification.close();
clients.openWindow(event.notification.data?.url || "/");
});
📌 What does this do?
- Registers a background worker to handle notifications when the app is closed.
- Listens for clicks on notifications and redirects users to a specific page.
📌 Step 3: Setting Up an Azure Function to Send Notifications
Why Use Azure Functions?
- ✅ Scales automatically (serverless architecture).
- ✅ Event-driven notifications (e.g., send alerts when an order is placed).
- ✅ Works well with Firebase & React.
1️⃣ Install Firebase Admin SDK in C#
dotnet add package FirebaseAdmin
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
📌 Why?
- FirebaseAdmin → Sends push notifications.
- EF Core → Stores logs of sent notifications.
2️⃣ Initialize Firebase in C# (FirebaseService.cs)
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
public static class FirebaseService
{
public static void InitializeFirebase()
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("path/to/service-account.json")
});
}
}
📌 What does this do?
- Initializes Firebase Admin SDK in Azure Functions.
3️⃣ Store Notification Requests & Logs (AppDbContext.cs)
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<NotificationRequest> NotificationRequests { get; set; }
public DbSet<NotificationLog> NotificationLogs { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}
📌 Why track notifications?
- Ensures messages are delivered (retry if failed).
- Tracks notification history for analytics.
- Debugging (e.g., logs missing notifications).
4️⃣ Send Notifications from Azure Queue (NotificationFunction.cs)
[Function("SendNotification")]
public async Task Run([QueueTrigger("notification-queue", Connection = "AzureWebJobsStorage")] string queueItem)
{
var request = JsonConvert.DeserializeObject<NotificationRequest>(queueItem);
var tokens = await GetUserTokens(request.UserId);
var message = new MulticastMessage()
{
Tokens = tokens,
Notification = new Notification { Title = request.Title, Body = request.Message }
};
var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message);
}
📌 Why use Azure Queue?
- Queues notifications to avoid blocking requests.
- Ensures reliability even if Firebase is down.
📌 Step 4: Tracking Notification Clicks & Adding Buttons
Modify Service Worker to Handle Actions
self.addEventListener("notificationclick", (event) => {
event.notification.close();
if (event.action === "reply") {
console.log("User clicked Reply");
} else if (event.action === "view") {
clients.openWindow("https://your-app.com/orders");
}
});
📌 Why add buttons?
- Increases engagement (e.g., quick actions like "View Order").
- Saves user clicks (faster user flow).
📌 Step 5: Deploying to Azure
Deploy the Azure Function
az login
func azure functionapp publish YOUR_FUNCTION_APP_NAME
Deploy React App
npm run build
firebase deploy
🎯 Final Summary
✅ Built a full push notification system using React, Firebase, and Azure.
✅ Stored requests & logs using EF Core.
✅ Tracked user clicks & actions in notifications.
✅ Deployed & automated notifications using Azure Functions.
🔹 Next Steps?
🚀 Send notifications to user segments (e.g., premium users only).
📊 Analyze engagement metrics (track open rates & interactions).
🔥 Now your app is ready to engage users with real-time notifications! 🚀

