본문 바로가기
Node.js

[Node.js] FCM으로 푸시 메시지 전송(단일, 여러개)

by pocket.dev 2024. 8. 21.
반응형

Firebase Cloud Messaging

📌 선행 작업

발급받은 serviceAccountKey.json 파일로 초기 세팅해주기.

import admin from 'firebase-admin';
import serviceAccount from 'path/to/serviceAccountKey.json';

admin.initializeApp({
   credential: admin.credential.cert(serviceAccount)
});

 

 

1. 단일 건 전송

admin.messaging().send() 사용

token 키 값에 푸시 메시지를 보낼 단일 token 값 설정

import admin from 'firebase-admin';

const token = 'token123456789';

const message = {
   token: token,
   data: { key1: 'value1', key2: 'value2' },
    notification: {
      title: 'notification title',
      body: 'notification body content',
    },
    android: {
      priority: 'high',
      ...
    },
    apns: {
      payload: {
        aps: {
          sound: 'default',
          ...
        },
      },
    }
};

await admin.messaging().send(message);

 

2. 여러 건 벌크로 전송

admin.messaging().sendEachForMulticast() 사용

tokens 키 값에 푸시 메시지를 보낼 token 리스트 전달

import admin from 'firebase-admin';

const tokenList = [
   'token111111111',
   'token222222222',
   'token333333333',
   'token444444444',
   'token555555555',
];

const message = {
   tokens: tokenList,
   data: { key1: 'value1', key2: 'value2' },
    notification: {
      title: 'notification title',
      body: 'notification body content',
    },
    android: {
      priority: 'high',
      ...
    },
    apns: {
      payload: {
        aps: {
          sound: 'default',
          ...
        },
      },
    }
};

await admin.messaging().sendEachForMulticast(message);