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:
exports.handler
method that your code defines, and provide the context
, event
, and callback
parameters, in addition to a selection of useful global utility methods.callback()
method in order to emit your response. After executing the callback()
method, your Twilio Function execution will be terminated. This includes any asynchronous processes that may still be executing.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.
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 |
Twilio Function Handler Method Boilerplate
1exports.handler = (context, event, callback) => {2// Your application logic34// To emit a response and stop execution, call the callback() method5return callback();6}
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.
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. |
Example of using built-in Twilio REST Helper
1exports.handler = (context, event, callback) => {2// Access the pre-initialized Twilio REST client3const twilioClient = context.getTwilioClient();45// Determine message details from the incoming event, with fallback values6const from = event.From || '+15095550100';7const to = event.To || '+15105550101';8const body = event.Body || 'Ahoy, World!';910twilioClient.messages11.create({ to, from, body })12.then((result) => {13console.log('Created message using callback');14console.log(result.sid);15return callback();16})17.catch((error) => {18console.error(error);19return callback(error);20});21};
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.
Example of how to access the Default Environment Variables
1exports.handler = (context, event, callback) => {2// Check to see if the Domain name is null3const domain = context.DOMAIN_NAME || 'No Domain available';4// Respond with the Domain hosting this Function5return callback(null, domain);6};
Example of how to access Environment Variables
1exports.handler = (context, event, callback) => {2// Get the primary and secondary phone numbers, if set3const primary = context.PRIMARY_PHONE_NUMBER || 'There is no primary number';4const secondary = context.SECONDARY_PHONE_NUMBER || 'There is no secondary number!';56// Build our response object7const response = {8phone_numbers: {9primary,10backup: secondary,11},12};1314// Return the response object as JSON15return callback(null, response);16};
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
.
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:
1{2"ToCountry": "US",3"ToState": "CA",4"SmsMessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",5"NumMedia": "0",6"ToCity": "BOULEVARD",7"FromZip": "",8"SmsSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",9"FromState": "WA",10"SmsStatus": "received",11"FromCity": "",12"Body": "Ahoy!",13"FromCountry": "US",14"To": "+15555555555",15"ToZip": "91934",16"NumSegments": "1",17"MessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",18"AccountSid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",19"From": "+14444444444",20"ApiVersion": "2010-04-01",21"request": {22"headers": { ... },23"cookies": { ... }24},25}
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
.
Example of how to access webhook values by name from the event object in a Function
1exports.handler = (context, event, callback) => {2// Prepare a new messaging response object; no need to import Twilio3const twiml = new Twilio.twiml.MessagingResponse();4// Access incoming text information like the from number and contents off of `event`5// Access environment variables and other runtime data from `context`6twiml.message({ to: context.MY_NUMBER }, `${event.From}: ${event.Body}`);7// Remember to return the TwiML as the second argument to `callback`8return callback(null, twiml);9};
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:
1{2"firstName": "Rick",3"age": "42",4"request": {5"headers": { ... },6"cookies": { ... }7}8}
Similarly, given a POST
request with query parameters, a JSON body, or both such as:
1curl -L -X POST 'https://http-7272.twil.io/response?age=42&firstName=Rick' \2-H 'Content-Type: application/json' \3--data-raw '{4"color": "orange"5}'
the Function of the receiving end will then have access to an event
object with these contents:
1{2"firstName": "Rick",3"age": "42",4"color": "orange",5"request": {6"headers": { ... },7"cookies": { ... }8}9}
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.
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.
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.
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.
Example of how to appropriately use callback() with an asynchronous HTTP request
1exports.handler = (context, event, callback) => {2// Fetch the already initialized Twilio REST client3const client = context.getTwilioClient();45// Determine message details from the incoming event, with fallback values6const from = event.From || '+15095550100';7const to = event.To || '+15105550101';8const body = event.Body || 'Ahoy, World!';910client.messages11.create({ to, from, body })12.then((result) => {13console.log('Created message using callback');14console.log(result.sid);15// Callback is placed inside the successful response of the request16return callback();17})18.catch((error) => {19console.error(error);20// Callback is also used in the catch handler to end execution on errors21return callback(error);22});2324// If you were to place the callback() function here, instead, then the process would25// terminate before your API request to create a message could complete.26};
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. |
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);
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.
Example of how to return an error message with HTTP 500 Error
1exports.handler = (context, event, callback) => {2// Providing a single string or an Error object will result in a 500 Error3return callback('Something went very, very wrong.');4};
Example of how to return an empty HTTP 200 OK
1exports.handler = (context, event, callback) => {2// Providing neither error nor response will result in a 200 OK3return callback();4};
Example of how to return plaintext with HTTP 200 OK
1exports.handler = (context, event, callback) => {2// Providing a string will result in a 200 OK3return callback(null, 'This is fine');4};
Example of how to return JSON in HTTP 200 OK
1exports.handler = (context, event, callback) => {2// Construct an object in any way3const response = { result: 'winner winner!' };4// A JavaScript object as a response will be serialized to JSON and returned5// with the Content-Type header set to "application/json" automatically6return callback(null, response);7};
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)
1exports.handler = (context, event, callback) => {2// Create a new messaging response object3const twiml = new Twilio.twiml.MessagingResponse();4// Use any of the Node.js SDK methods, such as `message`, to compose a response5twiml.message('Hello, World!');6// Return the TwiML as the second argument to `callback`7// This will render the response as XML in reply to the webhook request8return callback(null, twiml);9};
1exports.handler = (context, event, callback) => {2// Create a new voice response object3const twiml = new Twilio.twiml.VoiceResponse();4// Webhook information is accessible as properties of the `event` object5const city = event.FromCity;6const number = event.From;78// You can optionally edit the voice used, template variables into your9// response, play recorded audio, and more10twiml.say({ voice: 'alice' }, `Never gonna give you up, ${city || number}`);11twiml.play('https://demo.twilio.com/docs/classic.mp3');12// Return the TwiML as the second argument to `callback`13// This will render the response as XML in reply to the webhook request14return callback(null, twiml);15};
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.
The Twilio
class is accessible at any time. This is commonly used to initialize TwiML or Access Tokens for your Function responses. For example:
1// Initialize TwiML without needing to import Twilio2const response = new Twilio.twiml.MessagingResponse();34// Similarly for other utilities, such as Access Tokens5const AccessToken = Twilio.jwt.AccessToken;6const SyncGrant = AccessToken.SyncGrant;
The Runtime Client is accessible via Runtime
, and exposes helper methods for accessing private Assets, other Functions, and the Sync client. For example:
1const text = Runtime.getAssets()['/my-file.txt'].open();2console.log('Your file contents: ' + text);
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:
1// No need to import Twilio; it is globally available in Functions2const response = new Twilio.Response();
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 |
Example of setting a Status Code using Twilio Response
1exports.handler = (context, event, callback) => {2// No need to import Twilio; it is globally available in Functions3const response = new Twilio.Response();45// Set the status code to 204 Not Content6response.setStatusCode(204);78return callback(null, response);9};
Example of building a plaintext response with Twilio Response
1exports.handler = (context, event, callback) => {2// No need to import Twilio; it is globally available in Functions3const response = new Twilio.Response();45response6// Set the status code to 200 OK7.setStatusCode(200)8// Set the response body9.setBody('This is fine');1011return callback(null, response);12};
Example of building a JSON response with Twilio Response
1exports.handler = (context, event, callback) => {2// No need to import Twilio; it is globally available in Functions3const response = new Twilio.Response();45response6// Set the status code to 200 OK7.setStatusCode(200)8// Set the Content-Type Header9.appendHeader('Content-Type', 'application/json')10// Set the response body11.setBody({12everything: 'is alright',13});1415return callback(null, response);16};
Example of setting an header using Twilio Response
1exports.handler = (context, event, callback) => {2// No need to import Twilio; it is globally available in Functions3const response = new Twilio.Response();45response6// Set the status code to 301 Redirect7.setStatusCode(301)8// Set the Location header for redirect9.appendHeader('Location', 'https://twilio.com');1011return callback(null, response);12};
Example of setting multiple headers using Twilio Response
1exports.handler = (context, event, callback) => {2// No need to import Twilio; it is globally available in Functions3const response = new Twilio.Response();45// Build a mapping of headers as a way to set many with one command6const headers = {7'Access-Control-Allow-Origin': 'example.com',8'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',9'Access-Control-Allow-Headers': 'Content-Type',10};1112// Set headers in response13response.setHeaders(headers);1415return callback(null, response);16};
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)!