Twilio Functions provide a complete runtime environment for executing your Node.js scripts. Functions integrates popular package managers like NPM, and provides a low latency Twilio-hosted environment for your application. Read on for more information on how to use Functions with your Twilio project.
- Node.js versions
- Building apps with Functions
- What information is in the context object?
- What information is the in the event object?
- How do I use the callback to return from a Function?
- How do I generate TwiML?
- How do I call 3rd party HTTP APIs?
Node.js versions
All new or modified Functions scripts default to Node 18.
Notice: Any Functions created or deployed from Console will continue to run on their current Node. If these scripts are modified and redeployed, they will move to Node 18. For full details, please see Runtime Node Upgrade.
Building apps with Functions
Here's an example of what a Functions script looks like:
exports.handler = function(context, event, callback) {
// code
// invoke callback function
}
The handler
method is the starting point of your function, and accepts the following 3 arguments:
- The
context
object includes information about your Runtime, such as configuration variables. - The
event
object includes information about a specific invocation, including HTTP parameters from the HTTP request. - The
callback
Function completes execution of your code.
When writing code for your Function, you can reference the Twilio Node helper library using the Twilio
global:
const twiml = new Twilio.twiml.MessagingResponse()
What information is in the Context object?
On the Functions Configuration page in Console, you can configure environmental variables for your app. These key/value pairs are attached to the context parameter.
For example, setting the following key value pairs:
Results in this context object response:
{
NAME: 'Phil',
CITY: 'London'
}
You can also allow your project credentials (Account Sid and Auth Token) to be accessible via the context object. This enables you to invoke the getTwilioClient
method on the context object for a fully-initialized Twilio REST API client.
const client = context.getTwilioClient()
client.messages.create({to: '+12025551212', from: '+12065551212', body: "hello world!"})
For more details, please see Enable and Configure Credentials and Environmental Variables with Twilio Functions.
What information is the in the Event object?
GET and POST parameters are attached to the event object. For instance, if an HTTP request to your Function looked like this:
curl -XPOST -d "c=d" https://your-domain-1234.twil.io/path?a=b
The event object would look like this:
{
a: 'b',
c: 'd'
}
If a POST parameter and GET parameter have the same name, the POST parameter will take precedence.
How do I use the Callback to return from a Function?
When you're ready to return from your Function, you invoke callback. In non-error situations the first parameter is null and the second parameter is the value you want to return.
If you return a TwiML object, Functions will ensure that this is turned into XML and content-type is set to text/xml
.
const twiml = new Twilio.twiml.MessagingResponse()
callback(null, twiml)
If you return a JavaScript object, Functions will convert to JSON and set the content-type to application/json
.
callback(null, {token: "abcdef"})
If you return a String, Functions will return a String and set the content-type to text/plain.
callback(null, "OK")
If you return a String as the first parameter, Functions will return the string as text/plain
and set the response code to HTTP 500.
callback("NOT OK")
How do I generate TwiML?
If you're building Voice or SMS applications, you'll often want to generate TwiML. There are two kinds of TwiML: Voice TwiML and Messaging TwiML. You can use the Twilio Node helper library to programmatically generate both of these kinds of TwiML.
Voice TwiML
const twiml = new Twilio.twiml.VoiceResponse()
twiml.dial().sip("sip:jack@example.com")
console.log(twiml.toString())
//<Response><Dial><Sip>sip:jack@example.com</Sip></Dial></Response>
Messaging TwiML
const twiml = new Twilio.twiml.MessagingResponse()
twiml.message("Hello SMS")
console.log(twiml.toString())
// <Response><Message>Hello SMS</Message></Response>
How do I call 3rd party REST APIs?
If you want to use 3rd party REST APIs in your Functions, we recommend adding the Got NPM module. For help adding this modules in Functions, see Add or Modify Node Modules with Twilio Functions.
Here's an example of using Got to make a GET request:
const got = require('got');
got('https://your-api.com/endpoint', {responseType: 'json'})
.then(function(response) {
console.log(response)
twiml.message(response.body.results[0].url)
callback(null, twiml);
})
.catch(function(error) {
callback(error)
});
Sometimes you'll want to POST data to an API. Here is an example of sending a POST with a JSON payload and setting the Accept header to application/json
:
const got = require('got');
const requestPayload = {foo: 'bar'};
got.post('https://your-api.com/endpoint',
{ body: JSON.stringify(requestPayload),
headers: {
'accept': 'application/json'
},
json: true
}).then(function(response) {
console.log(response.body)
callback(null, response.body);
}).catch(function(error) {
callback(error)
});
Note: Due to the asynchronous nature of Node, please remember to execute your callback only after your HTTP request has finished. Executing callback terminates the execution of your Function, including any in-flight async code.