Serverless Webhooks with Azure Functions and Node.js

Serverless architectures allow developers to write code that runs in the cloud without running out to find web hosting. These applications can be very compute efficient and reduce costs by only running in response to events like API requests.

Microsoft Azure's offering for serverless code is called Azure Functions. Let's look at a practical application of Azure Functions by writing Node.js JavaScript code to handle Twilio Webhooks for incoming SMS messages and voice phone calls.

Create a New Azure Function App

To get started on the road to serverless bliss, you first need to create a new Function App in the Azure Portal. Do this by clicking New, searching for "Function App" and selecting "Function App" from the list:

Azure - Create function app

After clicking on "Function App," click the "Create" button. Provide an app name and other parameters to your preferences:

Azure - Function app details

Write a Function to Respond to SMS Messages

Create the Function

Bring up your new Function App in the Azure Portal. You should see the Quickstart page which will give you options for creating your first function. We want to use the "Webhook + API" scenario and choose JavaScript as our language:

Azure - Create JS function

Click "Create this function" and you'll be presented with the function editor, where you can start cutting some code.

Install the Twilio Node.js Helper Library

When Twilio calls your webhook, it is expecting a response in TwiML. Our JavaScript code will need to generate this TwiML, which is just standard XML. While we could create the XML in a string, the Twilio Helper Library provides classes to make it easy to build a valid TwiML response. Azure Functions allows installing npm packages and making them available to your functions. We need to create a package.json file with the following content:

Loading Code Samples...
Language
{
  "name": "twilio-azure-functions-sms-node",
  "version": "1.0.0",
  "description": "Receive SMS with Azure Functions and Node.js",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Twilio",
  "license": "MIT",
  "dependencies": {
    "twilio": "^3.0.0"
  }
}
Customize the name, version, etc. for your project.
package.json for Node.js Azure Functions

Customize the name, version, etc. for your project.

To create this file, click the View Files button and then the Add button. Name the file package.json. Paste the JSON into the code editor and Save the file.

Lastly, you need to run npm to install the packages:

  1. Click on Function app settings button in the lower-left corner.
  2. Click the Go to Kudu button button to bring up a console window.
  3. Navigate to the D:\home\site\wwwroot\[YourFunctionName] directory.
  4. Run the following command at the command prompt: npm install

Write the Message Handling Code

Now let's write the code that will handle the incoming text message. Switch back to your function code (click the function name and then select the index.js file) and paste the following JavaScript code into the editor:

Loading Code Samples...
Language
const qs = require("querystring");
const MessagingResponse = require('twilio').twiml.MessagingResponse;

module.exports = function (context, req) {
  context.log('JavaScript HTTP trigger function processed a request.');

  const formValues = qs.parse(req.body);

  const twiml = new MessagingResponse();
  twiml.message('You said: ' + formValues.Body);

  context.res = {
    status: 200,
    body: twiml.toString(),
    headers: { 'Content-Type': 'application/xml' },
    isRaw: true
  };

  context.done();
};
Receive SMS with Node.js Azure Functions

Twilio will send data about the incoming SMS as form parameters in the body of the POST request. This function has the code to parse out all of those parameters. You need only reference the name of the parameter you want such as formValues.Body for the body of the message or formValues.From for the phone number of the person sending the message (note the PascalCase of the parameters).

The output of the function is a properly formatted XML response containing the TwiML built by the twilio.Twiml.MessagingResponse builder. This function simply echoes back whatever message was sent, but you can see where you you could put code to do any number of things such as call an external API or make use of other Azure resources.

Configure the Message Webhook

Now we need to configure our Twilio phone number to call our Azure Function whenever a new text message comes in. To find the URL for your function, look for the Function Url label directly above the code editor in the Azure Portal:

Azure Function Node.js Url

Copy this URL to the clipboard. Next, open the Twilio Console and find the phone number you want to use (or buy a new number). On the configuration page for the number, scroll down to "Messaging" and next to "A MESSAGE COMES IN," select "Webhook" and paste in the function URL. (Be sure "HTTP POST" is selected, as well.)

Azure Functions Phone Number Config

Test the Message Webhook Function

Now send a text message to your Twilio phone number. If you texted "Hello", then you should get a reply back saying "You said: Hello". If there are any problems, you can use the Logs button in the Azure Function to see what error messages are happening on the server-side. To see errors on Twilio's side, use the Twilio Debugger.

