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

1. **Environment Bootstrap -** The Twilio Function environment is bootstrapped, and any resources your Function code may rely on are quickly initialized.
2. **Handler Execution** **-** The Twilio Environment will then execute the `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.
3. **Response Emitted** **-** When your Twilio Function code has completed, your code must call the `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.

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

```js title="Handler Method Boilerplate" description="Twilio Function Handler Method Boilerplate"
exports.handler = (context, event, callback) => {
  // Your application logic

  // To emit a response and stop execution, call the callback() method
  return callback();
};
```

## 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 SDK](https://github.com/twilio/twilio-node). 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. |

```js title="Use built-in Twilio REST Helper to send an SMS Message" description="Example of using built-in Twilio REST Helper"
exports.handler = (context, event, callback) => {
  // Access the pre-initialized Twilio REST client
  const twilioClient = context.getTwilioClient();

  // Determine message details from the incoming event, with fallback values
  const from = event.From || "+15095550100";
  const to = event.To || "+15105550101";
  const body = event.Body || "Ahoy, World!";

  twilioClient.messages
    .create({ to, from, body })
    .then((result) => {
      console.log("Created message using callback");
      console.log(result.sid);
      return callback();
    })
    .catch((error) => {
      console.error(error);
      return callback(error);
    });
};
```

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

```js title="Retrieve Domain from Default Environment Variables" description="Example of how to access the Default Environment Variables"
exports.handler = (context, event, callback) => {
  // Check to see if the Domain name is null
  const domain = context.DOMAIN_NAME || "No Domain available";
  // Respond with the Domain hosting this Function
  return callback(null, domain);
};
```

```js title="Retrieve Environment Variables" description="Example of how to access Environment Variables"
exports.handler = (context, event, callback) => {
  // Get the primary and secondary phone numbers, if set
  const primary = context.PRIMARY_PHONE_NUMBER || "There is no primary number";
  const secondary =
    context.SECONDARY_PHONE_NUMBER || "There is no secondary number!";

  // Build our response object
  const response = {
    phone_numbers: {
      primary,
      backup: secondary,
    },
  };

  // Return the response object as JSON
  return callback(null, response);
};
```

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

```json
{
  "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](/docs/messaging/guides/webhook-request#parameters-in-twilios-request-to-your-application) and [Voice](/docs/voice/twiml#request-parameters) Webhook documentation to learn the full list of properties which you can leverage in your Functions.

> \[!NOTE]
>
> Webhook properties are always in
> [PascalCase](https://en.wikipedia.org/wiki/Camel_case#:~:text=PascalCase%20for%20upper%20camel%20case);
> check to make sure that you have capitalized the first letter of commonly used
> variables, such as `From`.

```js title="Access webhook values from event" description="Example of how to access webhook values by name from the event object in a Function"
// !mark(6)
exports.handler = (context, event, callback) => {
  // Prepare a new messaging response object; no need to import Twilio
  const twiml = new Twilio.twiml.MessagingResponse();
  // Access incoming text information like the from number and contents off of `event`
  // Access environment variables and other runtime data from `context`
  twiml.message({ to: context.MY_NUMBER }, `${event.From}: ${event.Body}`);
  // Remember to return the TwiML as the second argument to `callback`
  return callback(null, twiml);
};
```

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

```bash
curl -X GET 'https://http-7272.twil.io/response?age=42&firstName=Rick'
```

The resulting event object will be:

```json
{
  "firstName": "Rick",
  "age": "42",
  "request": {
    "headers": { ... },
    "cookies": { ... }
  }
}
```

Similarly, given a `POST` request with query parameters, a JSON body, or both such as:

```bash
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:

```json
{
  "firstName": "Rick",
  "age": "42",
  "color": "orange",
  "request": {
    "headers": { ... },
    "cookies": { ... }
  }
}
```

> \[!WARNING]
>
> 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`.

> \[!NOTE]
>
> 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](/docs/serverless/functions-assets/functions/headers-and-cookies/access)
> 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), 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.

```js title="Complete Execution with Asynchronous HTTP Request" description="Example of how to appropriately use callback() with an asynchronous HTTP request"
exports.handler = (context, event, callback) => {
  // Fetch the already initialized Twilio REST client
  const client = context.getTwilioClient();

  // Determine message details from the incoming event, with fallback values
  const from = event.From || "+15095550100";
  const to = event.To || "+15105550101";
  const body = event.Body || "Ahoy, World!";

  client.messages
    .create({ to, from, body })
    .then((result) => {
      console.log("Created message using callback");
      console.log(result.sid);
      // Callback is placed inside the successful response of the request
      return callback();
    })
    .catch((error) => {
      console.error(error);
      // Callback is also used in the catch handler to end execution on errors
      return callback(error);
    });

  // If you were to place the callback() function here, instead, then the process would
  // terminate before your API request to create a message could complete.
};
```

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

```javascript
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:

