✅ Step 1: Create a Firebase Project
- Go to https://console.firebase.google.com
- Click Add project
- Give it a name and continue
- Once created, go to Project settings
- Under Your apps, click </> Web and register your app
- Copy the Firebase config — we’ll need it soon
- 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;
}
};
📦 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;
🧩 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>
);
}
📄 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 || '',
});
});
🏁 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)