firebase를 이용하면 간단하게 FCM(firebase cloud messaging)으로 푸시 알림을 전송하는 기능을 만들 수 있다. 현재 진행하고 있는 프로젝트에서 새 댓글이 달리거나, 개인에게 1:1 질문이 올 때 푸시 알림이 전송되도록 했는데 node.js에서 푸시 알림을 어떻게 구현했는지 보여주려 한다.
FCM을 이용해 메세지를 보내려면 몇 가지 준비 과정이 있다.
1) firebase 프로젝트 생성 및 비공개 키 생성
https://console.firebase.google.com/u/0/
firebase 콘솔로 이동해 프로젝트를 생성한다. 프로젝트 이름을 정하고, 계정만 있으면 간단히 만들 수 있다.



키 생성 버튼까지 누르면 json 파일이 다운로드 된다.
2) SDK 설치
npm install firebase-admin --save
3) SDK 초기화
const admin = require("firebase-admin");
const serviceAccount = require("path/to/비공개키.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
푸시 알림 전송하기
푸시 알림을 전송하는 데 있어서 크게 2가지 방법을 사용했는데, 첫 번째 방법은 unicast로 특정 기기에 메세지를 전송하는 방법이고 두 번째 방법은 multicast로 여러 기기에 메세지를 전송하는 방법이다. 관련 내용을 구현하는 데 있어 하단 링크 firebase 공식 문서를 참고했다.
https://firebase.google.com/docs/cloud-messaging/send-message?hl=ko
앱 서버 전송 요청 작성 | Firebase Documentation
의견 보내기 앱 서버 전송 요청 작성 Firebase Admin SDK 또는 FCM 앱 서버 프로토콜을 사용하여 메시지 요청을 작성하고 다음과 같은 타겟 유형으로 전송할 수 있습니다. 주제 이름 조건 기기 등록 토
firebase.google.com
[case1] 특정 기기에 메세지를 전송하는 방법
ex) 새 댓글이 달렸을 때 게시글 작성자 1명에게 알리는 경우
const notificationTitle = "나도선배"; // 앱 이름
const notificationContent = `작성하신 질문글에 ${sender.nickname}님이 답글을 남겼습니다.`; // 전송하고 싶은 알림 내용
const receivertoken = "디바이스 토큰" // 클라이언트 쪽에서 받은 디바이스 토큰
// 메세지 내용
const message = {
notification: {
title: notificationTitle,
body: notificationContent,
},
token: receiverToken,
};
// 메세지 전송
admin
.messaging()
.send(message) // send를 사용하면 unicast로 전송!
.then(function (response) {
console.log('Successfully sent message', response);
})
.catch(function (error) {
console.log('Error sending message', error);
});
[case2] 여러 기기에 메세지를 전송하는 방법
ex) 새 댓글이 달렸을 때 그 게시글에 댓글을 달았던 작성자 여러 명에게 알리는 경우
case1과 다른 점은 message에서 tokens 배열로 받는다는 점과, sendMulticast를 사용한다는 점 2가지 밖에 없고 기본적인 골조는 비슷하다. 성공 및 실패의 경우에 몇 개의 토큰에 알림을 보내는 데 성공/실패했는지 개수를 console.log로 찍을 수 있다. 이 코드에서 실패의 경우는 따로 사용하지 않았고, 성공인 경우 response.successCount로 성공 개수를 확인했다.
const notificationTitle = "나도선배";
const notificationContent = `답글을 작성하신 질문글에 ${sender.nickname}님이 답글을 남겼습니다.`;
const receiverTokens = ["디바이스 토큰1", "디바이스 토큰2", ...]; // 알림을 보낼 각 유저의 디바이스 토큰들
// 메세지 내용
const message = {
notification: {
title: notificationTitle,
body: notificationContent,
},
tokens: receiverTokens,
};
// 메세지 전송
admin
.messaging()
.sendMulticast(message) // sendMulticast를 사용하면 multicast로 전송!
.then(function (response) {
console.log('Successfully sent message', response.successCount);
})
.catch(function (error) {
console.log('Error sending message');
});
}
실제 코드에서는 위의 내용에 추가로 sender는 알림을 받지 않도록 예외 처리(ex. 댓글 작성자가 알림을 받지 않도록), receiver가 여러 명일 때 디바이스 토큰이 중복되지 않도록 (한 사람에게 같은 내용으로 알림이 여러 번 가지 않도록) 하는 에러 처리 등을 추가했다.
