Environment Variables are key/value pairs that you can add to a specific Environment. Use these for storing configuration like API keys rather than hardcoding them into your Functions. 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.
To view and modify the Environment Variables for a given Service, open the Service using the Twilio Console. Once the Functions Editor is open for your Service, in the Settings menu, click on Environment Variables.
context
, and also that calling context.getTwilioClient()
will return an initialized Twilio REST client for making calls to Twilio's API.If you're using the Serverless Toolkit, you will instead set your Environment Variables using .env files.
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.
_33const axios = require('axios');_33const querystring = require('querystring');_33_33exports.handler = async (context, event, callback) => {_33 // Environment Variables can be accessed from the context object_33 const apiKey = context.API_KEY;_33 const supportNumber = context.SUPPORT_PHONE_NUMBER;_33_33 // Query parameters and the request body can be accessed_33 // from the event object_33 const city = event.city || 'Seattle';_33_33 // The Weather API accepts the city and apiKey as query parameters_33 const query = querystring.stringify({ q: city, appid: apiKey });_33 // Make our OpenWeather API request, and be sure to await it!_33 const { data } = await axios.get(_33 `https://api.openweathermap.org/data/2.5/weather?${query}`_33 );_33 // Do some math to convert the returned temperature from Kelvin to F_33 const tempInFahrenheit = (data.main.temp - 273.15) * 1.8 + 32;_33 // If its too hot, relay this information and the support number_33 if (tempInFahrenheit >= 100) {_33 return callback(null, {_33 isOpen: false,_33 message:_33 'Due to extreme temperatures and to protect the health ' +_33 "of our employees, we're closed today. If you'd like to " +_33 `speak to our support team, please call ${supportNumber}`,_33 });_33 }_33 // Otherwise, business as usual_33 return callback(null, { isOpen: true, message: "We're open!" });_33};
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 which the current Function is contained in. |
ENVIRONMENT_SID | string | The SID of the Environment which the current Function is hosted in. |
Please note that 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.
There are limitations on the size of individual Environment Variables depending on your method of deployment. A variable can be no longer than:
Additionally, there is a maximum limit of approximately 3kb on the combined size of your Environment Variables after they have been JSON encoded.
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.
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 and ingest it in your code using the Runtime.getAssets helper.
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.
_10{_10 "myRsaKey": "xxxxxx..."_10}
You could then access the RSA key (or any other stored credentials) in your Function using this code pattern.
_12exports.handler = (context, event, callback) => {_12 // The open method returns the file's contents assuming utf8 encoding._12 // Use JSON.parse to parse the file back into a JavaScript object_12 const credentials = JSON.parse(_12 Runtime.getAssets()['/credentials.json'].open()_12 );_12_12 // Reference the key from the credentials object_12 const { myRsaKey } = credentials;_12_12 // Perform any API calls that require this key!..._12};