> ## Documentation Index
> Fetch the complete documentation index at: https://tyk.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Request Context Variables

> Learn how to use the request context in your transformation middleware

Context variables are extracted from the request at the start of the middleware chain. These values can be very useful for later transformation of request data, for example, in converting a form POST request into a JSON PUT request or to capture an IP address as a header.

> [!NOTE]
>
> Context variables must be enabled for your API to access them in transformation middleware. See [Enabling Context Variables](#enabling-context-variables) for configuration instructions.

## Available Context Variables

| Variable name | Description |
| - | - |
| `request_data` | If the inbound request contained any query data or form data, it will be available in this object. For the header injector Tyk will format this data as `key:value1,value2,valueN;key:value1,value2` etc. |
| `path_parts` | The components of the path, split on `/`. These values should be in the format of a comma delimited list. |
| `token` | The inbound raw token of this user (if bearer tokens are being used). |
| `path` | The path that is being requested. |
| `remote_addr` | The client's IP address. |
| `request_id` | Allows the injection of request correlation ID (for example X-Request-ID) |
| `tyk_trace_id` | When OpenTelemetry tracing is enabled on Tyk Gateway, this contains the OpenTelemetry trace ID allocated to the request. |
| `jwt_claims_CLAIMNAME` | If JWT tokens are being used, then each claim in the JWT is available in this format to the context processor. `CLAIMNAME` is case sensitive so use the exact claim. |
| `cookies_COOKIENAME` | If there are cookies, then each cookie is available in context processor in this format. `COOKIENAME` is case sensitive so use the exact cookie name and replace any `-` in the cookie name with `_`. |
| `headers_HEADERNAME` | Request headers are accessed using the following format: Convert the **first letter** in each word of an incoming header to Capital Case and replace any `-` in the `HEADERNAME` name with `_`. For example, to get the value stored in `test-header`, the syntax would be `$tyk_context.headers_Test_Header`. |

From Tyk Gateway 5.13.0, the current session's rate limit and quota data are available from the following context variables:

| Variable name | Description |
| - | - |
| `rate_limit_limit` | Number of requests that can be sent in the rate limit period |
| `rate_limit_remaining` | Number of requests remaining in the current rate limit period |
| `rate_limit_reset` | Timestamp for next rate limit period reset (Unix time) |
| `quota_limit` | Number of requests that can be sent in the quota period |
| `quota_remaining` | Number of requests remaining in the current quota period |
| `quota_reset` | Timestamp for next quota period reset (Unix time) |

## Middleware That Can Use Context Variables

Context variables are exposed in five middleware plugins but are accessed differently depending on the caller:

| Middleware | Syntax |
| - | - |
| [URL Rewriter](https://tyk.io/docs/transform-traffic/url-rewriting.md) | `$tyk_context.CONTEXTVARIABLES` |
| [Request Header Transform](https://tyk.io/docs/api-management/traffic-transformation/request-headers.md) | `$tyk_context.CONTEXTVARIABLES` |
| [Response Header Transform](https://tyk.io/docs/api-management/traffic-transformation/response-headers.md) | `$tyk_context.CONTEXTVARIABLES` |
| [Request Body Transform](https://tyk.io/docs/api-management/traffic-transformation/request-body.md) | `{{ ._tyk_context.CONTEXTVARIABLES }}` |
| [Response Body Transform](https://tyk.io/docs/api-management/traffic-transformation/response-body.md) | `{{ ._tyk_context.CONTEXTVARIABLES }}` |

> [!NOTE]
>
> Request Body Transform and Response Body Transform can fully iterate through list indices within context data. For example, calling `{{ index ._tyk_context.path_parts 0 }}` in the Go Template exposes the first entry in the `path_parts` list.
>
> URL Rewriter, Request Header Transform, and Response Header Transform cannot iterate through list indices.

In Tyk OAS API definitions, add these middlewares under `x-tyk-api-gateway.middleware`:

* **Global level** (`x-tyk-api-gateway.middleware.global`): applied across all endpoints in the API.
* **Operation level** (`x-tyk-api-gateway.middleware.operations.<operationId>`): `transformRequestHeaders`, `transformResponseHeaders`, `transformRequestBody`, `transformResponseBody`, or `urlRewrite`, applied to a specific endpoint operation.

If using Tyk Classic APIs, add these middlewares under `version_data.versions.<version_name>`:

* **Global level** (applies to all paths in the version): `global_headers` / `global_response_headers`.
* **Path level**: `extended_paths.transform_headers`, `extended_paths.transform_response_headers`, `extended_paths.transform`, `extended_paths.transform_response`, or `extended_paths.url_rewrites`.

## Example Use of Context Variables

### Examples of the Syntax to Use with Available Context Variables

The following example adds context variables to request headers sent to the upstream. The upstream in this example echoes received request headers back in its response body, which is how the resulting values appear below.

```
"x-remote-addr": "$tyk_context.remote_addr",
"x-token": "$tyk_context.token",
"x-jwt-sub": "$tyk_context.jwt_claims_sub",
"x-part-path": "$tyk_context.path_parts",
"x-jwt-pol": "$tyk_context.jwt_claims_pol",
"x-cookie": "$tyk_context.cookies_Cookie_Context_Var",
"x-cookie-sensitive": "$tyk_context.cookies_Cookie_Case_sensitive",
"x-my-header": "$tyk_context.headers_My_Header",
"x-path": "$tyk_context.path",
"x-request-data": "$tyk_context.request_data",
"x-req-id": "$tyk_context.request_id",
"x-trace-id": "$tyk_context.tyk_trace_id"
```

![Example of the syntax in the UI](https://mintcdn.com/tyk/5UCBGp0ycRfPh9jq/img/dashboard/system-management/context_variables_ui.jpg?fit=max\&auto=format\&n=5UCBGp0ycRfPh9jq\&q=85\&s=7712879067d19c278087b64b3fe5bffe)

### Context Variable Values in the Response

The values below are from the upstream's echoed response, not values Tyk returns directly to the API client.

```
"My-Header": "this-is-my-header",
"User-Agent": "PostmanRuntime/7.4.0",
"X-Cookie": "this-is-my-cookie",
"X-Cookie-Sensitive": "case-sensitive",
"X-Jwt-Pol": "5bca6a739afe6a00017eb267",
"X-Jwt-Sub": "john.doe@test.com",
"X-My-Header": "this-is-my-header",
"X-Part-Path": "context-var-example,anything",
"X-Path": "/context-var-example/anything",
"X-Remote-Addr": "127.0.0.1",
"X-Req-Id": "e3e99350-b87a-4d7d-a75f-58c1f89b2bf3",
"X-Request-Data": "key1:val1;key2:val2",
"X-Token": "5bb2c2abfb6add0001d65f699dd51f52658ce2d3944d3d6cb69f07a2",
"X-Trace-Id": "4bf92f3577b34da6a3ce929d0e0e4736"
```

## Enabling Context Variables

### Tyk OAS

In Tyk OAS APIs, context variables are enabled by default when creating or importing an API. This is an API-wide setting under `x-tyk-api-gateway.middleware.global.contextVariables.enabled`

> [tab] Dashboard
>
> 1. In the Tyk Dashboard, select **APIs** from the **API Management** menu.
>
> 2. Select your Tyk OAS API.
>
>    ![Tyk Dashboard APIs list under API Management, showing Tyk OAS APIs to select from](https://mintcdn.com/tyk/nHl8HUJvac9TMQQ5/img/dashboard/system-management/tyk-oas-context-variables-api-list.png?fit=max\&auto=format\&n=nHl8HUJvac9TMQQ5\&q=85\&s=690ee7b10b61203fb4acf5e99a282c62)
>
> 3. Select the **Settings** tab.
>
> 4. Scroll down to the **Middleware** section and toggle **Context variables** to **On**.
>
>    ![Tyk OAS API Settings Middleware section with the Context variables toggle switched on](https://mintcdn.com/tyk/nHl8HUJvac9TMQQ5/img/dashboard/system-management/tyk-oas-context-variables-toggle.png?fit=max\&auto=format\&n=nHl8HUJvac9TMQQ5\&q=85\&s=7e5233a3ca0e20d1d4bcb29266541b14)
>
> 5. Click **Save API**.

> [tab] Operator
>
> When using Tyk Operator with `TykOasApiDefinition`, set `x-tyk-api-gateway.middleware.global.contextVariables.enabled` to `true` in the OpenAPI specification stored in the ConfigMap referenced by the custom resource:
>
> ```yaml expandable theme={null}
> apiVersion: v1
> kind: ConfigMap
> metadata:
>   name: httpbin-oas
>   namespace: default
> data:
>   openapi.json: |-
>     {
>       "openapi": "3.0.3",
>       "info": {
>         "title": "httpbin",
>         "version": "1.0.0"
>       },
>       "paths": {},
>       "x-tyk-api-gateway": {
>         "info": {
>           "name": "httpbin",
>           "state": {
>             "active": true
>           }
>         },
>         "upstream": {
>           "url": "http://httpbin.org"
>         },
>         "server": {
>           "listenPath": {
>             "value": "/httpbin",
>             "strip": true
>           }
>         },
>         "middleware": {
>           "global": {
>             "contextVariables": {
>               "enabled": true
>             }
>           }
>         }
>       }
>     }
> ---
> apiVersion: tyk.tyk.io/v1alpha1
> kind: TykOasApiDefinition
> metadata:
>   name: httpbin
>   namespace: default
> spec:
>   tykOAS:
>     configmapRef:
>       name: httpbin-oas
>       namespace: default
>       keyName: openapi.json
> ```

> [tab] API Definition
>
> In your Tyk OAS API definition file, enable context variables under `x-tyk-api-gateway.middleware.global.contextVariables.enabled`:
>
> ```json theme={null}
> {
>   "x-tyk-api-gateway": {
>     "middleware": {
>       "global": {
>         "contextVariables": {
>           "enabled": true
>         }
>       }
>     }
>   }
> }
> ```

### Tyk Classic

If using Tyk Classic APIs, context variables are disabled by default and must be explicitly enabled (`enable_context_vars: true`).

> [tab] Dashboard
>
> 1. In the Tyk Dashboard, select **APIs** from the **System Management** menu.
> 2. Select your Tyk Classic API.
> 3. Select the **Advanced Options** tab and select **Enable context variables**.
> 4. Click **Update**.
>
> ![Context Variables](https://mintcdn.com/tyk/rcbuH4FawxAvTx_L/img/2.10/context_variables.png?fit=max\&auto=format\&n=rcbuH4FawxAvTx_L\&q=85\&s=7a0f7f75e5a3dbb1d24be14d0605e0ff)

> [tab] Operator
>
> When using Tyk Operator with Tyk Classic `ApiDefinition` custom resources, set `spec.enable_context_vars` to `true`:
>
> ```yaml {linenos=true, linenostart=1, hl_lines=["10-10"]} theme={null}
> apiVersion: tyk.tyk.io/v1alpha1
> kind: ApiDefinition
> metadata:
>   name: httpbin
> spec:
>   name: httpbin
>   use_keyless: true
>   protocol: http
>   active: true
>   enable_context_vars: true
>   proxy:
>     target_url: http://httpbin.org
>     listen_path: /httpbin
>     strip_listen_path: true
> ```

> [tab] API Definition
>
> If you are not using Tyk Dashboard, add the field `enable_context_vars` at the root level of your API definition file and set it to `true`:
>
> ```json theme={null}
> {
>   "name": "httpbin",
>   "enable_context_vars": true
> }
> ```
