DEV Community

Mayank Tamrkar
Mayank Tamrkar

Posted on

Simple Push Notification Setup with Firebase in React or Next.js

✅ Step 1: Create a Firebase Project

  1. Go to https://console.firebase.google.com
  2. Click Add project
  3. Give it a name and continue
  4. Once created, go to Project settings
  5. Under Your apps, click </> Web and register your app
  6. Copy the Firebase config — we’ll need it soon
  7. Go to Cloud Messaging tab and copy the Public VAPID key

📁 Step 2: Create Firebase Helper

File: src/utils/firebase.ts

import { initializeApp } from 'firebase/app';
import { getMessaging, getToken } from 'firebase/messaging';

// Replace this with your Firebase config
const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_PROJECT_ID.firebaseapp.com',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_PROJECT_ID.appspot.com',
  messagingSenderId: 'YOUR_SENDER_ID',
  appId: 'YOUR_APP_ID',
};

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

// Get token function
export const requestFcmToken = async (): Promise<string | null> => {
  try {
    const permission = await Notification.requestPermission();
    if (permission !== 'granted') return null;

    const token = await getToken(messaging, {
      vapidKey: 'YOUR_PUBLIC_VAPID_KEY', // from Firebase Cloud Messaging settings
    });

    console.log('✅ FCM Token:', token);
    return token;
  } catch (err) {
    console.error('Error getting FCM token', err);
    return null;
  }
};
Enter fullscreen mode Exit fullscreen mode

📦 Step 3: Create a Custom Hook

File: src/hooks/useFcm.ts

import { useEffect, useState } from 'react';
import { requestFcmToken } from '@/utils/firebase';

const useFcm = () => {
  const [token, setToken] = useState<string | null>(null);

  useEffect(() => {
    const getToken = async () => {
      const fcmToken = await requestFcmToken();
      setToken(fcmToken);
    };

    getToken();
  }, []);

  return token;
};

export default useFcm;
Enter fullscreen mode Exit fullscreen mode

🧩 Step 4: Use the Hook in App

File: src/app/layout.tsx (or _app.tsx in a React app)

'use client';

import useFcm from '@/hooks/useFcm';
import { useEffect } from 'react';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  const token = useFcm();

  useEffect(() => {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/firebase-messaging-sw.js').then(() => {
        console.log('✅ Service worker registered');
      });
    }
  }, []);

  return (
    <html>
      <body>{children}</body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

📄 Step 5: Create Service Worker File

File: public/firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/10.8.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.8.1/firebase-messaging-compat.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_SENDER_ID',
  appId: 'YOUR_APP_ID',
});

const messaging = firebase.messaging();

self.addEventListener('push', function (event) {
  const data = event.data?.json();
  self.registration.showNotification(data?.notification?.title || 'Notification', {
    body: data?.notification?.body || '',
  });
});
Enter fullscreen mode Exit fullscreen mode

🏁 You're Done!

Now your app will:

  • Ask for notification permission
  • Get an FCM token
  • Register the service worker
  • Show background notifications

Let me know if you want a version with token refresh or API integration later!

Top comments (0)