# Environment Variables

Environment Variables are key/value pairs that you can add to a specific [Environment](/docs/serverless/api/resource/environment). Use these for storing configuration like API keys rather than hardcoding them into your [Functions](/docs/serverless/api/resource/function). Environment Variables are encrypted, so they are the preferred way to store API keys, passwords, and any other secrets that your Function needs to use.

They also prove useful because when an Environment Variable is updated, the new value will instantly reflect in subsequent Function executions without the need for deploying new code. This allows you to adjust configurations on the fly without potentially interrupting your service due to deployments.

## Setting Environment Variables

To view and modify the Environment Variables for a given [Service](/docs/serverless/functions-assets/functions/create-service), open the Service using the [Twilio Console](/console/functions/overview/services). Once the Functions Editor is open for your Service, in the **Settings** menu, click on **Environment Variables**.

![UI for managing environment variables with options to add API keys and Twilio credentials.](https://docs-resources.prod.twilio.com/e201e14373ea04a4dde6253caacf2dfb6fad6704110ac501df7cdee9377e6c7b.png)

The resulting UI allows you to add, remove, and update Environment Variables.

Additionally, the **Add my Twilio Credentials (ACCOUNT\_SID) and (AUTH\_TOKEN) to ENV** checkbox allows you to choose if you would like for your ACCOUNT SID and AUTH TOKEN to be automatically added to your Function's context. This means both of these values will be accessible as Environment Variables from `context`, and also that calling `context.getTwilioClient()` will return an initialized Twilio REST client for making calls to Twilio's API.

> \[!NOTE]
>
> If you're using the Serverless Toolkit, you will instead [set your Environment
> Variables using .env
> files](/docs/labs/serverless-toolkit/general-usage#environment-variables).

### Editing Environment Variables across Environments

If you're using multiple Environments in your application, such as dev, stage, and production, it's common to have the same Environment Variables present in each Environment, but with different values so that each version of your application is connecting to the appropriate resources. These could be various API keys with different levels of access or rate limits for the same service, credentials for different versions of your database, and more.

Using the Console UI, you can switch between which Environment Variables you are adjusting by clicking on your application URL, directly above the **Deploy All** button. This will render a menu showing your various Environments, and selecting one will put you in the context of that Environment.

![Dropdown showing environment options for deployment with 'Deploy All' button.](https://docs-resources.prod.twilio.com/4df7613c62e5f8dd3c8763bcc35f5b522bbdd6b7d793403f55685e28a5f870a1.png)

Any modifications to Environment Variables that follow will only apply to the selected Environment and not affect any others.

> \[!NOTE]
>
> If you're developing using the Serverless Toolkit, check out the specific
> documentation on [how to scope environment
> variables](/docs/labs/serverless-toolkit/configuration#scoped-configurations).

## Consuming Environment Variables

Any Environment Variables that have been set will be accessible in your Function as properties of the `context` object by name. For example, if you set an Environment Variable named API\_KEY, it can be retrieved as `context.API_KEY` in your Function's code.

Suppose an IVR tree you're designing requires some logic to determine if a branch of your business is open that day based on local temperatures. Using the OpenWeather Weather API and an API Key that you've set to an Environment Variable, you could securely retrieve that key from `context.API_KEY` and make validated requests for weather data to complete your business logic. You can also store a common support phone number as an Environment Variable to share between your Functions.

```js
const axios = require("axios");
const querystring = require("querystring");

exports.handler = async (context, event, callback) => {
  // Environment Variables can be accessed from the context object
  const apiKey = context.API_KEY;
  const supportNumber = context.SUPPORT_PHONE_NUMBER;

  // Query parameters and the request body can be accessed
  // from the event object
  const city = event.city || "Seattle";

  // The Weather API accepts the city and apiKey as query parameters
  const query = querystring.stringify({ q: city, appid: apiKey });
  // Make our OpenWeather API request, and be sure to await it!
  const { data } = await axios.get(
    `https://api.openweathermap.org/data/2.5/weather?${query}`
  );
  // Do some math to convert the returned temperature from Kelvin to F
  const tempInFahrenheit = (data.main.temp - 273.15) * 1.8 + 32;
  // If its too hot, relay this information and the support number
  if (tempInFahrenheit >= 100) {
    return callback(null, {
      isOpen: false,
      message:
        "Due to extreme temperatures and to protect the health " +
        "of our employees, we're closed today. If you'd like to " +
        `speak to our support team, please call ${supportNumber}`,
    });
  }
  // Otherwise, business as usual
  return callback(null, { isOpen: true, message: "We're open!" });
};
```

## Default Environment Variables

The `context` object provides you with several Environment Variables by default:

| Property          | Type           | Description                                                                                                                                                                                                                                           |
| :---------------- | :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ACCOUNT_SID`     | `string\|null` | If you have chosen to include your account credentials in your Function, this will return the SID identifying the Account that owns this Function. If you have not chosen to include account credentials in your Function, this value will be `null`. |
| `AUTH_TOKEN`      | `string\|null` | If you have chosen to include your account credentials in your Function, this will return the Auth Token associated with the owning Account. If you have not chosen to include account credentials in your Function, this value will be `null`.       |
| `DOMAIN_NAME`     | `string`       | The Domain that is currently serving your Twilio Function.                                                                                                                                                                                            |
| `PATH`            | `string`       | The path of Twilio Function that is currently being executed.                                                                                                                                                                                         |
| `SERVICE_SID`     | `string`       | The SID of the [Service](/docs/serverless/api/resource/service) which the current Function is contained in.                                                                                                                                           |
| `ENVIRONMENT_SID` | `string`       | The SID of the [Environment](/docs/serverless/api/resource/environment) which the current Function is hosted in.                                                                                                                                      |

> \[!WARNING]
>
> For a small number of customers, `SERVICE_SID` and `ENVIRONMENT_SID` are not enabled due to the combined size of environment variables in use being too high and approaching the allowed limit of **3kb**. In this case, these variables will return `undefined`.
>
> If you believe you are affected by this issue and wish to enable these variables, please reach out to our support team for assistance.

## Limitations

There are limitations on the size of individual Environment Variables depending on your method of deployment. A variable can be no longer than:

* 255 characters if set using the current V2 Console
* 150 characters if set using the legacy, Functions(Classic) Console
* 450 bytes if set using the Serverless Toolkit or the Serverless API

Additionally, there is a maximum limit of approximately **3kb** on the combined size of your Environment Variables after they have been JSON encoded.

> \[!CAUTION]
>
> If any Environment Variable exceeds the individual limit or all Variables
> combined exceed the maximum limit, then your deployments will fail until your
> Variables have been resized.

### Storing large credentials

If you must store an extremely long API key or other credential, such as an RSA key, which will cause you to exceed these limits, we suggest that you instead store the value in a [private Asset](/docs/serverless/functions-assets/assets) and ingest it in your code using the [Runtime.getAssets helper](/docs/serverless/functions-assets/client#getassets).

Given these constraints and a large RSA key that you need to store securely, you could store the text of the key in an Asset named `credentials.json`, and set the Asset's Privacy to **private**.

```json
{
  "myRsaKey": "xxxxxx..."
}
```

You could then access the RSA key (or any other stored credentials) in your Function using this code pattern.

```js
exports.handler = (context, event, callback) => {
  // The open method returns the file's contents assuming utf8 encoding.
  // Use JSON.parse to parse the file back into a JavaScript object
  const credentials = JSON.parse(
    Runtime.getAssets()["/credentials.json"].open()
  );

  // Reference the key from the credentials object
  const { myRsaKey } = credentials;

  // Perform any API calls that require this key!...
};
```
