FCMDebug logoFCMDebug

FCM with Web (JavaScript)

Send push notifications to web browsers using Firebase Cloud Messaging and the Web Push API.

Setup

1. Install Firebase

bash
npm install firebase

2. Initialize Firebase

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

const firebaseConfig = {
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  messagingSenderId: "...",
  appId: "..."
};

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

3. Get VAPID Key

  1. Go to Firebase Console → Project settings → Cloud Messaging
  2. Under "Web configuration," find or generate a Web Push certificate key pair
  3. Copy the Key pair value (this is your VAPID key)

4. Request Permission and Get Token

Important: FCM requires a firebase-messaging-sw.js file at the root of your domain. Create it (even if empty) before calling getToken(). See Step 6 below.

Note: If you're using Firebase JS SDK 6.7.0 or later, make sure the FCM Registration API is enabled in your Google Cloud Console. New projects have this enabled by default.

javascript
async function requestNotificationPermission() {
  const permission = await Notification.requestPermission();
  
  if (permission === 'granted') {
    const token = await getToken(messaging, {
      vapidKey: 'YOUR_VAPID_KEY_HERE'
    });
    console.log('FCM Token:', token);
    return token;
  }
  
  console.log('Notification permission denied');
  return null;
}

5. Handle Foreground Messages

javascript
onMessage(messaging, (payload) => {
  console.log('Foreground message:', payload);
  
  // Show a custom notification
  new Notification(payload.notification.title, {
    body: payload.notification.body,
    icon: '/icon.png'
  });
});

6. Create a Service Worker

Create public/firebase-messaging-sw.js:

javascript
importScripts('https://www.gstatic.com/firebasejs/12.11.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/12.11.0/firebase-messaging-compat.js');

firebase.initializeApp({
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  messagingSenderId: "...",
  appId: "..."
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  console.log('Background message:', payload);
  
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: '/icon.png'
  };

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

Keep versions in sync: The Firebase version in the service worker (importScripts) should match the version you installed via npm. Check your node_modules/firebase/package.json for the current version.

Browser Support

BrowserSupport
Chrome (Desktop & Android)✅ Full support
Firefox✅ Full support
Edge✅ Full support
Safari 16.4+✅ Supported (macOS & iOS)
Safari < 16.4❌ Not supported

Testing

  1. Open your web app and copy the FCM token from the console
  2. Go to the FCM Tester
  3. Paste your service account JSON and the token
  4. Send a notification — it should appear as a browser notification

Common Issues

IssueFix
Token is nullCheck VAPID key and that notification permission is granted
No notification in foregroundForeground messages need manual handling with onMessage()
Service worker not foundFile must be at the root: public/firebase-messaging-sw.js — create it before calling getToken()
Safari not workingRequires Safari 16.4+ and HTTPS
"messaging/permission-blocked"User blocked notifications — they need to re-enable in browser settings
Token retrieval failsEnsure the FCM Registration API is enabled in your Google Cloud project

Related

Was this page helpful?