Function Execution
The Twilio Function runtime environment is lightweight by design to provide developers with all the flexibility they need. Read on to learn about how your code is executed, what variables and tools this environment provides, and ways you could create a valid response.
During Function invocation, the following steps occur:
- Environment Bootstrap – The Twilio Function environment is bootstrapped, and any resources your Function code may rely on are quickly initialized.
- Handler Execution – The Twilio Environment will then execute the
exports.handler
method that your code defines, and provide thecontext
,event
, andcallback
parameters, in addition to a selection of useful global utility methods. - Response Emitted – When your Twilio Function code has completed, your code must call the
callback()
method in order to emit your response. After executing thecallback()
method, your Twilio Function execution will be terminated. This includes any asynchronous processes that may still be executing.
Handler Method
The handler
method is the interface between Twilio Functions and your application logic. You can think of the handler
method as the entry point to your application. This is somewhat analogous to a main()
function in Java or __init__
in Python.
Twilio Functions will execute your handler
method when it is ready to hand off control of execution to your application logic. If your Function Code does not contain a handler
method, Twilio Functions will be unable to execute your logic and will emit an HTTP 500 error.
Handler Arguments
Argument | Type | Description |
---|---|---|
context |
object |
Provides information about the current execution environment |
event |
object |
Contains the request parameters passed into your Twilio Function |
callback |
function |
Function used to complete execution and emit responses |
Context Object
Twilio Functions provides the context
object as an interface between the current execution environment and the handler
method. The context
object provides access to helper methods, as well as your Environment Variables.
Helper Methods
The context
object provides helper methods that pre-initialize common utilities and clients that you might find useful when building your application. These helper methods extract all their required configuration from Environment Variables.
Method | Type | Description |
---|---|---|
getTwilioClient() |
Twilio REST Helper | If you have enabled the inclusion of your account credentials in your Function, this will return an initialized Twilio REST Helper Library. If you have not included account credentials in your Function, calling this method will result in an error. If your code doesn’t catch this error, it will result in an HTTP 500 response. |
Environment Variables
We encourage developers to use Environment Variables to separate their code from configuration. Using Environment Variables ensures that your code is portable, and that simple configuration changes can be made instantly.
For a more in-depth explanation and examples, refer to the Environment Variables documentation.
Event Object
The event
object contains the request parameters and headers being passed into your Function. Both POST and GET parameters will be collapsed into the same object. For POST requests, you can pass either form encoded parameters or JSON documents; both will be collapsed into the event
object.
The specific values that you'll be able to access on event
are dependent on what context your Function is being used in and what parameters it is receiving. We'll cover some common use cases and general scenarios below, so you can get the most out of event
.
Webhook parameters
If you have configured your Function to act as the webhook for an action, such as an incoming SMS or phone call, event
will contain a very specific set of values related to the phone number in question. These will be values such as event.From
, which resolves to the E.164 formatted phone number as a string, event.Body
, which returns the text message of an incoming SMS, and many more. For example, an incoming message will result in event
having this shape:
{
"ToCountry": "US",
"ToState": "CA",
"SmsMessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"NumMedia": "0",
"ToCity": "BOULEVARD",
"FromZip": "",
"SmsSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"FromState": "WA",
"SmsStatus": "received",
"FromCity": "",
"Body": "Ahoy!",
"FromCountry": "US",
"To": "+15555555555",
"ToZip": "91934",
"NumSegments": "1",
"MessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"AccountSid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"From": "+14444444444",
"ApiVersion": "2010-04-01",
"request": {
"headers": { ... },
"cookies": { ... }
},
}
Refer to the dedicated Messaging and Voice Webhook documentation to learn the full list of properties which you can leverage in your Functions.
Webhook properties are always in PascalCase; check to make sure that you have capitalized the first letter of commonly used variables, such as From
.
Parameters from HTTP requests
If your Function is being executed in response to an incoming HTTP request, then the contents of event
will directly correspond to the request's query parameters and request body (if any).
For example, given a Function with the URL of http-7272.twil.io/response
and this request:
curl -X GET 'https://http-7272.twil.io/response?age=42&firstName=Rick'
The resulting event object will be:
{
"firstName": "Rick",
"age": "42",
"request": {
"headers": { ... },
"cookies": { ... }
}
}
Similarly, given a POST request with query parameters, a JSON body, or both such as:
curl -L -X POST 'https://http-7272.twil.io/response?age=42&firstName=Rick' \
-H 'Content-Type: application/json' \
--data-raw '{
"color": "orange"
}'
the Function of the receiving end will then have access to an event
object with these contents:
{
"firstName": "Rick",
"age": "42",
"color": "orange",
"request": {
"headers": { ... },
"cookies": { ... }
}
}
In the case of a POST request, query parameters and any JSON in the body of the request will be merged into the same object. If a property such as age
is defined in both parts of the request, the value defined in the JSON body takes precedence and will overwrite the initial value from the query parameters in event
.
You might have noticed that event
also contains a request
object with headers
and cookies
that aren't explicitly part of the request(s). To learn more about this aspect of event
and how you can leverage request headers and cookies, refer to the accessing headers and cookies documentation.
Parameters from the Run Function Widget
Similar to a direct HTTP request, a Run Function widget is invoking a Function, that Function's event
will be populated by any arguments specified in the configuration of that particular Run Function widget.
Refer to the Use the Run Function widget in Studio example to see what this looks like in practice when combining Functions and Studio Flows.
Callback Function
When you have finished processing your request, you need to invoke the callback
function to emit a response and signal that your Function has completed its execution. The callback
method will automatically determine the data type of your response and serialize the output appropriately.
You must invoke the callback
method when your Function is done processing. Failure to invoke callback
will cause your Function to continue running up to the 10-second execution time limit. When your Function reaches the execution time limit, it will be terminated, and a 504 Gateway timeout error will be returned to the client.
Callback and Asynchronous Limitations
It is important to note that when the callback
function is invoked, it will terminate all execution of your Function. This includes any asynchronous processes you may have kicked off during the execution of your handler
method.
For this reason, if you are using libraries that are natively asynchronous and/or operate using Promises, you must properly handle this asynchronous behavior. Structure your code to call callback
within the correct callback methods, .then
chains, or after await
in async
functions.
Callback Arguments
Argument | Type | Description |
---|---|---|
error |
string|null |
Error indicating what problem was encountered during execution. Defining this value (as anything but null or undefined ) will result in the client receiving a HTTP 500 response with the provided payload. |
response |
string|object|null |
Successful response generated by the Function. Providing this argument will result in the client receiving a HTTP 200 response containing the provided value. |
How do I return an error?
If you have encountered an exception in your code or otherwise want to indicate an error state, invoke the callback
method with the error object or intended message as a single parameter:
return callback(error);
How do I return a successful response?
To signal success and return a value, pass a falsy value such as null
or undefined
as the first parameter to callback
, and your intended response as the second parameter:
return callback(null, response);
Please note that all samples demonstrate using the return
keyword before calling callback
. This is to prevent subsequent code from unintentionally running before handler
is terminated, or from calling callback
multiple times, and is considered a best practice when working with Functions.
How do I return TwiML?
In addition to the standard response types, Functions has built-in support to allow you to quickly generate and return TwiML for your application's needs.
This is such a common use case that callback
directly accepts valid TwiML objects, such as MessagingResponse
and VoiceResponse
, as the second argument. If you return TwiML in this way, the environment will automatically convert your response to XML without any extra work required on your part. (Such as stringifying the TwiML and specifying a response content type)
Global classes
In addition to the values and helpers available through the context
, event
, and callback
parameters, you have access to some globally-scoped helper classes that you can access without needing to import any new Dependencies.
Twilio
The Twilio
class is accessible at any time. This is commonly used to initialize TwiML or Access Tokens for your Function responses. For example:
// Initialize TwiML without needing to import Twilio
const response = new Twilio.twiml.MessagingResponse();
// Similarly for other utilities, such as Access Tokens
const AccessToken = Twilio.jwt.AccessToken;
const SyncGrant = AccessToken.SyncGrant;
Runtime
The Runtime Client is accessible via Runtime
, and exposes helper methods for accessing private Assets, other Functions, and the Sync client. For example:
const text = Runtime.getAssets()['/my-file.txt'].open();
console.log('Your file contents: ' + text);
Constructing a Response
In some instances, your Function may need greater control over the response it is going to emit. For those instances, you can use the Twilio Response object that is available in the global scope of your Function by default. No need to import Twilio yourself!
By using the Twilio Response object, you will be able to specify the status code, headers, and body of your response. You can begin constructing a custom response by creating a new Twilio Response object, like so:
// No need to import Twilio; it is globally available in Functions
const response = new Twilio.Response();
Twilio Response Methods
Method | Return Type | Description |
---|---|---|
setStatusCode(int) |
self |
Sets the status code in the HTTP response |
setBody(mixed) |
self |
Sets the body of the HTTP response. Takes either an object or string. When setting the body to anything other than text, make sure to set the corresponding Content-Type header with appendHeader() |
appendHeader(string, string) |
self |
Adds a header to the HTTP response. The first argument specifies the header name and the second argument the header value |
setHeaders(object) |
self |
Sets all of the headers for the HTTP response. Takes an object mapping the names of the headers to their respective values |
What's next?
By now, you should have a pretty good idea of what goes into writing a Function. (Although there are plenty of specifics and examples yet to learn)
The next important step in your journey is to understand the concept of visibility, and how it affects access to and use of your Functions (and Assets)!
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 by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.