How to Send SMS using NodeJS and AWS Lambda

March 19, 2024
Written by
Reviewed by

How to Send SMS using NodeJS and AWS Lambda

In the era of digital communication, SMS remains a vital tool for businesses to connect with their customers promptly and effectively. Leveraging the power of cloud computing and APIs, developers have found innovative ways to send SMS messages seamlessly. One method involves using AWS Lambda, a serverless computing platform by Amazon Web Services, in conjunction with Twilio. This integration allows for the development of lightweight, scalable applications for sending SMS messages, without the overhead of managing infrastructure.

Prerequisites

Before we can move forward, make sure you have the following.

AWS Lambda to send SMS

Today we will create our own SMS sending service using AWS Lambda Functions and Twilio. Just imagine all the value and convenience that it puts in your hands.

Let’s start with creating the Lambda Function in AWS Console. Once you are logged into your AWS Account, you can search for AWS Lambda in the search bar.

AWS Management Console with Lambda Service in search

You will see all the Lambda Functions you might have, but to create a new one, click on Create function.

AWS Lambda Functions Dashboard

Let’s name the function lambda-twilio-sms . Runtime is Node.js 20.x . Leave the Architecture as x86_64.

AWS Lambda Function creation wizard with different properties like Function Name, Runtime, etc.

Now under Advanced settings, check the Enable function URL and select Auth type NONE. This allows us to send HTTP requests to our Lambda Function.

For real-world use-cases, you should put the Lambda functions behind an API Gateway to add proper authentication and authorization.

Advanced Settings tab of Lambda Function creation wizard to enable function URL

Writing Lambda functions in Node.js

Now let’s write some JavaScript code. Start by creating a directory locally named twilio-aws-lambda and initializing the node.

mkdir twilio-aws-lambda
cd twilio-aws-lambda
npm init -y

We will need the twilio npm library, install it by running the following command in the console.

npm install twilio --save

Let’s implement the function that uses the twilio package to send SMS based on the provided request parameters. The account credentials will automatically be retrieved from the corresponding environment variables which we will set up later:

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

const client = require('twilio')(accountSid, authToken);

exports.handler = async (event, context) => {
  const data = JSON.parse(event.body);
  const body = data.body;
  const to = data.to;

  try {
    const message = await client.messages.create({
      body: body,
      from: process.env.TWILIO_NUMBER,
      to: to,
    });
    return {
      statusCode: 200,
      body: JSON.stringify(message),
    };
  } catch (err) {
    return {
      statusCode: 500,
      body: JSON.stringify(err),
    };
  }
}

We have to zip the folder to upload to Lambda. You can do so by opening up the terminal, navigating into the folder and running.

zip -r ../twilio-aws-lambda.zip *

Now, your project folder should have the zip file twilio-aws-lambda.zip that we will upload to AWS Lambda. In the AWS Management Console, within your Lambda Function, click on the Code tab, and you will see an Upload from button on the right hand side, then select “.zip file” as the option and upload twilio-aws-lambda.zip.

lambda-twilio-sms Lambda Function overview with Code tab highlighted with functionality to upload .zip file

You can also use the AWS CLI. For this step, make sure you have installed and configured the AWS CLI and then utilize the update-function-code, more details can be found here.

Before we can test our Lambda function, there is one last configuration we have to modify. The Lambda function timeout is set to 3 seconds by default, let’s change that to 60 seconds. Go to the Configuration tab and under General Configuration you will find the setting for timeout. Edit the timeout to 1 minute and then click Save.

Configuration tab in the Lambda Function Settings with General Configuration selected
Timeout setting in the Lambda Function configuration changed to 1 minute, default is 3 seconds

Configuring your Twilio Account

Once you are logged in to the Twilio Console, scroll down to find your Account SID and Auth Token. Copy these values, as we will save these as Environment Variables within AWS Lambda.

Twilio Console home screen with Account SID and Auth token highlighted

To send a message, you will need to buy a phone number—ideally from the region you are based in—to avoid roaming charges. To accomplish this, go to the Twilio Console and search for a number you’d like to buy.

Buy a number screen in Twilio Console, with numbers from Canada

Head over to AWS Management Console and within your Lambda Function, click on Configuration tab and then select Environment Variables. Add the three values (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_NUMBER) you copied earlier.

Configuration tab in Lambda Function, with Environment Variables setting selected. Added Twilio secrets in Environment Variables.

Send a test message with AWS Lambda

Go to the Test tab and Create new event. Let’s name it “TestSMS” and in the Event JSON field add a valid to number (number you want to send text to) and body for the SMS.

{
"body": "{\"to\":\"<your_phone_number>\", \"body\":\"Ahoy, World!\"}",
"headers": {
    "Content-Type": "application/json"
    }
}
Test event for the Lambda Function. Creating new event named TestSMS with Event JSON having required information.

Click on Save and then Test.

After you hit Test, the function executes the code and you should see the log output.

Test Execution succeeded with statusCode of 200.

Remember, we also enabled the function URL so we could send HTTP requests, you can do so by either using Postman or cURL . You can find your Lambda function URL in the Function overview tab:

Lambda Function overview screen with Function URL being highlighted.

Here is a curl request example:

curl -m 70 -X GET https://<your-function-url>.lambda-url.us-east-1.on.aws/ \
-H "Content-Type: application/json" \
-d '{
  "to": "<your_phone_number>",
  "body": "Ahoy World from Terminal"
}'

And Voila! You have built an AWS Lambda Function that you can send SMS with by sending an HTTP request with a valid to phone number and message as body.

Conclusion

In conclusion, integrating AWS Lambda with Twilio to send SMS messages using NodeJS offers a powerful, scalable, and cost-effective solution. This combination leverages the serverless cloud infrastructure of AWS and the seamless communication capabilities of Twilio, providing a reliable and efficient way to send SMS. With the simplicity of NodeJS and Serverless, developers can easily implement and maintain this solution without the need for extensive infrastructure. This integration not only streamlines the process of sending SMS messages but also opens up possibilities for other innovative applications. I can’t wait to see what you build!

Rishab Kumar is a Developer Evangelist at Twilio and a cloud enthusiast. Get in touch with Rishab on Twitter @rishabincloud and follow his personal blog on cloud, DevOps, and DevRel adventures at youtube.com/@rishabincloud.