Sending Push Notifications with SMS in a Lambda Function

2023-03-07

Sending Push Notifications with SMS in a Lambda Function

This is a series of articles about setting up a complex Serverless backend infrastructure with AWS SAM and CloudFormation.

Here is the index of all the articles in case you want to jump to any of them:

1. Setup of AppSync and API Gateway with Multiple AWS Cognito User Pools

2. Configuring S3 Buckets with Permissions and Access Roles in AWS Cognito AuthRole

3. Intro to DynamoDB Resolvers for AppSync Implementation

4. Intro to Lambda Resolvers for AppSync Implementation

5. Configuring an AWS VPC to Include Lambda Resolvers with a Fixed IP

6. Intro to Pipeline Resolvers for AppSync Implementation

7. Handling Lambda Resolver Timeouts with SNS Messages

Introduction

Push notifications are a powerful tool for real-time user engagement. In this article, we'll explore how to send push notifications using SMS from a Lambda function. We'll use Amazon SNS (Simple Notification Service) to send these SMS messages.

Amazon SNS is a fully managed messaging service that supports multiple messaging types, including SMS. By integrating SNS with AWS Lambda, we can send SMS messages in response to various triggers or events.

The Code

1. Setting up the Infrastructure

To set up our infrastructure, we'll use AWS CloudFormation. This will allow us to define and provision our resources in a structured manner.

Resources:

  # SNS Topic for SMS
  SMSTopic:
    Type: "AWS::SNS::Topic"
    Properties:
      DisplayName: "SMSPushNotification"

  # Lambda Function to send SMS
  SendSMSPushFunction:
    Type: "AWS::Lambda::Function"
    Properties:
      Handler: "index.handler"
      Role: !GetAtt LambdaExecutionRole.Arn
      FunctionName: "SendSMSPush"
      Code:
        S3Bucket: "myBucket"
        S3Key: "code/sendSMSPush.zip"
      Runtime: "nodejs14.x"

  # IAM Role for Lambda Execution
  LambdaExecutionRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service: "lambda.amazonaws.com"
            Action: "sts:AssumeRole"
      Policies:
        - PolicyName: "LambdaExecutionPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: "Allow"
                Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Resource: "arn:aws:logs:*:*:*"
              - Effect: "Allow"
                Action: "sns:Publish"
                Resource: !Ref SMSTopic

2. Implementing the Lambda Function

Let's dive into the Lambda function's code with our infrastructure in place. This function will take a phone number and a message as input and send an SMS.

const AWS = require('aws-sdk');
const sns = new AWS.SNS();

exports.handler = async (event) => {
  const phoneNumber = event.phoneNumber;
  const message = event.message;

  const params = {
    Message: message,
    PhoneNumber: phoneNumber
  };

  try {
    const data = await sns.publish(params).promise();
    return { messageId: data.MessageId };
  } catch (error) {
    console.error(error);
    throw new Error('Failed to send SMS');
  }
};

Conclusion

By integrating AWS Lambda with Amazon SNS, we've created a flexible and scalable solution for sending SMS push notifications. This approach can be extended to support other notifications types or integrate with other AWS services.

Please note that the code examples have been simplified to help understand the approach and the resources. Some adjustments might be needed.