DEV Community

Cover image for 🌟 Comprehensive Guide to Firebase Cloud Messaging in React with Vite πŸš€
Harsh Shah
Harsh Shah

Posted on

🌟 Comprehensive Guide to Firebase Cloud Messaging in React with Vite πŸš€

Firebase Cloud Messaging (FCM) is a powerful tool for sending notifications and messages to your users, keeping them engaged and informed. This guide will take you through the process of setting up FCM in your React application using Vite, and we'll also cover how to obtain the necessary FCM keys to test notifications. Let's get started! πŸŽ‰

Table of Contents πŸ“‘

  1. Introduction to Firebase Cloud Messaging
  2. Creating a Firebase Project πŸ”₯
  3. Setting Up a Vite + React Project πŸ› οΈ
  4. Integrating Firebase in React πŸ“²
  5. Obtaining FCM Key in React πŸ”‘
  6. Sending Notifications with FCM πŸ“§
  7. Receiving Notifications in React πŸ“₯
  8. Best Practices and Security πŸ›‘οΈ
  9. Troubleshooting and Common Issues 🐞
  10. Conclusion πŸŽ‰

Introduction to Firebase Cloud Messaging

Firebase Cloud Messaging allows you to send notifications and messages across platforms like Android, iOS, and the web. It’s an effective way to keep users engaged with timely updates and notifications. πŸš€

Creating a Firebase Project πŸ”₯

  1. Visit Firebase Console: Go to the Firebase Console.
  2. Create a New Project: Click "Add project" and follow the prompts to create a new project. 🎯
  3. Enable Cloud Messaging: In Project Settings > Cloud Messaging, ensure Cloud Messaging is enabled. πŸ“¬
  4. Add a Web App: Register your web app in the Firebase console and note the configuration details provided.

Setting Up a Vite + React Project πŸ› οΈ

Vite is a modern build tool that enhances the development experience. Here’s how to set up a Vite + React project:

  1. Create a Vite Project: Open your terminal and run:
   npm create vite@latest my-fcm-app -- --template react
   cd my-fcm-app
   npm install
Enter fullscreen mode Exit fullscreen mode
  1. Start the Development Server: Run:
   npm run dev
Enter fullscreen mode Exit fullscreen mode

This starts a development server and opens your React app in the browser. πŸŽ‰

Integrating Firebase in React πŸ“²

Installing Firebase SDK πŸ“¦

First, install the Firebase SDK:

npm install firebase
Enter fullscreen mode Exit fullscreen mode

Configuring Firebase in React βš™οΈ

Create a firebase.js file in the src directory:

// src/firebase.js
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging";

const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID",
};

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

export { messaging };
Enter fullscreen mode Exit fullscreen mode

Replace placeholders with your Firebase configuration values. 🧩

Requesting Notification Permissions 🚦

Create a Notification.js component to request notification permissions:

// src/Notification.jsx
import React, { useEffect } from 'react';
import { messaging } from './firebase';
import { getToken } from "firebase/messaging";

const Notification = () => {
    useEffect(() => {
        const requestPermission = async () => {
            try {
                const token = await getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' });
                if (token) {
                    console.log('Token generated:', token);
                    // Send this token to your server to store it for later use
                } else {
                    console.log('No registration token available.');
                }
            } catch (err) {
                console.error('Error getting token:', err);
            }
        };

        requestPermission();
    }, []);

    return <div>Notification Setup πŸš€</div>;
};

export default Notification;
Enter fullscreen mode Exit fullscreen mode

Replace 'YOUR_VAPID_KEY' with your VAPID key from the Firebase console. πŸ”‘

Handling Token Generation πŸ”‘

Ensure the token is securely sent to your server for later use:

// src/Notification.jsx
if (token) {
    console.log('Token generated:', token);
    fetch('/save-token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ token }),
    });
}
Enter fullscreen mode Exit fullscreen mode

Obtaining FCM Key in React πŸ”‘

To test notifications, you need the FCM key, also known as the Server Key. Here’s how to obtain it:

1. Access Firebase Console

  1. Go to the Firebase Console.
  2. Log in with your Google account and select your project.

2. Navigate to Project Settings

  1. Click on the gear icon βš™οΈ next to "Project Overview" in the left-hand menu.
  2. Select "Project settings" from the dropdown menu.

3. Find Cloud Messaging Settings

  1. Click on the Cloud Messaging tab.
  2. Under the "Project credentials" section, locate the Server key.
  3. Copy the Server key to use it for testing.

Using FCM Key in React

Store this key securely and use it for testing notifications in your React application.

Sending Notifications with FCM πŸ“§

Using Firebase Console πŸ–₯️

  1. Go to Cloud Messaging: In the Firebase Console, navigate to Cloud Messaging.
  2. Compose a Message: Click "Send your first message" and fill in the details.
  3. Target Users: Choose your web app and specify the users or topics.
  4. Send the Message: Click "Send message." πŸš€

Sending Notifications Programmatically πŸ’»

To send notifications programmatically, use the Firebase Admin SDK:

// Example with Node.js
const admin = require('firebase-admin');
admin.initializeApp({
    credential: admin.credential.applicationDefault(),
});

const message = {
    notification: {
        title: 'Hello!',
        body: 'You have a new message.',
    },
    token: 'DEVICE_REGISTRATION_TOKEN',
};

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

Replace 'DEVICE_REGISTRATION_TOKEN' with the token you received in your React app. πŸ”„

Receiving Notifications in React πŸ“₯

Handling Foreground Notifications 🌐

Listen for notifications while the app is open using onMessage:

// src/Notification.jsx
import { onMessage } from "firebase/messaging";

useEffect(() => {
    const unsubscribe = onMessage(messaging, (payload) => {
        console.log('Message received. ', payload);
        // Customize notification display here
    });

    return () => {
        unsubscribe();
    };
}, []);
Enter fullscreen mode Exit fullscreen mode

Handling Background Notifications πŸ•ΆοΈ

Create firebase-messaging-sw.js in the public folder:

// public/firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');

firebase.initializeApp({
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID",
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
    console.log('Received background message ', payload);
    // Customize notification here
});
Enter fullscreen mode Exit fullscreen mode

Register the service worker in main.jsx:

// src/main.jsx
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/firebase-messaging-sw.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

Best Practices and Security πŸ›‘οΈ

  1. Secure Your Tokens: Ensure messaging tokens are securely transmitted and stored.
  2. Handle Permissions Wisely: Clearly communicate why you need notification permissions to build trust.
  3. Optimize Notification Delivery: Avoid spamming users with irrelevant notifications. Target notifications for relevance and timeliness. πŸ“†

Troubleshooting and Common Issues 🐞

  1. Token Issues: Ensure the Firebase configuration is correct and you are using the correct VAPID key.
  2. Service Worker Issues: Make sure firebase-messaging-sw.js is correctly located in the public directory.
  3. No Notifications: Verify notification permissions and check if they are blocked by the browser or OS.

Debugging the MIME Type Error

  • Error Explanation: The error indicates the service worker file firebase-messaging-sw.js is served as text/html, indicating a 404 error.
  • Solution Steps:
    • Ensure the file exists in the public directory.
    • Check the path and file name in your registration code.
    • Verify access to the file in your browser.

Conclusion πŸŽ‰

Integrating Firebase Cloud Messaging with your Vite-powered React application allows you to engage users with notifications. By following this guide, you can set up and test notifications effectively. Happy coding! πŸ“²πŸš€


Ready to notify? Dive in and make sure your app keeps users informed and engaged! πŸ’¬πŸ“²

Top comments (0)