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).

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *