In the rapidly evolving world of web development, keeping up with the latest tools and technologies is essential. By 2026, Firebase Cloud Messaging (FCM) has become the go-to solution for delivering web push notifications. This guide will walk you through the process of integrating FCM using the latest modular SDK version 10 and Vue 3.
Setting Up Your Project
Start by installing the Firebase SDK:
pnpm add firebase
# Or: npm install firebase
Next, create a configuration file at src/lib/firebase.ts to initialize Firebase:
const firebaseConfig = {
apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_FIREBASE_APP_ID,
};
export const app = initializeApp(firebaseConfig);
export const messaging = getMessaging(app);
Ensure all sensitive credentials are stored in .env.local to maintain security.
Obtain a VAPID Key
To enable web push notifications, navigate to the Firebase Console, select your project settings, and under the Cloud Messaging section, generate a key pair. Save the public key as VITE_FIREBASE_VAPID_KEY for later use.
Request Permission and Retrieve FCM Token
Create a Vue 3 composable at src/composables/usePushNotifications.ts to manage notification permissions and tokens:
export function usePushNotifications() {
const token = ref<string | null>(null);
const notification = ref<MessagePayload | null>(null);
const error = ref<string | null>(null);
async function requestPermissionAndGetToken() {
try {
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
error.value = 'Notification permission denied';
return;
}
const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js');
token.value = await getToken(messaging, {
vapidKey: import.meta.env.VITE_FIREBASE_VAPID_KEY,
serviceWorkerRegistration: registration,
});
console.log('FCM token:', token.value);
// Store the token on your backend
} catch (err) {
error.value = err instanceof Error ? err.message : 'Unknown error';
}
}
function listenForMessages() {
onMessage(messaging, (payload) => {
console.log('Foreground message received:', payload);
notification.value = payload;
});
}
return { token, notification, error, requestPermissionAndGetToken, listenForMessages };
}
Incorporate this composable in your Vue component to enable notifications and handle messages.
Configure the Service Worker
Create a service worker at public/firebase-messaging-sw.js:
import {
getMessaging,
onBackgroundMessage,
} from 'https://www.gstatic.com/firebasejs/10.12.0/firebase-messaging-sw.js';
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
onBackgroundMessage(messaging, (payload) => {
console.log('Background message received:', payload);
const { title = 'New message', body = '' } = payload.notification ?? {};
self.registration.showNotification(title, {
body,
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: payload.data,
});
});
Note: Service workers cannot access Vite environment variables, so ensure Firebase configuration is directly included.
Sending Notifications from the Backend
Using the Firebase Admin SDK, you can send notifications from your server. Install the SDK:
npm install firebase-admin
Create a script at server/send-notification.ts:
initializeApp({
credential: cert('./service-account.json'),
});
const messaging = getMessaging();
async function sendPushToUser(fcmToken: string) {
const messageId = await messaging.send({
token: fcmToken,
notification: {
title: 'Your order shipped! 📦',
body: 'Estimated delivery: tomorrow between 2–5 PM',
},
webpush: {
fcmOptions: {
link: 'https://yourapp.com/orders',
},
},
});
console.log('Sent message:', messageId);
}
For targeting multiple users, use messaging.sendEachForMulticast() with an array of tokens.
Update Your Web App Manifest
Ensure your web app manifest includes the FCM sender ID:
{
"name": "My App",
"gcm_sender_id": "YOUR_MESSAGING_SENDER_ID"
}
Summary
Here's a quick recap of the setup:
- initializeApp(): Connects to your Firebase project.
- Notification.requestPermission(): Prompts the browser permission dialog.
- getToken(messaging, { vapidKey }): Retrieves the FCM registration token.
- onMessage(): Handles notifications when the app tab is open.
- firebase-messaging-sw.js: Manages notifications when the app is closed or in the background.
- messaging.send() (Admin SDK): Sends notifications from your server.
The token obtained through getToken() should be stored for each user and refreshed on subsequent app visits.