If you'd like to simulate a request from Twilio, you can use the Test button. Provide url encoded form parameters in the "Request body" field and the click the "Run" button at the top of code editor.

Write a Node.js Function to Handle Phone Calls

Follow the same steps above to create your function and reference the Twilio Helper Library.

Write the Call Handling Code

Now let's write the code that will handle the incoming phone call. Switch back to your function code (click the function name and then select the index.js file) and paste the following JavaScript code into the editor:

Loading Code Samples...
Language
const qs = require("querystring");
const VoiceResponse = require('twilio').twiml.VoiceResponse;

module.exports = function (context, req) {
  context.log('JavaScript HTTP trigger function processed a request.');

  const formValues = qs.parse(req.body);
  // Insert spaces between numbers to aid text-to-speech engine
  const phoneNumber = formValues.From.replace(/\+/g, '').split('').join(' ');

  const twiml = new VoiceResponse();
  twiml.say('Your phone number is: ' + phoneNumber);

  context.res = {
    status: 200,
    body: twiml.toString(),
    headers: { 'Content-Type': 'application/xml' },
    isRaw: true
  };

  context.done();
};
Receive Voice Calls with Node.js Azure Functions

Twilio will send data about the incoming call as form parameters in the body of the POST request. This function has the code to parse out all of those parameters. You need only reference the name of the parameter you want such as formValues.From for the phone number of the person calling or formValues.CallSid for a unique identifier of the call (note the PascalCase of the parameters).

The output of the function is a properly formatted XML response containing the TwiML built by the twilio.twiml.VoiceResponse builder. This function simply tells the caller their phone number, but you can see where you you could put code to do any number of things such as call an external API or make use of other Azure resources.

Configure the Voice Webhook

Now we need to configure our Twilio phone number to call our Azure Function whenever a call comes in. To find the URL for your function, look for the Function Url label directly above the code editor in the Azure Portal:

Azure Function Node.js Url

Copy this URL to the clipboard. Next, open the Twilio Console and find the phone number you want to use (or buy a new number). On the configuration page for the number, scroll down to "Voice" and next to "A CALL COMES IN," select "Webhook" and paste in the function URL. (Be sure "HTTP POST" is selected, as well.)

Azure Functions Voice Config

Test the Voice Webhook Function

Now call your Twilio phone number. You should hear a voice saying "Your phone number is <123456>". If there are any problems, you can use the Logs button in the Azure Function to see what error messages are happening on the server-side. To see errors on Twilio's side, use the Twilio Debugger.

If you'd like to simulate a request from Twilio, you can use the Test button. Provide url encoded form parameters in the "Request body" field and the click the "Run" button at the top of code editor.

What's Next?

The Azure Functions documentation contains all you need to take your functions to the next level. Be sure to also refer to our TwiML Reference for all that you can do with TwiML in your serverless webhooks. Ready to build? Check out our guides or tutorials for Node.js... and some other great languages.

Now, get out there and enjoy your new serverless life!

David Prothero
Paul Kamp
Jose Oliveros
Agustin Camino
Kevin Whinnery

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
{
  "name": "twilio-azure-functions-sms-node",
  "version": "1.0.0",
  "description": "Receive SMS with Azure Functions and Node.js",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Twilio",
  "license": "MIT",
  "dependencies": {
    "twilio": "^3.0.0"
  }
}
const qs = require("querystring");
const MessagingResponse = require('twilio').twiml.MessagingResponse;

module.exports = function (context, req) {
  context.log('JavaScript HTTP trigger function processed a request.');

  const formValues = qs.parse(req.body);

  const twiml = new MessagingResponse();
  twiml.message('You said: ' + formValues.Body);

  context.res = {
    status: 200,
    body: twiml.toString(),
    headers: { 'Content-Type': 'application/xml' },
    isRaw: true
  };

  context.done();
};
const qs = require("querystring");
const VoiceResponse = require('twilio').twiml.VoiceResponse;

module.exports = function (context, req) {
  context.log('JavaScript HTTP trigger function processed a request.');

  const formValues = qs.parse(req.body);
  // Insert spaces between numbers to aid text-to-speech engine
  const phoneNumber = formValues.From.replace(/\+/g, '').split('').join(' ');

  const twiml = new VoiceResponse();
  twiml.say('Your phone number is: ' + phoneNumber);

  context.res = {
    status: 200,
    body: twiml.toString(),
    headers: { 'Content-Type': 'application/xml' },
    isRaw: true
  };

  context.done();
};