Skip to main content
Version: 3.20.0

Register Custom Variables

Plugin configurations often need request-specific values, such as headers, route details, or upstream information. APISIX provides built-in variables for common values and lets you register a Lua function when the value you need is not built in.

A common use is adding route context to logs. The example below registers the matched route's labels when APISIX starts or from a serverless function, then includes them in http-logger output. The final section applies the same mechanism to a captured path value used by proxy-rewrite.

Prerequisite(s)​

  • Follow the Getting Started tutorial to start APISIX.
  • Install cURL to send requests.
  • Prepare an HTTP endpoint that records POST requests, and export its URL as REMOTE_SERVER_ADDR.
  • If Admin API authentication is enabled, export an admin-role key as ADMIN_API_KEY.

Create a Service​

Start by creating a service that sends request logs to the prepared endpoint and proxies requests to httpbin.org:

curl "http://127.0.0.1:9180/apisix/admin/services" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
--data-binary @- <<EOF
{
"id": "srv_custom_var",
"plugins": {
"http-logger": {
"uri": "${REMOTE_SERVER_ADDR}"
}
},
"upstream": {
"nodes": {
"httpbin.org:80": 1
}
}
}
EOF

Register the Route Labels Variable​

The service is ready to send logs. Next, choose when to register the route-label variable:

MethodChoose this method whenWhat you need
Startup hookThe variable should be available as soon as APISIX startsAccess to the APISIX filesystem and static configuration, followed by a reload
Serverless functionRegistration should be managed with a route or serviceA serverless pre-function that runs before another plugin reads the variable

Complete one method, then continue with the log format configuration. Both methods make the matched route's labels available to the logging plugin.

Register at Startup​

Use a startup hook when the variable should be available before APISIX handles requests. The commands below use the Docker quickstart container named apisix-quickstart.

Save the following module as custom_variables.lua:

custom_variables.lua
require "apisix"
local core = require "apisix.core"

core.ctx.register_var("a6_route_labels", function(ctx)
local route = ctx.matched_route and ctx.matched_route.value
if route and route.labels then
return route.labels
end
return nil
end)

return true

The startup hook runs early in APISIX initialization, so the module imports apisix before apisix.core.

Copy the module into the Docker quickstart container:

docker exec apisix-quickstart mkdir -p /opt/apisix-custom
docker cp custom_variables.lua apisix-quickstart:/opt/apisix-custom/custom_variables.lua

Copy the active configuration to the current directory before editing it:

docker cp apisix-quickstart:/usr/local/apisix/conf/config.yaml ./config.yaml

Configure the Lua module search path and startup hook:

config.yaml
apisix:
extra_lua_path: "/opt/apisix-custom/?.lua"
lua_module_hook: custom_variables

Merge these fields into the existing apisix object in config.yaml. The Lua search path lets APISIX find the custom module, and the module hook loads it during initialization.

Copy the updated configuration into the container, validate it, and reload APISIX:

docker cp config.yaml apisix-quickstart:/usr/local/apisix/conf/config.yaml
docker exec apisix-quickstart apisix test
docker exec apisix-quickstart apisix reload

For another deployment method, mount or copy the Lua module into the APISIX instance, update its active config.yaml, and reload APISIX. Reloading plugins through the Admin API does not reload a startup hook.

For more information about loading custom Lua code, see Create a Custom Plugin in Lua.

Register with a Serverless Function​

Use a serverless function plugin when registration should be managed with a route or service. Serverless functions run before or after a configured plugin execution phase.

Serverless functions are configured as Lua strings. In readable Lua, the function used here is:

return function()
local core = require "apisix.core"

core.ctx.register_var("a6_route_labels", function(ctx)
local route = ctx.matched_route and ctx.matched_route.value
if route and route.labels then
return route.labels
end
return nil
end)
end

The following request attaches the function to the service. During the rewrite phase, it makes route labels available before http-logger records the request:

curl "http://127.0.0.1:9180/apisix/admin/services/srv_custom_var" -X PATCH \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"plugins": {
"serverless-pre-function": {
"phase": "rewrite",
"functions": [
"return function() local core = require \"apisix.core\" core.ctx.register_var(\"a6_route_labels\", function(ctx) local route = ctx.matched_route and ctx.matched_route.value if route and route.labels then return route.labels end return nil end) end"
]
}
}
}'

Configure the Log Format​

With either registration method configured, add the custom variable to the http-logger plugin metadata:

curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/http-logger" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"log_format": {
"host": "$host",
"client_ip": "$remote_addr",
"labels": "$a6_route_labels"
}
}'

The log format combines standard NGINX values for the host and client address with the custom route-label value.

Create a Route​

Create a route for the service. The assigned label is the value returned by the custom variable:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "route_custom_var",
"uri": "/get",
"service_id": "srv_custom_var",
"labels": {
"key": "test_a6_route_labels"
}
}'

Verify the Logged Variable​

Send a request to the route:

curl "http://127.0.0.1:9080/get"

The HTTP log endpoint should receive a POST request with a body similar to the following:

[
{
"labels": {
"key": "test_a6_route_labels"
},
"service_id": "srv_custom_var",
"client_ip": "172.21.0.1",
"route_id": "route_custom_var",
"host": "127.0.0.1"
}
]

The labels field confirms that the custom variable returned the matched route's labels.

Register a Route Parameter Before a Plugin Runs​

The _meta.pre_function hook can register a variable immediately before a plugin runs. The configuration below makes a captured user ID available to proxy-rewrite and does not depend on the logging workflow.

Configure the radixtree_uri_with_parameter router:

config.yaml
apisix:
router:
http: radixtree_uri_with_parameter

Apply the router setting to the active configuration for your deployment, then reload APISIX.

For the Docker quickstart, follow the same copy, validation, and reload sequence in Register at Startup, but add only the router setting shown above.

The pre-function used by proxy-rewrite is:

return function(conf, ctx)
local core = require "apisix.core"

core.ctx.register_var("user_id", function(ctx)
return ctx.curr_req_matched.user_id
end)
end

Create a route that captures user_id, registers it as a variable, and rewrites the URI with proxy-rewrite:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "pre-func-route",
"uri": "/anything/:user_id/hello",
"plugins": {
"proxy-rewrite": {
"_meta": {
"pre_function": "return function(conf, ctx) local core = require \"apisix.core\" core.ctx.register_var(\"user_id\", function(ctx) return ctx.curr_req_matched.user_id end) end"
},
"uri": "/anything/$user_id/world"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'

The route configuration works as follows:

  • The route captures the user ID from /anything/:user_id/hello.
  • The pre-function makes the captured value available as the user_id variable.
  • proxy-rewrite inserts that variable into /anything/$user_id/world.

Send a request with johndoe as the path parameter:

curl -i "http://127.0.0.1:9080/anything/johndoe/hello"

The response should contain the rewritten URL:

{
"url": "http://127.0.0.1/anything/johndoe/world"
}

The response confirms that proxy-rewrite used the custom user_id variable.