Access to incoming headers and cookies is only available when your Function is running @twilio/runtime-handler
version 1.2.0
or later. Consult the Runtime Handler guide to learn more about the latest version and how to update.
Within a Function, headers are stored on the event.request.headers
object and can be accessed by name in lowercase.
The names of all headers are lowercased before being passed into your Function. Please reference headers with the correct casing to avoid errors.
For example, the key of the Content-Type
header will be content-type
.
For example, if the following request is received by your Function:
1GET /example HTTP/1.12Host: test-4321.twil.io3Authorization: 123abc4Content-Type: application/json5Content-Length: 2367{8"body": "Ahoy!"9}
You can access various headers in the following ways:
1exports.handler = (context, event, callback) => {2// Access the `Authorization` header via dot notation3const authHeader = event.request.headers.authorization;4console.log(authHeader); // '123abc'56// Access the `Authorization` header via bracket notation7const alsoTheAuthHeader = event.request.headers['authorization'];8console.log(alsoTheAuthHeader); // '123abc'910// Access headers that include hyphens and other non-alphanumeric11// characters with bracket notation12const contentType = event.request.headers['content-type'];13console.log(contentType); // 'application/json'1415return callback();16}
It is possible for a request to contain multiple values for a single header.
For example, consider the following incoming request:
1GET /example HTTP/1.12Host: test-4321.twil.io3Content-Type: application/json4Cache-Control: no-cache5Cache-Control: private6Content-Length: 2378{9"body": "Ahoy!"10}
Here, both no-cache
and private
have been assigned to the cache-control
header. Since cache-control
now has multiple values instead of a single value, it will return an array of strings when accessed:
1exports.handler = (context, event, callback) => {2// Access a multivalued header. In this case, `Cache-Control`3const cacheControl = event.request.headers['cache-control'];4console.log(cacheControl); // ['no-cache', 'private'];56return callback();7}
The order of multivalued headers in a request is preserved.
If you know for certain that the value of interest lies at a particular index of a header, you may access it directly. e.g. event.request.headers['cache-control'][1]
Now that you know how to access incoming headers and cookies, let's take a look at how you can set and modify headers on your Function responses.