Vue로 PWA 개발 - 그랜파 개발자
마이로그를 저장하면 구독자에게 알림을 보내려고 합니다. FCM(Firebase Cloud Messaging)을 이용하면 구독자에게 알림을 보낼 수 있습니다. FCM 서비스를 구현합니다.
To implement Firebase Cloud Messaging (FCM) service in Firebase v9 (modular SDK), you'll follow a structured process for integrating push notifications in a web application. Here's a step-by-step guide on how to achieve this in a Vue.js application or any web app.
Firebase v9(모듈형 SDK) 에서 Firebase 클라우드 메시징(FCM) 서비스를 구현하려면 웹 애플리케이션에 푸시 알림을 통합하기 위한 구조화된 프로세스를 따라야 합니다. Vue.js 애플리케이션이나 웹 앱에서 이를 달성하는 방법에 대한 단계별 가이드는 다음과 같습니다.
Set Up Firebase in Your Web App
웹 앱에서 Firebase 설정
Configure FCM
FCM 구성
Get Permission for Notifications
알림 권한 받기
Retrieve the FCM Token
FCM 토큰 검색
Handle Incoming Messages
수신 메시지 처리
Send Notifications (From Server)
알림 보내기(서버에서)
Ensure you have Firebase set up in your project. If you haven't installed the Firebase SDK yet, you can install it using npm:
프로젝트에 Firebase가 설정되어 있는지 확인하세요. 아직 Firebase SDK를 설치하지 않았다면 npm을 사용하여 설치할 수 있습니다.
npm install firebase
Create or update your firebase.js file for Firebase configuration:
Firebase 구성을 위한 firebase.js 파일을 만들거나 업데이트합니다
// firebase.js
import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
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",
};
// Initialize Firebase app
const app = initializeApp(firebaseConfig);
// Initialize Firebase Cloud Messaging
const messaging = getMessaging(app);
export { messaging };
To use Firebase Cloud Messaging, you'll need to:
Firebase 클라우드 메시징을 사용하려면 다음을 수행해야 합니다.
You need to request the user’s permission to send notifications:
알림을 보내려면 사용자의 권한을 요청해야 합니다.
// requestPermission.js
import { messaging } from './firebase';
import { getToken } from "firebase/messaging";
export const requestNotificationPermission = async () => {
try {
const permission = await Notification.requestPermission();
if (permission === "granted") {
console.log("Notification permission granted.");
const token = await getFCMToken();
console.log("FCM Token: ", token);
} else {
console.log("Unable to get permission to notify.");
}
} catch (error) {
console.error("An error occurred while requesting notification permission", error);
}
};
// Get FCM token
const getFCMToken = async () => {
try {
const token = await getToken(messaging, { vapidKey: "YOUR_VAPID_KEY" });
if (token) {
console.log("Token retrieved successfully:", token);
// You can send the token to your server to save it
return token;
} else {
console.log("No registration token available. Request permission to generate one.");
}
} catch (error) {
console.error("An error occurred while retrieving token", error);
}
};
To handle incoming messages when the user is currently on the web page, you can listen for them using the onMessage method from the FCM SDK:
사용자가 현재 웹페이지에 있을 때 들어오는 메시지를 처리하려면 FCM SDK의 'onMessage' 메서드를 사용하여 해당 메시지를 수신할 수 있습니다.
import { onMessage } from "firebase/messaging";
import { messaging } from './firebase';
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// Customize notification handling here
});
To handle notifications when the app is in the background, you need a service worker. Create a firebase-messaging-sw.js file in your project’s root directory (where index.html is located):
앱이 백그라운드에 있을 때 알림을 처리하려면 서비스 워커가 필요합니다. 프로젝트의 루트 디렉터리(index.html이 있는 위치)에 firebase-messaging-sw.js 파일을 만듭니다.
// firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js');
// Your web app's Firebase configuration (same as in your firebase.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",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: '/firebase-logo.png', // Optional
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
To send a notification, you will need to make a request to the FCM server with the user's FCM token. You can use Firebase Cloud Functions, your backend server, or Firebase Admin SDK to send notifications.
Here’s an example using Firebase Admin SDK:
알림을 보내려면 사용자의 FCM 토큰을 사용하여 FCM 서버에 요청해야 합니다. Firebase Cloud Functions, 백엔드 서버 또는 Firebase Admin SDK를 사용하여 알림을 보낼 수 있습니다.
Firebase Admin SDK를 사용하는 예는 다음과 같습니다.
const admin = require("firebase-admin");
// Initialize the Firebase Admin SDK
admin.initializeApp({
credential: admin.credential.cert("path/to/serviceAccountKey.json"),
databaseURL: "https://your-project-id.firebaseio.com"
});
// Send notification
const sendNotification = async (token, payload) => {
try {
const response = await admin.messaging().sendToDevice(token, payload);
console.log("Notification sent successfully:", response);
} catch (error) {
console.error("Error sending notification:", error);
}
};
// Example usage
const token = "user_fcm_token_here";
const payload = {
notification: {
title: "New Post",
body: "A new post has been added to your subscriptions.",
},
};
sendNotification(token, payload);
To use FCM with web push notifications, you'll need to configure a VAPID key:
웹 푸시 알림과 함께 FCM을 사용하려면 VAPID 키를 구성해야 합니다.
Go to the Firebase Console.
Firebase 콘솔로 이동합니다.
Navigate to Project Settings > Cloud Messaging.
프로젝트 설정 > 클라우드 메시징으로 이동합니다.
Generate or use an existing Web Push certificate key (VAPID key).
기존 웹 푸시 인증서 키(VAPID 키) 를 생성하거나 사용합니다.
Add this key to your web app, where getToken() is called.
'getToken()'이 호출되는 웹 앱에 이 키를 추가하세요.
In your getFCMToken function, make sure to provide the vapidKey option:
getFCMToken 함수에서 vapidKey 옵션을 제공해야 합니다.
const token = await getToken(messaging, { vapidKey: "YOUR_VAPID_KEY" });
Here’s an example of a notification payload:
알림 페이로드의 예는 다음과 같습니다.
{
"notification": {
"title": "New Article Posted",
"body": "Check out the latest article by your favorite author!",
"click_action": "https://your-app-url.com"
},
"data": {
"extraInfo": "Some additional data"
}
}
You have now successfully integrated Firebase Cloud Messaging with Firebase v9 in a web app. You can send notifications from your backend or Firebase Cloud Functions, handle foreground notifications, and receive push notifications in the background via a service worker.
Make sure you test the entire flow to verify that push notifications work both when the app is in the foreground and background.
이제 웹 앱에서 Firebase 클라우드 메시징을 Firebase v9와 성공적으로 통합했습니다. 백엔드 또는 Firebase Cloud Functions에서 알림을 보내고, 포그라운드 알림을 처리하고, 서비스 워커를 통해 백그라운드에서 푸시 알림을 받을 수 있습니다.
앱이 포그라운드와 백그라운드에 있을 때 푸시 알림이 모두 작동하는지 확인하려면 전체 흐름을 테스트해야 합니다.