TADA: Coincidence of NodeJS and FCM with AWS Pinpoint Push Notifications
Tags: aws, node, firebase, ios
Published: 2022-04-01 07:46:10

The agenda of this story is to realize that whatever you learned today or in past will be useful one day. You never know when situation strikes.  
So here is what happen, I was working closely with my client and some how [**FCM Push Notifications**](https://firebase.google.com/docs/cloud-messaging/http-server-ref) are working fine at our end. But we were using **FCM HTTP API** to test. Our client was using AWS Pinpoint. Now since the clashes of SDKs and the server written in python.

Now since AWS provide almost every server language support and I have worked on Node JS almost 2 years back. So I decided to go back and create simple server. So I created a free AWS account and navigate to [SDK for Node JS](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-nodejs.html).

**Note:**

1. Don’t afraid of adding **Credit Card Details** while doing signup on **AWS**. As they will only charge if the usgage exceeds free plan.
2. To test push notifications from **AWS Pinpoint** console here is the [**document**](https://docs.aws.amazon.com/pinpoint/latest/userguide/messages-mobile.html).

For beginners seeking **Node JS tutorial**. I will recommend [this](https://www.udemy.com/course/nodejs-express-mongodb-bootcamp/).

I am expecting you have basic knowledege of Node JS. Still you can setup project from here

1. **VS Code:** [https://code.visualstudio.com/docs/nodejs/nodejs-tutorial](https://code.visualstudio.com/docs/nodejs/nodejs-tutorial)
2. **MDN:** [https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express\_Nodejs/development\_environment](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment)

So situation is not that simple here as we go through Node JS SDK [**Document**](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-nodejs.html).

```json
{  
  "name": "aws-sdk-v3-iam-examples",  
  "version": "1.0.0",  
  "main": "index.js",  
  "dependencies": {  
   "@aws-sdk/client-s3": "^3.32.0"  
  },  
  "type": "module"  
}
```

Now according to this we are installing **AWS S3 Client**. But wait our requirement is to test notification using pinpoint. So we will add depedencies in **package.json** like below

```json
{  
  "name": "FCM Test Server",  
  "version": "1.0.0",  
  "main": "index.js",  
  "author": "Abhishek Thapliyal",  
  "dependencies": {  
    "@aws-sdk/client-pinpoint": "^3.54.1",  
    "aws-sdk": "^2.1094.0"  
  },  
  "type": "module"  
}
```

Hit the below command to install dependencies

```script
npm install
```

Now as per [**official document**](https://docs.aws.amazon.com/pinpoint/latest/developerguide/send-messages-push.html), Node JS Example for testing push notification will be updated as below. In doc you will see other targets as well like **APNS**, **Baidu** etc. But we need to **FCM** so I removed other services.

```javascript
"use strict";

const AWS = require("aws-sdk");
const region = "<REGION>";

var applicationId = "<APPLICATION_ID>";

var recipient = {
  token: "<FCM TOKEN>",
  service: "GCM",
};

function CreateMessageRequest() {
  var token = recipient["token"];
  var service = recipient["service"];
  if (service == "GCM") {
    var messageRequest = {
      Addresses: {
        [token]: {
          ChannelType: "GCM",
        },
      },
      MessageConfiguration: {
        GCMMessage: {
          RawContent: `{
                    "notification": {
                      "title": "AWS Pinpoint Notification title",
                      "body": "AWS Pinpoint Notification body",
                      "sound": "default",
                      "content_available": true
                    },
                    "data": {
                      "url": "katapult://leases/118636"
                    },
                    "priority": "high"
                  }`,
        },
      },
    };
  }

  return messageRequest;
}

function ShowOutput(data) {
  if (
    data["MessageResponse"]["Result"][recipient["token"]]["DeliveryStatus"] ==
    "SUCCESSFUL"
  ) {
    var status = "Message sent! Response information: ";
  } else {
    var status = "The message wasn't sent. Response information: ";
  }
  console.log(status);
  console.dir(data, { depth: null });
}

function SendMessage() {
  var token = recipient["token"];
  var service = recipient["service"];
  var messageRequest = CreateMessageRequest();
  var credentials = new AWS.SharedIniFileCredentials({ profile: "default" });
  AWS.config.credentials = credentials;
  AWS.config.update({ region: region });
  var pinpoint = new AWS.Pinpoint();
  var params = {
    ApplicationId: applicationId,
    MessageRequest: messageRequest,
  };

  pinpoint.sendMessages(params, function (err, data) {
    if (err) console.log(err);
    else ShowOutput(data);
  });
}

exports.SendMessage = SendMessage;
```

Now you have to replace **REGION**, **APPLICATION\_ID** and **FCM** **TOKEN**.

**REGION:** You will get region on top right cornor of AWS console.

![AWS Region](https://miro.medium.com/max/1400/1*ywhBVKfqedJ9swa7ExgIlQ.png)

**APPLICATION\_ID:** Search for pinpoint in AWS Console. Add a new project. It will ask for **Configure features,** select **Push Notifications.** It will as for **Push notifications services,** choose **FCM** and add FCM Server key from FCM Console. You will get inside **Project Settings > Cloud Messsaging.**

You will get **Application Id** name as **Project Id** when project is created successfully in AWS Pinpoint.

![AWS Pinpoint Dashboard](https://miro.medium.com/max/1400/1*1cfb85JSpPPCLb0QV3-Fgg.png)

**FCM** **TOKEN** : You will get fcm token from device depending upon the mobile project you are working. Below are references for setup and get FCM Token

1. **Android**: [https://firebase.google.com/docs/cloud-messaging/android/client](https://firebase.google.com/docs/cloud-messaging/android/client)
2. **iOS**: [https://firebase.google.com/docs/cloud-messaging/ios/client](https://firebase.google.com/docs/cloud-messaging/ios/client)
3. **React-Native**: [https://firebase.google.com/docs/cloud-messaging/ios/client](https://firebase.google.com/docs/cloud-messaging/ios/client)

Make sure you have requested notifications in already before testing.

I have used to **RawContent** as I wanted to support background notification as per FCM Payload Structure. You can play around with properties from [**here**](https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-push.html).

So In your request controller you have to use like this

```javascript
const { SendMessage } = require("./Location /to/pinpoint\_notification\_service.js");.  
..  
...
SendMessage();
```

Use **async await** to make flow as per your requirement.

Hit the API and See the magic

All document links are attached. You can check and feel free to add feedback.

**Happy Coding 😄😄**