FCM with Web (JavaScript)
Send push notifications to web browsers using Firebase Cloud Messaging and the Web Push API.
Setup
1. Install Firebase
bashnpm install firebase
2. Initialize Firebase
javascriptimport { 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
- Go to Firebase Console → Project settings → Cloud Messaging
- Under "Web configuration," find or generate a Web Push certificate key pair
- Copy the Key pair value (this is your VAPID key)
4. Request Permission and Get Token
Important: FCM requires a
firebase-messaging-sw.jsfile at the root of your domain. Create it (even if empty) before callinggetToken(). 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.
javascriptasync 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
javascriptonMessage(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:
javascriptimportScripts('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 yournode_modules/firebase/package.jsonfor the current version.
Browser Support
| Browser | Support |
|---|---|
| Chrome (Desktop & Android) | ✅ Full support |
| Firefox | ✅ Full support |
| Edge | ✅ Full support |
| Safari 16.4+ | ✅ Supported (macOS & iOS) |
| Safari < 16.4 | ❌ Not supported |
Testing
- Open your web app and copy the FCM token from the console
- Go to the FCM Tester
- Paste your service account JSON and the token
- Send a notification — it should appear as a browser notification
Common Issues
| Issue | Fix |
|---|---|
| Token is null | Check VAPID key and that notification permission is granted |
| No notification in foreground | Foreground messages need manual handling with onMessage() |
| Service worker not found | File must be at the root: public/firebase-messaging-sw.js — create it before calling getToken() |
| Safari not working | Requires Safari 16.4+ and HTTPS |
| "messaging/permission-blocked" | User blocked notifications — they need to re-enable in browser settings |
| Token retrieval fails | Ensure the FCM Registration API is enabled in your Google Cloud project |
Related
Was this page helpful?