firebase notif

Step 3 : Request Notification Permission

// src/requestPermission.js
import { messaging } from './firebase';

export const requestPermission = async () => {
  try {
    await messaging.requestPermission();
    const token = await messaging.getToken();
    console.log('User token:', token);
    // Save the token to your backend database if needed
  } catch (error) {
    console.error('Permission denied', error);
  }
};



STep 4 : Handle Incoming Messages

// src/firebase-messaging-sw.js (Service Worker)
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.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(function(payload) {
  console.log('Received background message ', payload);
  // Customize notification here
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});


Step 5 : Integrate with React Components
// src/App.js
import React, { useEffect } from 'react';
import { requestPermission } from './requestPermission';

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

  return (
    <div className="App">
      <header className="App-header">
        <p>Firebase Notifications with React</p>
      </header>
    </div>
  );
}

export default App;


Step 6 : Register the Service Worker
// public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React App</title>
</head>
<body>
  <div id="root"></div>
  <script src="%PUBLIC_URL%/firebase-messaging-sw.js"></script>
</body>
</html>