Implementing Mobile Push Notifications with AWS and Terraform
Tags: aws, terraform, node, mobile
Published: 2023-10-17 18:19:08

Mobile push notifications are unavoidable whether you're building a mobile app or a web application. AWS provides multiple services for implementing push notifications. In this article, we'll see how to implement mobile push notifications with AWS SNS and Terraform.

## Before starting
What you will need :
- An AWS account.
- A mobile app.
- Terraform installed.

## Create an SNS (Simple Notification Service) Topic
Amazon SNS is the notification service from AWS using topics to send messages in a one to many way (Pub/Sub). 
Here is an article if you wanna know more about it : https://dev.to/onepoint/aws-sqs-sns-kinesis-eventbridge-how-to-choose--32l7.

Let's create an SNS topic with Terraform :

**Terraform Configuration:**

```hcl
resource "aws_sns_topic" "push_notifications" {
  name = "MyPushNotificationsTopic"
}
```

## Configure Application Platforms
AWS SNS supports multiple platforms (iOS, Android...) To send push notifications to specific devices, you need to configure the right platform.

**iOS Example:**

```hcl
resource "aws_sns_platform_application" "ios_app" {
  name     = "MyiOSApp"
  platform = "APNS"
  attributes = {
    PlatformCredential = "<APNS_CERT>"
    PlatformPrincipal = "<APNS_PRIVATE_KEY>"
  }
}
```

**Android Example:**

```hcl
resource "aws_sns_platform_application" "android_app" {
  name     = "MyAndroidApp"
  platform = "GCM"
  attributes = {
    PlatformCredential = "<GCM_API_KEY>"
  }
}
```

## Subscribe Devices to the Topic

To receive push notifications, your mobile devices need to subscribe to the SNS topic. Let's do it in the mobile app code :

**Android Example:**

```java
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
    @Override
    public void onResult(UserStateDetails result) {
        if (result.getUserState() == UserState.SIGNED_IN) {
            String endpointArn = AWSMobileClient.getInstance().getDetails().getUserSub();
            AWSSNSClient snsClient = new AWSSNSClient(getApplicationContext());
            snsClient.createPlatformEndpoint(endpointArn, "MyAndroidApp", "ANDROID_DEVICE_TOKEN");
        }
    }

    @Override
    public void onError(Exception e) {
        // Handle error
    }
});
```

## Send Push Notifications
Now that your devices are subscribed to the SNS topic, you can send push notifications to them by publishing messages in the SNS topic like follows :

```typescript
import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";

// Create an SNS client
const snsClient = new SNSClient({ region: "us-east-1" }); // Replace with your desired AWS region

// Set the message parameters
const params = {
  Message: "Hello from AWS SNS!",
  MessageStructure: "string",
  TopicArn: "arn:aws:sns:us-east-1:123456789012:MyPushNotificationsTopic", // Replace with your SNS topic ARN (the AWS unique id of the topic)
};

// Publish the push notification
const publishCommand = new PublishCommand(params);

snsClient.send(publishCommand)
  .then((data) => {
    console.log("Push notification sent successfully:", data);
  })
  .catch((error) => {
    console.error("Error sending push notification:", error);
  });
```

## Handle Notifications in Your App
Finally, in the mobile app, you need to implement the code that handles incoming push notifications. This involves setting up listeners and customizing the user interface to handle notifications.

**Example Code (iOS, using Swift):**

```swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    if let aps = userInfo["aps"] as? [String: Any] {
        let alert = UIAlertController(title: "Push Notification", message: aps["alert"] as? String, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }
}
```
## Conclusion

Implementing mobile push notifications with AWS is a straightforward process, and Terraform can simplify the infrastructure provisioning and configuration. By following the steps outlined in this guide and adapting the code examples to your specific platform and requirements, you can successfully integrate push notifications into your mobile app or web application.

As you continue to develop your application, consider implementing additional features like push notification personalization, in-app messaging, and performance monitoring to enhance the user experience.

Happy pushing!