Send FCM push notifications with AWS Lambda function

Push notifications are back here again. In this case I’m going to send it from the clouds.

In this simple example I’ll use AWS Lambda function with API Gateway integration and Firebase Cloud Messaging service in order to send push notifications to the topic subscribers.

Let’s begin

At first we’re creating a new Node.js AWS Lambda function.

const https = require('https');
var AWS = require('aws-sdk');

exports.handler = (event, context, callback) => {
    processNotification(JSON.parse(event.body), context);
};

function processNotification(notificationData, context) {
    console.log(notificationData);
    const FIREBASE_API_KEY = '<YOUR-FIREBASE-API-KEY>';
    const data = JSON.stringify({
        message: {
            topic: 'common',
            notification: {
                body: notificationData.message,
                title: notificationData.title
            }
        }
    });
    const options = {
        host: 'fcm.googleapis.com',
        path: '/v1/projects/<YOUR-PROJECT-ID>/messages:send',
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + FIREBASE_API_KEY,
            'Content-Type': 'application/json'
        }

    };

    const req = https.request(options, (res) => {
        console.log(`statusCode: ${res.statusCode}`)
        res.on('data', (d) => {
            process.stdout.write(d)
        })

    })

    req.on('error', (error) => {
        console.error(error)
    })

    req.write(data)
    req.end();
    return context.succeed(buildSuccessResponse(data));

}

function buildSuccessResponse(data) {
    return {
        statusCode: 200,
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json',
        }
    };
}

The function is sending push notification toΒ the topic (which is calledΒ common) subscribers. Proper notification data is obtained from the event body.

Please note you’ll need OAuth FCM token (FIREBASE_API_KEY variable – how to get the token? Read more here) and your Firebase project identifier.

Then we’ll need to create API Gateway resource. If you already have one you can create a POST method with Lambda proxy integration. Pass your specific function name there.

Then you can send your very first test event.

{
    "title": "Hello \uD83D\uDE42 πŸ˜ŠπŸπŸ‘Œ",
    "message": "This is the message... πŸŒ²πŸ“¦πŸπŸ†•πŸ˜‹πŸ‘Œ"
}

If everything is okay you should receive your notification. It even supports emojis πŸ™‚.

Now we can deploy the API and use the endpoint.

The end

And that’s it. You can now send your push notifications using AWS Lambda function.
Please note that this is just a simple example. In production environment you’ll have to handle OAuth tokens refreshing (read more about it).

 

 

 

 

5 thoughts on “Send FCM push notifications with AWS Lambda function”

    1. Thanks, Salah, this is a very good point πŸ‘

      Well, there are multiple ways to achieve the same goal using AWS.
      For instance, we could add AWS SNS to that list as well.

      I’d say, use what works best for you.

      Take care πŸ‘‹

  1. Hi Rafal,

    I can’t find out how to send messages to Firebase topics subscribers using AWS SNS.

    In my use case there is no server that could manage device tokens. So, I’d like to send push notifications to specific device groups that subscribed to specific FCM topics. Is it anyhow possible without to use another AWS service or API?

    Currently I’m getting the message content from AWS IoT Core, that forwards it via a Rule to SNS. But how to use Firebase topics instead of device tokens in SNS…

    Any help would be much appreciated! πŸ™‚

    1. I was able to get it right. However your code sample didn’t work for me. I’v got an error in line 5. Maybe a different Node.js version… Anyway, thank you!

Leave a Reply

Your email address will not be published.