๐ข 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! ๐
Top comments (0)