Firebase

How to use Firebase Cloud Messaging with Firebase Functions for push notifications?

Discover how to seamlessly merge Firebase Cloud Messaging with Firebase Functions for easy push notification delivery. Follow this step-by-step guide to simplify your setup process.

Developer profile skeleton
a developer thinking

Overview

Implementing Firebase Cloud Messaging (FCM) with Firebase Functions lets you send real-time push notifications to users, triggered by events in your Firebase backend. This process involves setting up your Firebase project to manage FCM and crafting Firebase Functions to watch for events like database changes, Firestore updates, or user authentication events. Merging FCM and Firebase Functions guarantees timely and pertinent alerts, boosting user engagement and maintaining a dynamic, interactive app experience.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to use Firebase Cloud Messaging with Firebase Functions for push notifications?

Step 1: Set Up Firebase in Your Project

  1. Head over to the Firebase Console.
  2. Create a new project or pick one you already have.
  3. Add your Android or iOS app to the project and grab the config file (google-services.json for Android and GoogleService-Info.plist for iOS).
  4. Drop that config file into your app.

Step 2: Add Firebase SDK to Your App

For Android:

  • In your build.gradle (Project level), add:

    ```gradle
    classpath 'com.google.gms:google-services:4.3.3'
    ```

  • In your build.gradle (App level), add:

    ```gradle
    implementation 'com.google.firebase:firebase-messaging:21.0.1'
    apply plugin: 'com.google.gms.google-services'
    ```

For iOS:

  • In your Podfile, add:

    ```ruby
    pod 'Firebase/Messaging'
    ```

  • Run pod install to get those Firebase dependencies.

Step 3: Initialize Firebase in Your App

For Android:

  • In your MainActivity's onCreate method, add:

    ```java
    FirebaseApp.initializeApp(this);
    ```

For iOS:

  • Import Firebase in your AppDelegate:

    ```swift
    import Firebase
    ```

  • Initialize Firebase in application:didFinishLaunchingWithOptions:

    ```swift
    FirebaseApp.configure()
    ```

Step 4: Set Up Firebase Cloud Messaging (FCM) in Your App

  1. Register for FCM in your app and get the token:

    For Android:

    • In your FirebaseMessagingService, add:

      ```java
      public class MyFirebaseMessagingService extends FirebaseMessagingService {

        @Override
        public void onNewToken(String token) {
            super.onNewToken(token);
            // Send token to your server or save it locally
        }
      
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
            // Handle the received message
        }
      

      }
      ```

    For iOS:

    • Register for remote notifications in AppDelegate:

      ```swift
      UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
      guard granted else { return }
      DispatchQueue.main.async {
      UIApplication.shared.registerForRemoteNotifications()
      }
      }
      ```

Step 5: Set Up Firebase Functions

  1. Install Firebase CLI:

    ```bash
    npm install -g firebase-tools
    ```

  2. Initialize Firebase Functions in your project:

    ```bash
    firebase init functions
    ```

  3. Choose JavaScript or TypeScript as your language.

Step 6: Write Your Firebase Function

  1. Open the index.js (or index.ts for TypeScript) file inside the functions folder.

  2. Require the necessary modules and write a function that uses FCM to send a notification. Here's a sample:

    ```javascript
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();

    exports.sendPushNotification = functions.https.onRequest((req, res) => {
    const message = {
    notification: {
    title: req.body.title,
    body: req.body.body,
    },
    token: req.body.token,
    };

    admin.messaging().send(message)
    .then((response) => {
    res.status(200).send('Notification sent successfully: ' + response);
    })
    .catch((error) => {
    res.status(500).send('Error sending notification: ' + error);
    });
    });
    ```

Step 7: Deploy Your Function

  1. Deploy the function using Firebase CLI:

    ```bash
    firebase deploy --only functions
    ```

  2. Once deployed, the function can be triggered via an HTTPS request.

Step 8: Trigger Notification from Your App

  1. Send an HTTPS POST request from your app to trigger the Firebase function.

    Example with fetch in JavaScript:

    ```javascript
    const response = await fetch('YOUR_CLOUD_FUNCTION_URL', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    },
    body: JSON.stringify({
    title: 'Hello!',
    body: 'This is a test notification.',
    token: 'TARGET_DEVICE_TOKEN',
    }),
    });

    const responseBody = await response.json();
    console.log(responseBody);
    ```

Note: Replace YOUR_CLOUD_FUNCTION_URL with the URL of your deployed function and TARGET_DEVICE_TOKEN with the token retrieved in Step 4.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.