Day 6: Implementing Push Notifications for Your PWA


Today, you’ll learn how to implement push notifications in your Progressive Web App (PWA) using the Notifications API and Firebase Cloud Messaging (FCM). Push notifications allow your app to engage users with timely information even when they are not actively using the app.

What You Will Do Today:

  1. Set up Firebase Cloud Messaging for push notifications.
  2. Request notification permissions from users.
  3. Register the service worker for push notifications.
  4. Send and receive notifications from Firebase.

Step 1: Setting Up Firebase Cloud Messaging (FCM)

  1. Go to the Firebase Console and create a new project or open an existing one.
  2. In your Firebase project, go to Project Settings > Cloud Messaging.
  3. Note down the Server Key and Sender ID for use in your app.
  4. Download the firebase-messaging-sw.js file to configure the service worker.

Step 2: Adding Firebase to Your Project

  1. Install the Firebase package:
   npm install firebase
  1. In the src folder, create a file called firebaseConfig.js to initialize Firebase:
   // src/firebaseConfig.js
   import { initializeApp } from 'firebase/app';
   import { getMessaging, getToken, onMessage } from 'firebase/messaging';

   const firebaseConfig = {
     apiKey: "YOUR_API_KEY",
     authDomain: "YOUR_AUTH_DOMAIN",
     projectId: "YOUR_PROJECT_ID",
     storageBucket: "YOUR_STORAGE_BUCKET",
     messagingSenderId: "YOUR_SENDER_ID",
     appId: "YOUR_APP_ID",
   };

   const app = initializeApp(firebaseConfig);
   const messaging = getMessaging(app);

   export { messaging, getToken, onMessage };
  1. Replace "YOUR_API_KEY", "YOUR_AUTH_DOMAIN", etc., with the values from your Firebase project settings.
See also  Day 9: Implementing In-App Purchases in React Native

Step 3: Requesting Notification Permissions

  1. Create a new file called NotificationService.js to handle permission requests and token generation:
   // src/NotificationService.js
   import { messaging, getToken } from './firebaseConfig';

   export const requestNotificationPermission = async () => {
     try {
       const permission = await Notification.requestPermission();
       if (permission === 'granted') {
         console.log('Notification permission granted.');
         const token = await getToken(messaging, { vapidKey: "YOUR_PUBLIC_VAPID_KEY" });
         console.log('Firebase token:', token);
         return token;
       } else {
         console.log('Notification permission denied.');
       }
     } catch (error) {
       console.error('Error getting permission or token:', error);
     }
   };
  1. Replace "YOUR_PUBLIC_VAPID_KEY" with your Firebase Cloud Messaging VAPID key found in Project Settings > Cloud Messaging.

Step 4: Registering the Service Worker for Push Notifications

  1. In the public folder, create a file called firebase-messaging-sw.js for the service worker:
   // public/firebase-messaging-sw.js
   importScripts('https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js');
   importScripts('https://www.gstatic.com/firebasejs/9.6.7/firebase-messaging.js');

   firebase.initializeApp({
     apiKey: "YOUR_API_KEY",
     authDomain: "YOUR_AUTH_DOMAIN",
     projectId: "YOUR_PROJECT_ID",
     storageBucket: "YOUR_STORAGE_BUCKET",
     messagingSenderId: "YOUR_SENDER_ID",
     appId: "YOUR_APP_ID",
   });

   const messaging = firebase.messaging();

   messaging.onBackgroundMessage((payload) => {
     console.log('Received background message:', payload);
     const notificationTitle = payload.notification.title;
     const notificationOptions = {
       body: payload.notification.body,
       icon: '/icon-192x192.png'
     };
     self.registration.showNotification(notificationTitle, notificationOptions);
   });
  1. Replace "YOUR_API_KEY", "YOUR_AUTH_DOMAIN", etc., with your Firebase project settings.
  2. In public/index.html, register the new service worker by adding this at the end of the <head> tag:
   <script>
     if ('serviceWorker' in navigator) {
       navigator.serviceWorker.register('/firebase-messaging-sw.js')
         .then((registration) => {
           console.log('Service Worker registered for Firebase Messaging:', registration);
         })
         .catch((error) => {
           console.error('Service Worker registration failed:', error);
         });
     }
   </script>

Step 5: Handling Foreground Notifications

  1. In NotificationService.js, add a function to listen for foreground notifications:
   import { onMessage } from './firebaseConfig';

   export const onForegroundNotification = () => {
     onMessage(messaging, (payload) => {
       console.log('Received foreground message:', payload);
       alert(`Notification: ${payload.notification.title} - ${payload.notification.body}`);
     });
   };
  1. Call onForegroundNotification in your main component (e.g., App.js) to handle notifications when the app is in the foreground.
   import React, { useEffect } from 'react';
   import { requestNotificationPermission, onForegroundNotification } from './NotificationService';

   function App() {
     useEffect(() => {
       requestNotificationPermission();
       onForegroundNotification();
     }, []);

     return (
       <div>
         <h1>My PWA with Push Notifications</h1>
         <p>Check your notifications for updates!</p>
       </div>
     );
   }

   export default App;

Step 6: Testing Push Notifications

  1. Go to Firebase Console > Cloud Messaging.
  2. Create a new notification by clicking Send your first message.
  3. Fill out the message details, targeting your specific app.
  4. Under Target, choose User segment or Single device and enter the device token.
  5. Click Send message to test. You should see the notification on your device or in your browser.
See also  Day 7: Securing Your App with Firebase Rules and Authentication

Summary

Today, you implemented push notifications in your PWA using Firebase Cloud Messaging, allowing your app to send and receive notifications in both the foreground and background.

Tomorrow, you’ll learn about testing and optimizing for different screen sizes to make your PWA responsive.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.