Going Serverless With Twilio

March 04, 2024
Written by
Joseph Udonsak
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Going Serverless With Twilio

The search for innovative solutions to enhance application efficiency, scalability, and cost-effectiveness has led to the rise of "serverless computing" — a transition from traditional server-based architectures to a more dynamic and agile model which changes how we design, deploy, and manage applications.

Gone are the days when organizations needed to invest in and manage complex server infrastructure to run applications. Serverless computing, in essence, shifts the burden of infrastructure management away from developers, allowing them to focus on writing code and delivering value to end-users.

In addition to SDKs and a REST API, Twilio provides a serverless outlet for its products. These come in the form of TwiML Bins and Twilio functions . In this tutorial, I will walk you through Twilio's serverless offerings and how they can enhance your developer experience.

In the spirit of the season, you will set up a TwiML Bin for your phone number which plays an automated New Years’ message whenever your phone number is called. Additionally, you can spread cheer by triggering phone calls to your loved ones — via SMS.

To follow this article, you will require the following:

Create a TwiML Bin

Head to the TwiML Bins section of the Twilio Console. Then:

  • Click on the + button to create a new bin
  • Give your bin a friendly name (e.g., "Happy New Year")
  • Update the TwiML section to match the following code
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>
   Happy New Year. Best wishes for 2024!!!
  </Say>
  <Play>
    https://bitly.ws/34Pc5
  </Play>
</Response>

The TwiML instruction uses the and verbs to say a New Year’s message and play an audio file back to the caller.

The audio file courtesy of Clipchamp.

Click on the Create button to finish up. You will be redirected and shown the properties of the newly created Bin as shown below.

Make a note of the Bin’s URL as we will be using this in the next section.

Create a Serverless Function

To create a serverless function, head to the Services section of the Twilio Console. There, click on the Create Service button to create a new service, give it a friendly name of your choice, and click the Next button.

You will be redirected to the Twilio Functions environment, from where you can create new functions. Click the Create your function button to create a new function. A new path will be created under the Functions tab. You can rename it to something more appropriate (for example greet).

The function you will create requires your Twilio phone number, so add that before proceeding. Click on the Environment variables button (under Settings & More). Next, add a new variable with the KEY named PHONE_NUMBER, and with the value set to your Twilio phone number. Click Add to complete the process. Then, add another variable named BIN_URL for your TwiML Bin URL.

Your Twilio function will also require a Twilio client. Twilio simplifies this for you. All you have to do is enable the Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV option, and you will have access to an initialized Twilio REST client.

Your environment variables should look like the following.

Next, click on your function path and update the code to match the following.

exports.handler = async function (context, event, callback) {
  const twilioClient = context.getTwilioClient();

  // Query parameters or values sent in a POST body can be accessed from `event`
  const from = context.PHONE_NUMBER;
  const to = event.Body;
  const url = context.BIN_URL;

  twilioClient.calls
    .create({ to, from, url })
    .then((call) => {
      console.log('Call successfully placed');
      console.log(call.sid);
      return callback(null, `Success! Call SID: ${call.sid}`);
    })
    .catch((error) => {
      console.error(error);
      return callback(error);
    });
};

This function will handle an SMS event for your Twilio phone number. When you send a phone number (in E.164 format), your function will call that phone number and deliver your New Year’s greeting as specified in your TwiML bin. To keep things simple, the function does not validate the content of the SMS.

Save the changes you have made by clicking the Save button. Next, click the Deploy All at the bottom left of your screen to build and deploy your newly created function.

Link the TwiML Bin and Serverless Function to your Twilio phone number

The last step is to link the TwiML bin and serverless function you created earlier to your Twilio phone number. To do this, head to the Active Numbers section of the Twilio Console and click on your Twilio phone number. This will direct you to the configuration page for your phone number.

In the Voice Configuration section, update the configuration as shown below. Make sure you select the bin you created in the TwiML Bin section.

Next, update the Messaging configuration as shown below. Make sure you select your messaging service in the Messaging Service. Do the same for the Service and Function Path options.

Click the Save configuration button to save all your changes.

Test that it all works

All that’s left is for you to test your implementation. To do that, make a voice call to your Twilio phone number to hear a special greeting. You can also send an SMS to your Twilio phone number with just the phone number of a loved one, and they can share in the season cheer.

That's how to start going Serverless with Twilio

Sometimes, building a new feature doesn’t have to be a painful experience — especially if you’re still getting to grips with setting up and managing servers. In this tutorial, you were able to build an automated responder without having to worry about anything infrastructure related — because Twilio did it all for you!

This is not isolated to the Twilio environment by any means, as you can create HTTP requests to Twilio which will trigger your TwiML Bin. You can read more about that here .

Well, that’s all for today. Until next time, make peace not war ✌🏾.

Joseph Udonsak is a software engineer with a passion for solving challenges – be it building applications, or conquering new frontiers on Candy Crush. When he’s not staring at his screens, he enjoys a cold beer and laughs with his family and friends. Find him at LinkedIn , Medium , and Dev.to.