Firebase 및 React로 푸시 알림을 보내는 방법

푸시 알림은 앱 참여를 향상시킵니다. Firebase는 Firebase 클라우드 메시징 서비스를 사용하여 보낼 수 있는 방법을 제공합니다. React 앱에 통합하는 방법을 보여 드리겠습니다.

우리가 구축하는 것





전체 코드를 가져옵니다here.

Firebase 프로젝트 만들기


  • Firebase Console에서 프로젝트 추가









  • setup firebase project step 5
  • Firebase 프로젝트에 웹 앱 추가

  • setup firebase project step 6


  • 누르기 Continue to console

  • React 앱에 Firebase 추가


  • Firebase CLI 설치

  • npm i -g firebase-tools
    


  • Clone React 앱 튜토리얼 스타터

  • npx degit https://github.com/jeremytenjo/starter-demo.git firebase-messaging-with-react && cd firebase-messaging-with-react && npm i && npm run dev
    


  • 종속성 설치

  • npm i firebase @useweb/use-firebase-messaging @useweb/use-firebase
    


  • 앱에서 Firebase 설정

  • firebase init hosting
    


  • 클릭 Use an existing project
  • 클릭 tut-push-notifications (tut-push-notifications)
  • 다음 옵션을 선택합니다.

  • ? What do you want to use as your public directory? public
    ? Configure as a single-page app (rewrite all urls to /index.html)? Yes
    ? Set up automatic builds and deploys with GitHub? No
    


  • Firebase 초기화 🎉
  • Firebase는 firebase.json.firebaserc
  • 를 생성합니다.
  • gcm_sender_id 속성을 manifest.json 에 추가합니다. 변경하지 않고 그대로 아래 값을 삽입하십시오.

  • {
      "gcm_sender_id": "103953800507"
    }
    


  • 공용 폴더에 firebase-messaging-sw.js 파일을 만듭니다. 이 서비스 워커는 앱이 백그라운드에 있을 때 알림을 수신하고 표시합니다.

  • /* eslint-disable no-undef */
    importScripts('https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js')
    importScripts('https://www.gstatic.com/firebasejs/8.6.8/firebase-messaging.js')
    
    const firebaseConfig = undefined // firebaseConfig is required
    
    firebase.initializeApp(firebaseConfig)
    
    const messaging = firebase.messaging()
    
    messaging.onBackgroundMessage((payload) => {
      console.log('[firebase-messaging-sw.js] Received background message ', payload)
      const notificationTitle = payload.notification.title
      const notificationOptions = {
        body: payload.notification.body,
        icon: payload.notification.icon || payload.notification.image,
      }
    
      self.registration.showNotification(notificationTitle, notificationOptions)
    })
    
    self.addEventListener('notificationclick', (event) => {
      if (event.action) {
        clients.openWindow(event.action)
      }
      event.notification.close()
    })
    


  • firebaseConfig = undefinedfirebase-messaging-sw.js를 Firebase 구성으로 바꿉니다. Firebase 콘솔의 Project settings에서 찾습니다.


  • 생성src/services/Firebase/Firebase.tsx하고 다음 코드를 추가합니다. 나중에 사용할 @useweb/use-firebase 패키지에 필요한 데이터를 전달하기 위해 @useweb/use-firebase-messaging 패키지를 사용하고 있습니다.

  • import React from 'react'
    import { FirebaseProvider } from '@useweb/use-firebase'
    import { initializeApp } from 'firebase/app'
    import { getMessaging } from 'firebase/messaging'
    
    const firebaseConfig = undefined // firebaseConfig is required
    
    const firebaseApp = initializeApp(firebaseConfig)
    const messaging = getMessaging(firebaseApp)
    
    const envIsDev = process.env.NODE_ENV === 'development'
    
    const vapidKey = undefined // vapidKey is required
    
    export default function Firebase({ children }) {
      return (
        <FirebaseProvider
          firebaseConfig={firebaseConfig}
          firebaseApp={firebaseApp}
          envIsDev={envIsDev}
          messaging={messaging}
          messagingOptions={{
            vapidKey,
          }}
        >
          {children}
        </FirebaseProvider>
      )
    }
    


  • firebaseConfig = undefinedsrc/services/Firebase/Firebase.tsx를 Firebase 구성으로 바꿉니다. Firebase 콘솔의 Project settings에서 찾습니다.


  • Firebase 메시징 생성vapidKey
  • Firebase 콘솔 프로젝트 설정에서 Cloud Messaging tab을 열고 웹 구성 섹션으로 스크롤합니다.
  • Web Push certificates 탭에서 Generate key pair 버튼을 클릭합니다.
  • vapidKey = undefinedsrc/services/Firebase/Firebase.tsx를 생성된 vapidKey
  • 로 바꿉니다.
  • Firebase.tsx
  • 로 앱을 래핑하십시오.
    src/index.tsx
    import React from 'react'
    import ReactDOM from 'react-dom'
    
    import Firebase from './services/firebase/firebase'
    import Router from './pages/router'
    import Theme from './theme/theme'
    
    function App() {
      return (
        <Firebase>
          <Theme>
            <Router />
          </Theme>
        </Firebase>
      )
    }
    
    ReactDOM.render(<App />, document.getElementById('root'))
    


  • @useweb/use-firebase-messaging를 사용하여 FCM 등록 토큰을 검색하고 앱이 포그라운드에 있는 동안 알림을 처리합니다. pages/HomePage/HomePage.tsx에 다음 코드를 추가합니다.

  • import React, { useEffect } from 'react'
    import Box from '@mui/material/Box'
    import Button from '@mui/material/Button'
    import LinearProgress from '@mui/material/LinearProgress'
    import useFirebaseMessaging from '@useweb/use-firebase-messaging'
    
    import CopyToClipboard from '../../lib/components/CopyToClipboard/CopyToClipboard'
    import Text from '../../lib/components/Text/Text'
    import Header from '../../lib/components/_unique/Header/Header'
    import useSnackbar from '../../lib/components/Snackbar/Snackbar'
    
    export default function HomePage() {
      const snackbar = useSnackbar()
    
      const firebaseMessaging = useFirebaseMessaging({
        onMessage: (message) => {
          console.log(`Received foreground message`, message)
          snackbar.show({
            message: message?.notification?.title || message?.data?.title,
          })
        },
      })
    
      useEffect(() => {
        firebaseMessaging.init()
      }, [])
    
      return (
        <Box>
          <Header
            title='Firebase Messaging Push Notification Example'
            tutorialLink='how-to-send-push-notifications-with-firebase-and-react'
            repoLink='https://github.com/jeremytenjo/how-to-send-push-notifications-with-firebase-and-react'
          />
    
          {firebaseMessaging.initializing && (
            <>
              <Text
                text='Initializing Firebase Messaging (enable notifications for this page)'
                sx={{ mb: 2 }}
              />
              <LinearProgress />
            </>
          )}
    
          {firebaseMessaging.error && (
            <Text text={firebaseMessaging.error.toString()} sx={{ color: 'red' }} />
          )}
    
          {firebaseMessaging.fcmRegistrationToken && (
            <>
              <Box
                sx={{
                  display: 'grid',
                  gridAutoFlow: 'column',
                  justifyContent: 'start',
                  alignItems: 'center',
                  mb: 1,
                  gridGap: '10px',
                }}
              >
                <Text text='FCM Registration Token:' />
                <CopyToClipboard text={firebaseMessaging.fcmRegistrationToken}>
                  <Button>Copy</Button>
                </CopyToClipboard>
              </Box>
    
              <Text
                text={firebaseMessaging.fcmRegistrationToken}
                sx={{
                  width: '100%',
                  overflowWrap: 'break-word',
                  fontSize: '14px',
                  color: 'grey.main',
                }}
              />
            </>
          )}
        </Box>
      )
    }
    


    이제 생성된 FCM 등록 토큰을 사용하여 푸시 알림을 테스트할 수 있습니다.
  • 오픈 http://localhost:3001/
  • Firebase 메시지 작성기 열기

  • firebase messaging composer step 1
  • New campaign 버튼을 클릭하십시오
  • Notifications 버튼을 클릭하십시오


  • 추가 Notification titleNotification text
  • 클릭 Send test message
  • http://localhost:3001/에서 생성된 등록 토큰을 추가하고 더하기 아이콘
  • 을 클릭합니다.
  • 클릭 Test

  • 🎉 앱이 포그라운드에 있으면 앱에 스낵바가 표시되고 앱이 백그라운드에 있으면 기본 알림이 표시됩니다.



    클라우드 기능에서 알림 보내기(고급)


  • 클라우드 메시지를 보내려면 FCM registration token 가져오기.

  • const messaging = useFirebaseMessaging({
      onFcmRegistrationToken: (fcmRegistrationToken) => {
        console.log(fcmRegistrationToken)
      },
    })
    


  • nodejs 함수/앱에서 메시지 보내기

  •         const message = {
              data: {
                title: `New episodes aired recently!`,
                image: `/images/logo/assets/logo.png`,
                icon: `/images/logo/assets/logo.png`,
                body,
                actions: JSON.stringify(actions),
              },
              tokens: fcmRegistrationToken,
            }
    
            functions.logger.info('FCM Message', message)
    
            // https://firebase.google.com/docs/cloud-messaging/send-message#send-messages-to-multiple-devices
            const response = await messaging.sendMulticast(message)
    
    


    지금은 여기까지입니다. 이 튜토리얼이 도움이 되었기를 바랍니다! 아래에 피드백이나 질문을 자유롭게 남겨주세요. 듣고 작업하고 싶습니다.

    ✌️에서 더 많은 콘텐츠를 확인하려면 팔로우하세요.

    좋은 웹페이지 즐겨찾기