To avoid potential issues, we highly suggest that you update your twilio dependency to the latest version before running any of these code samples.
All Functions execute with a pre-initialized instance of the Twilio Node.js SDK available for use. This means you can access and utilize any Twilio helper library method in your Function. For example, you can use a Function to make outbound phone calls via Programmable Voice as we'll show in the following example snippets.
These examples are not exhaustive, and we encourage you to peruse the Programmable Voice documentation for more inspiration on what you can build.
Before you start, be sure to complete the following prerequisites. You can skip to "Create and host a Function" if you've already completed these steps and need to know more about Function deployment and invocation, or you can skip all the way to "Make an outbound call" if you're all ready to go and want to get straight to the code.
In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:
If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:
https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
test-function-3548.twil.io/hello-world
.
Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!
Functions created in the UI are Protected by default, and we highly recommend you to set Functions deployed via the Serverless Toolkit to protected
as well by prepending protected
before the file extension, for example: send-sms.protected.js
. This will help secure your Function and protect it from being accessed by bad actors. However, this also adds an extra layer of complexity if you want to manually invoke and test code, such as the examples on this page.
In order to successfully call your protected
Function, you will need to provide a valid X-Twilio-Signature
header in your request. You can learn more about the request validation process, but in the meantime, let's get started with some code that will get you up and running fast.
While it's possible to generate the header yourself using HMAC-SHA1, we highly recommend you use the convenience utilities exported by Twilio's Helper Libraries to perform this operation. Head over to the libraries page to download the library for your language of choice.
Once you have the library of your choice installed, you'll need to:
X-Twilio-Signature
for use in the next step.
Here are two examples for if you want to generate a signature for a POST
request which includes JSON, or a GET
request that communicates its data as query parameters instead:
_21const { getExpectedTwilioSignature } = require('twilio/lib/webhooks/webhooks');_21_21// Retrieve your auth token from the environment instead of hardcoding_21const authToken = process.env.TWILIO_AUTH_TOKEN;_21_21// Use the Twilio helper to generate your valid signature!_21// The 1st argument is your Twilio auth token._21// The 2nd is the full URL of your Function._21// The 3rd is any application/x-www-form-urlencoded data being sent, which is none!_21const xTwilioSignature = getExpectedTwilioSignature(_21 authToken,_21 'https://example-4321.twil.io/sms/send',_21 {} // <- Leave this empty if sending request data via JSON_21);_21_21// Print the signature to the console for use with your_21// preferred HTTP client_21console.log('xTwilioSignature: ', xTwilioSignature);_21_21// For example, the output will look like this:_21// xTwilioSignature: coGTEaFEMv8ejgNGtgtUsbL8r7c=
Once you've generated a valid X-Twilio-Signature
value, it's time to use this as a header in a request to your Function. You can do so using a variety of tools, such as curl, Postman, and more. Be sure to:
X-Twilio-Signature
header and content type header (
application/json
) for your request.
Using curl, the example request above would look like this:
_10curl -X POST 'http://test-4321.twil.io/sms/send' \_10 -H 'X-Twilio-Signature: coGTEaFEMv8ejgNGtgtUsbL8r7c=' \_10 -H 'Content-Type: application/json' \_10 --data-raw '{_10 "Body": "Hello, there!"_10 }'
For any Function using the built-in Twilio client, the "Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV" option on the Settings > Environment Variables tab must be enabled.
You can use a Function to make a call from your Twilio phone number via Programmable Voice. The to
and from
parameters of your call must be specified to successfully send, and valid TwiML must be provided either via the url
or twiml
parameters.
You'll tell Twilio which phone number to use to make this call by either providing a From
value in your request, or by omitting it and replacing the placeholder default value in the example code with your own Twilio phone number.
Next, specify yourself as the call recipient by either providing a To
value in your request, or by omitting it and replacing the default value in the example code with your personal number. The resulting from
and to
values both must use E.164 formatting ("+
" and a country code, e.g., +16175551212
).
Finally, the url
or twiml
value determines the contents of the call that is being sent. As with the other values, either pass in the respective value in your request to this Function or override the default in the example to your own custom value.
Once you've made any modifications to the sample and have deployed your Function for testing, go ahead and make some test HTTP requests against it to get a call to your phone! Example code for invoking your Function is described earlier in this document.
Twilio will retrieve the TwiML from the provided URL and use it to handle the call
_27exports.handler = function (context, event, callback) {_27 // The pre-initialized Twilio client is available from the `context` object_27 const twilioClient = context.getTwilioClient();_27_27 // Query parameters or values sent in a POST body can be accessed from `event`_27 const from = event.From || '+15017122661';_27 const to = event.To || '+15558675310';_27 // Note that TwiML can be hosted at a URL and accessed by Twilio_27 const url = event.Url || 'http://demo.twilio.com/docs/voice.xml';_27_27 // Use `calls.create` to place a phone call. Be sure to chain with `then`_27 // and `catch` to properly handle the promise and call `callback` _after_ the_27 // call is placed successfully!_27 twilioClient.calls_27 .create({ to, from, url })_27 .then((call) => {_27 console.log('Call successfully placed');_27 console.log(call.sid);_27 // Make sure to only call `callback` once everything is finished, and to pass_27 // null as the first parameter to signal successful execution._27 return callback(null, `Success! Call SID: ${call.sid}`);_27 })_27 .catch((error) => {_27 console.error(error);_27 return callback(error);_27 });_27};
Directly provide TwiML instructions for how to handle the call
_27exports.handler = function (context, event, callback) {_27 // The pre-initialized Twilio client is available from the `context` object_27 const twilioClient = context.getTwilioClient();_27_27 // Query parameters or values sent in a POST body can be accessed from `event`_27 const from = event.From || '+15017122661';_27 const to = event.To || '+15558675310';_27 // Note that the provided TwiML can be serialized as a string and sent!_27 const twiml = event.Twiml || '<Response><Say>Ahoy there!</Say></Response>';_27_27 // Use `calls.create` to place a phone call. Be sure to chain with `then`_27 // and `catch` to properly handle the promise and call `callback` _after_ the_27 // call is placed successfully!_27 twilioClient.calls_27 .create({ to, from, twiml })_27 .then((call) => {_27 console.log('Call successfully placed');_27 console.log(call.sid);_27 // Make sure to only call `callback` once everything is finished, and to pass_27 // null as the first parameter to signal successful execution._27 return callback(null, `Success! Call SID: ${call.sid}`);_27 })_27 .catch((error) => {_27 console.error(error);_27 return callback(error);_27 });_27};
When making an outgoing call, you can tell Twilio to record the entire call from beginning to end. Add the record
argument to your call to calls.create()
, set it to true
, and Twilio will record the full call on your behalf.
Once the call is complete, you can listen to your recordings either in the Twilio Console, or access them directly via the REST API for Recordings.
_28exports.handler = function (context, event, callback) {_28 // The pre-initialized Twilio client is available from the `context` object_28 const twilioClient = context.getTwilioClient();_28_28 // Query parameters or values sent in a POST body can be accessed from `event`_28 const from = event.From || '+15017122661';_28 const to = event.To || '+15558675310';_28 // Note that TwiML can be hosted at a URL and accessed by Twilio_28 const url = event.Url || 'http://demo.twilio.com/docs/voice.xml';_28_28 // Use `calls.create` to place a phone call. Be sure to chain with `then`_28 // and `catch` to properly handle the promise and call `callback` _after_ the_28 // call is placed successfully!_28 // Note the addition of the `record` configuration flag for `calls.create`_28 twilioClient.calls_28 .create({ to, from, record: true, url })_28 .then((call) => {_28 console.log('Call successfully placed');_28 console.log(call.sid);_28 // Make sure to only call `callback` once everything is finished, and to pass_28 // null as the first parameter to signal successful execution._28 return callback(null, `Success! Call SID: ${call.sid}`);_28 })_28 .catch((error) => {_28 console.error(error);_28 return callback(error);_28 });_28};