# Serverless Webhooks with Azure Functions and Node.js

[Serverless architectures](/docs/glossary/what-is-serverless-architecture) 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](https://azure.microsoft.com/en-us/services/functions/). Let's look at a practical application of Azure Functions by writing Node.js JavaScript code to handle [Twilio Webhooks](/docs/glossary/what-is-a-webhook) for incoming SMS messages and voice phone calls.

> \[!NOTE]
>
> Twilio can send your web application an HTTP request when certain events happen, such as an incoming text message to one of your Twilio phone numbers. These requests are called *webhooks*, or *status callbacks*. For more, check out our guide to [Getting Started with Twilio Webhooks](/docs/usage/webhooks/getting-started-twilio-webhooks). Find other webhook pages, such as a [security guide](/docs/usage/webhooks/webhooks-security) and an [FAQ](/docs/usage/webhooks/webhooks-faq) in the [Webhooks](/docs/usage/webhooks) section of the docs.

## 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](https://portal.azure.com/). Do this by clicking New, searching for "Function App" and selecting "Function App" from the list:

![Azure portal showing steps to create a function app: select Marketplace, search 'function app', and choose Function App.](https://docs-resources.prod.twilio.com/29d6ba60df970197bd5197c8759c17f1b48f437b608bd2a0ad95b342809d6936.png)

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

![Azure Function app setup with app name, subscription, resource group, hosting plan, location, and storage account.](https://docs-resources.prod.twilio.com/058cc6ca780c2b23043ba721876854221d576ff8703dc3ff783d9a16e0ce7649.png)

## 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:

![Select Webhook + API and JavaScript to create a function.](https://docs-resources.prod.twilio.com/45063e50bb2c00066ef799569902ff2c8b5a37aff69d1ddac87df87f30cd2681.png)

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 SDK

When Twilio calls your webhook, it is expecting a response in [TwiML](/docs/voice/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 SDK](https://github.com/twilio/twilio-node) 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:

```json title="package.json for Node.js Azure Functions" description="Customize the name, version, etc. for your project."
{
  "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"
  }
}

```

To create this file, click the button and then the 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 the button in the lower-left corner.
2. Click the 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:

```js title="Receive SMS with Node.js Azure Functions"
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();
};

```

Twilio will send [data about the incoming SMS as form parameters](/docs/messaging/twiml#twilios-request-to-your-application) 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 could put code to do any number of things such as call an external API or make use of [other Azure resources](https://docs.microsoft.com/en-us/azure/azure-functions/functions-overview#a-nameintegrationsaintegrations).

### 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:

![Node.js code snippet with highlighted Azure Function URL.](https://docs-resources.prod.twilio.com/1fb9bed61d7fff306d09ee311ccb3d46b59a5f94b8c272f394fe18299728c8d2.png)

Copy this URL to the clipboard. Next, open the [Twilio Console](/console) and [find the phone number](/console/phone-numbers/incoming) you want to use (or [buy a new number](/console/phone-numbers/search)). 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.)

![Messaging configuration with Webhooks and TwiML for incoming SMS via HTTP POST.](https://docs-resources.prod.twilio.com/033952a0ca45b93c79c496d85290c124b0bb3c82a4904c575138796ff155d3f8.png)

### 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 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](/console/dev-tools/debugger).

If you'd like to simulate a request from Twilio, you can use the button. Provide \[URL-encoded form parameters]\([https://en.wikipedia.org/wiki/POST\_(HTTP\\)#Use\_for\_submitting\_web\_forms](https://en.wikipedia.org/wiki/POST_\(HTTP\\\)#Use_for_submitting_web_forms)) 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](#write-a-function-to-respond-to-sms-messages) to create your function and reference the Twilio SDK.

### 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:

```js title="Receive Voice Calls with Node.js Azure Functions"
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();
};

```

Twilio will send [data about the incoming call as form parameters](/docs/messaging/twiml#twilios-request-to-your-application) 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 could put code to do any number of things such as call an external API or make use of [other Azure resources](https://docs.microsoft.com/en-us/azure/azure-functions/functions-overview#a-nameintegrationsaintegrations).

### 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:

![Node.js code snippet with highlighted Azure Function URL.](https://docs-resources.prod.twilio.com/1fb9bed61d7fff306d09ee311ccb3d46b59a5f94b8c272f394fe18299728c8d2.png)

Copy this URL to the clipboard. Next, open the [Twilio Console](/console) and [find the phone number](/console/phone-numbers/incoming) you want to use (or [buy a new number](/console/phone-numbers/search)). 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.)

![Voice configuration using Webhooks/TwiML and webhook URL for incoming calls.](https://docs-resources.prod.twilio.com/58720719ea529e364822c7fe601e1bf46b45a5d494b7693d6ab764d20a3521d6.png)

### 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 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](/console/dev-tools/debugger).

If you'd like to simulate a request from Twilio, you can use the button. Provide \[URL-encoded form parameters]\([https://en.wikipedia.org/wiki/POST\_(HTTP\\)#Use\_for\_submitting\_web\_forms](https://en.wikipedia.org/wiki/POST_\(HTTP\\\)#Use_for_submitting_web_forms)) in the "Request body" field and the click the "Run" button at the top of code editor.

## What's Next?

The [Azure Functions documentation](https://docs.microsoft.com/en-us/azure/azure-functions/) contains all you need to take your functions to the next level. Be sure to also refer to our [TwiML Reference](/docs/voice/twiml) for all that you can do with TwiML in your serverless webhooks. Ready to build? Check out our [tutorials](/docs) for Node.js... and some other great languages.

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