How to Use Push Notifications in React: A Step-by-Step Guide

ajayupreti

ajay upreti

Posted on September 22, 2023

How to Use Push Notifications in React: A Step-by-Step Guide

Introduction:

Push notifications have become a ubiquitous part of our digital lives. They keep us informed, engaged, and connected with our favorite apps and websites. If you're building a React application and want to implement push notifications, you're in the right place. In this tutorial, we will walk you through the process of adding push notification functionality to your React app. We will use a service worker, the Notifications API, and a popular library called Firebase Cloud Messaging (FCM) to achieve this. By the end of this guide, you'll have a React app that can send and receive push notifications.

Prerequisites:

Before we get started, make sure you have the following prerequisites in place:

Basic knowledge of React and JavaScript.
Node.js and npm (Node Package Manager) installed on your development machine.
A code editor of your choice (e.g., Visual Studio Code).
Let's dive in!

Step 1: Create a New React App

If you don't have a React app already, create one using Create React App (CRA). Open your terminal and run the following command:

npx create-react-app push-notification-app
// Replace "push-notification-app" with your preferred project name.
Enter fullscreen mode Exit fullscreen mode

Step 2: Register a Service Worker

Service workers are a fundamental part of enabling push notifications in web applications. They run in the background and can intercept network requests, making them suitable for handling push notifications.

In your React app's src folder, create a new file named service-worker.js. Add the following code to it:

// service-worker.js
self.addEventListener('push', event => {
  const options = {
    body: event.data.text(),
    icon: '/path/to/your/icon.png', // Replace with your icon path
  };
  event.waitUntil(
    self.registration.showNotification('Your App Name', options)
  );
});
Enter fullscreen mode Exit fullscreen mode

This code sets up a basic service worker that listens for incoming push notifications and displays them with a title and icon.

Step 3: Register the Service Worker

In your src/index.js file, register the service worker by adding the following code:

// src/index.js
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(registration => {
      console.log('Service Worker registered with scope:', registration.scope);
    })
    .catch(error => {
      console.error('Service Worker registration failed:', error);
    });
}
Enter fullscreen mode Exit fullscreen mode

This code checks if the browser supports service workers and registers the service worker file we created earlier.

Step 4: Set Up Firebase Cloud Messaging (FCM)

To send and receive push notifications, we'll use Firebase Cloud Messaging (FCM). Follow these steps to set up FCM:

Create a Firebase project at https://console.firebase.google.com/.

In your Firebase project, go to "Project settings" > "Cloud Messaging."

Copy the "Sender ID" and "Server key" values. You'll need them later.

Step 5: Install Firebase and Configure FCM

In your React app's root directory, install the Firebase package by running:

npm install firebase
Enter fullscreen mode Exit fullscreen mode

Now, create a Firebase configuration file. In your src folder, create a file named firebase.js and add the following code:

// src/firebase.js
import firebase from 'firebase/app';
import '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',
};

firebase.initializeApp(firebaseConfig);

export const messaging = firebase.messaging();
Enter fullscreen mode Exit fullscreen mode

Replace the placeholder values in firebaseConfig with the actual values from your Firebase project.

Step 6: Request Permission and Get the Registration Token

In your React app, you'll need to request permission from the user to send notifications and obtain a registration token. You can do this in a React component like so:

import React, { useEffect } from 'react';
import { messaging } from './firebase';

const PushNotificationButton = () => {
  useEffect(() => {
    messaging.requestPermission()
      .then(() => {
        return messaging.getToken();
      })
      .then(token => {
        console.log('Token:', token);
      })
      .catch(error => {
        console.error('Error:', error);
      });
  }, []);

  return (
    <button>Enable Push Notifications</button>
  );
};

export default PushNotificationButton;
Enter fullscreen mode Exit fullscreen mode

This component requests permission and logs the registration token to the console. You can customize it to display a user-friendly message and handle different permission scenarios.

Step 7: Send Push Notifications

With the registration token obtained in the previous step, you can now send push notifications from your server or Firebase Cloud Messaging console.

For example, you can use the Firebase Admin SDK on your server to send notifications to specific devices using their registration tokens.

const admin = require('firebase-admin');
const serviceAccount = require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

const message = {
  data: {
    title: 'New Notification',
    body: 'This is a push notification from your server.',
  },
  token: 'DEVICE_REGISTRATION_TOKEN',
};

admin.messaging().send(message)
  .then(response => {
    console.log('Successfully sent message:', response);
  })
  .catch(error => {
    console.error('Error sending message:', error);
  });
Enter fullscreen mode Exit fullscreen mode

Replace 'DEVICE_REGISTRATION_TOKEN' with the actual registration token of the target device.

Step 8: Display Push Notifications in Your Service Worker

To display push notifications received from FCM in your service worker, modify the service worker code you created in Step 2. Update the self.addEventListener('push', event => { ... }) block to customize the notification's appearance and behavior.

self.addEventListener('push', event => {
  const data = event.data.json(); // Assuming the payload is in JSON format

  const options = {
    body: data.body,
    icon: '/path/to/your/icon.png',
    data: {
      url: data.link, // Customize the link to open when the notification is clicked
    },
  };

  event.waitUntil(
    self.registration.showNotification(data.title, options)
  );
});
Enter fullscreen mode Exit fullscreen mode

Step 9: Handle Notification Clicks

To handle clicks on push notifications and navigate to a specific URL when a notification is clicked, add the following code to your service worker:

self.addEventListener('notificationclick', event => {
  const notificationData = event.notification.data;

  if (notificationData.url) {
    clients.openWindow(notificationData.url);
  }

  event.notification.close();
});
Enter fullscreen mode Exit fullscreen mode

This code listens for the notificationclick event, extracts the URL from the notification data, and opens the URL in a new browser tab when the notification is clicked.

Step 10: Test Your Push Notifications

Finally, it's time to test your push notifications. Run your React app locally and use the "Enable Push Notifications" button you created earlier to obtain a registration token.

Happy coding!

💖 💪 🙅 🚩
ajayupreti
ajay upreti

Posted on September 22, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related