Forem

Champ of Greatness
Champ of Greatness

Posted on

๐Ÿš€Building a Scalable Push Notification Service with Firebase, Azure Functions, and React

๐Ÿ“ข 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

  1. Visit the Firebase Console and create a new project.
  2. Navigate to Project Settings (gear icon).
  3. Under General โ†’ Your Apps, click Add App โ†’ Web App.
  4. Register your app and save the Firebase configuration details.

2๏ธโƒฃ Configure Firebase for Web Push

  1. Go to Project Settings โ†’ Cloud Messaging.
  2. Scroll to Web Configuration and click Generate Key Pair.
  3. 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
Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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 || "/");
});
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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")
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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) { }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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);
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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");
    }
});
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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
Enter fullscreen mode Exit fullscreen mode

Deploy React App

npm run build
firebase deploy
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ 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)