```javascript
return callback(null, response);
```

> \[!NOTE]
>
> 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.

```js title="Return an Error Response" description="Example of how to return an error message with HTTP 500 Error"
exports.handler = (context, event, callback) => {
  // Providing a single string or an Error object will result in a 500 Error
  return callback("Something went very, very wrong.");
};
```

```js title="Return a Simple Successful Response" description="Example of how to return an empty HTTP 200 OK"
exports.handler = (context, event, callback) => {
  // Providing neither error nor response will result in a 200 OK
  return callback();
};
```

```js title="Return a Successful Plaintext Response" description="Example of how to return plaintext with HTTP 200 OK"
exports.handler = (context, event, callback) => {
  // Providing a string will result in a 200 OK
  return callback(null, "This is fine");
};
```

```js title="Return a Successful JSON Response" description="Example of how to return JSON in HTTP 200 OK"
exports.handler = (context, event, callback) => {
  // Construct an object in any way
  const response = { result: "winner winner!" };
  // A JavaScript object as a response will be serialized to JSON and returned
  // with the Content-Type header set to "application/json" automatically
  return callback(null, response);
};
```

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

```js title="Return a static Messaging response to incoming text messages"
exports.handler = (context, event, callback) => {
  // Create a new messaging response object
  const twiml = new Twilio.twiml.MessagingResponse();
  // Use any of the Node.js SDK methods, such as `message`, to compose a response
  twiml.message("Hello, World!");
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

```js title="Return a Voice response that includes Say and Play verbs"
exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();
  // Webhook information is accessible as properties of the `event` object
  const city = event.FromCity;
  const number = event.From;

  // You can optionally edit the voice used, template variables into your
  // response, play recorded audio, and more
  twiml.say({ voice: "alice" }, `Never gonna give you up, ${city || number}`);
  twiml.play("https://demo.twilio.com/docs/classic.mp3");
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

## 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](/docs/serverless/functions-assets/functions/dependencies).

### Twilio

The `Twilio` class is accessible at any time. This is commonly used to initialize TwiML or [Access Tokens](/docs/iam/access-tokens) for your Function responses. For example:

```javascript
// 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](/docs/serverless/functions-assets/client) is accessible via `Runtime`, and exposes helper methods for accessing private Assets, other Functions, and the [Sync](/docs/sync) client. For example:

```javascript
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](#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:

```javascript
// 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                                                                              |

```js title="Set a Status Code in a Response" description="Example of setting a Status Code using Twilio Response"
exports.handler = (context, event, callback) => {
  // No need to import Twilio; it is globally available in Functions
  const response = new Twilio.Response();

  // Set the status code to 204 Not Content
  response.setStatusCode(204);

  return callback(null, response);
};
```

```js title="Build a Plaintext Response" description="Example of building a plaintext response with Twilio Response"
exports.handler = (context, event, callback) => {
  // No need to import Twilio; it is globally available in Functions
  const response = new Twilio.Response();

  response
    // Set the status code to 200 OK
    .setStatusCode(200)
    // Set the response body
    .setBody("This is fine");

  return callback(null, response);
};
```

```js title="Building a JSON Response" description="Example of building a JSON response with Twilio Response"
exports.handler = (context, event, callback) => {
  // No need to import Twilio; it is globally available in Functions
  const response = new Twilio.Response();

  response
    // Set the status code to 200 OK
    .setStatusCode(200)
    // Set the Content-Type Header
    .appendHeader("Content-Type", "application/json")
    // Set the response body
    .setBody({
      everything: "is alright",
    });

  return callback(null, response);
};
```

```js title="Set an HTTP Header in a Response" description="Example of setting an header using Twilio Response"
exports.handler = (context, event, callback) => {
  // No need to import Twilio; it is globally available in Functions
  const response = new Twilio.Response();

  response
    // Set the status code to 301 Redirect
    .setStatusCode(301)
    // Set the Location header for redirect
    .appendHeader("Location", "https://twilio.com");

  return callback(null, response);
};
```

```js title="Set Multiple HTTP Headers in a Response" description="Example of setting multiple headers using Twilio Response"
exports.handler = (context, event, callback) => {
  // No need to import Twilio; it is globally available in Functions
  const response = new Twilio.Response();

  // Build a mapping of headers as a way to set many with one command
  const headers = {
    "Access-Control-Allow-Origin": "example.com",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type",
  };

  // Set headers in response
  response.setHeaders(headers);

  return callback(null, response);
};
```

## 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](/docs/serverless/functions-assets/quickstart) yet to learn)

The next important step in your journey is to [understand the concept of visibility](/docs/serverless/functions-assets/visibility), and how it affects access to and use of your Functions (and Assets)!
