Develop Custom Lua Plugins
Custom Lua plugins add reusable request or response logic when built-in plugins do not meet an API's requirements. API7 Gateway validates and distributes uploaded plugin code through its control plane, then exposes the plugin to resources in the selected gateway groups.
The example below creates custom-header, a plugin that adds a configured request header. It also defines optional shared metadata so the same plugin can demonstrate the complete development, registration, testing, and metadata workflow.
Before You Begin
Prepare the following:
- Access to the Dashboard and a non-production gateway group.
- A Dashboard token with permission to manage the test resources.
- The gateway group ID and name, Admin API endpoint, and proxy endpoint. The commands use
https://localhost:7443andhttp://localhost:9080; replace them if the deployment uses different addresses.
Export the token and test gateway group identifiers:
export API_KEY="a7ee-xxxxxxxxxxxxx"
export GATEWAY_GROUP_ID="replace-with-test-gateway-group-id"
export GATEWAY_GROUP_NAME="replace-with-test-gateway-group-name"
export ADC_TOKEN="$API_KEY"
export ADC_SERVER="https://localhost:7443"
Build the Plugin
Create custom-header.lua with the following complete plugin. The plugin runs in the access phase, after route matching and before the request is proxied upstream.
local core = require("apisix.core")
local plugin = require("apisix.plugin")
local schema = {
type = "object",
properties = {
header_name = {
type = "string",
default = "X-Custom-Lua"
},
header_value = {
type = "string",
default = "loaded"
}
}
}
local plugin_name = "custom-header"
local _M = {
version = 0.1,
priority = 1500,
name = plugin_name,
schema = schema,
metadata_schema = {
type = "object",
properties = {
enabled = { type = "boolean" },
id = { type = "string" }
},
required = { "enabled" }
}
}
function _M.check_schema(conf, schema_type)
if schema_type == core.schema.TYPE_METADATA then
return core.schema.check(_M.metadata_schema, conf)
end
return core.schema.check(schema, conf)
end
function _M.access(conf, ctx)
core.request.set_header(ctx, conf.header_name, conf.header_value)
local metadata = plugin.plugin_metadata(plugin_name)
if metadata and metadata.value and metadata.value.enabled then
core.request.set_header(ctx, "X-Plugin-Metadata-ID", metadata.value.id)
end
end
return _M
❶ Defines the shared metadata object accepted by the plugin.
❷ Validates route or service configuration against schema and shared metadata against metadata_schema.
❸ Reads metadata safely. Before metadata exists, the plugin continues to set only the configured request header.
The module also declares the standard name, version, priority, and schema fields. See Plugin Development Best Practices for phase selection, priority, and apisix.core guidance.
Keep Uploaded Schemas Self-Contained
For a single-file upload, the control plane extracts selected declarations without executing the file as the gateway would. Keep schema, consumer_schema, and metadata_schema as self-contained table literals, as shown in custom-header.lua. Define nested schemas and pattern keys inline rather than through helper variables, function calls, later assignments, or modules loaded with require.
For example, avoid referencing a separate item schema:
local limit_schema = {
type = "integer",
minimum = 1
}
local schema = {
type = "object",
properties = {
limits = {
type = "array",
items = limit_schema
}
}
}
The extractor can omit limit_schema, causing the array item constraint to disappear. An omitted helper used as a table key, such as [date_pattern], can instead make parsing fail. A file that runs successfully on the gateway can therefore fail upload or produce an incomplete control-plane schema.
After uploading, test valid and invalid configurations, including nested fields. The control plane validates against the extracted JSON Schema, and the gateway also runs check_schema. Successful control-plane validation alone does not prove that the gateway will accept the configuration.
Register the Plugin in API7 Gateway
In the Dashboard, open Gateway Settings → Custom Plugin, then click Add Custom Plugin. Upload custom-header.lua as the Plugin Source Code File and complete the required fields:
- Plugin Catalog: select the catalog where operators should find the plugin.
- Plugin Description: describe what the plugin does.
- Plugin Documentation Link: provide a link to its operator documentation.
- Plugin Author: identify the owner of the plugin.
- Deployed Gateway Group: select only the non-production group used for this guide.
The Dashboard parses and displays the plugin name and version. Add the plugin, then open a route or service in the test group and confirm that custom-header appears in Add Plugin.
For the broader product workflow, see Custom Plugins.
Test the Plugin
Enable the registered plugin on a test route with the Admin API or ADC. The control plane distributes the plugin source to the gateway nodes.
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/services/custom-header-service?gateway_group_id=${GATEWAY_GROUP_ID}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "custom-header-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [
{
"host": "httpbin.org",
"port": 80,
"weight": 100
}
]
}
}'
curl -k "https://localhost:7443/apisix/admin/routes/custom-header-route?gateway_group_id=${GATEWAY_GROUP_ID}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "custom-header-route",
"methods": ["GET"],
"paths": ["/get"],
"service_id": "custom-header-service",
"plugins": {
"custom-header": {
"header_name": "X-Trace-ID",
"header_value": "docs-test"
}
}
}'
services:
- name: custom-header-service
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
routes:
- name: custom-header-route
uris:
- /get
plugins:
custom-header:
header_name: X-Trace-ID
header_value: docs-test
labels:
docs-example: custom-header-service
Preview the changes owned by this example and confirm that the diff contains no unintended updates or deletions:
adc diff -f adc.yaml \
--backend api7ee \
--server "$ADC_SERVER" \
--gateway-group "$GATEWAY_GROUP_NAME" \
--include-resource-type service \
--label-selector docs-example=custom-header-service
Synchronize the reviewed configuration:
adc sync -f adc.yaml \
--backend api7ee \
--server "$ADC_SERVER" \
--gateway-group "$GATEWAY_GROUP_NAME" \
--include-resource-type service \
--label-selector docs-example=custom-header-service
Send a request and verify the header in the upstream response body:
curl -i "http://localhost:9080/get"
The httpbin response should include X-Trace-ID: docs-test under headers, which confirms the plugin modified the request before proxying.
Because no shared metadata has been stored yet, the response should not include X-Plugin-Metadata-ID.
If the proxy returns 404 Route Not Found immediately after the route is created, wait a few seconds for configuration propagation and retry the request.
Store Plugin Metadata
Plugin metadata is one object shared by all instances of a plugin within a gateway group. Route and service settings still belong in the plugin's regular schema.
The custom-header plugin already defines metadata_schema and handles missing metadata safely. The client sends the metadata object directly, without an id or value wrapper. After validating the request, the control plane injects the plugin name as id. The synchronized wrapper contains the following fields used by this example, along with internal bookkeeping fields:
{
"key": "/apisix/plugin_metadata/custom-header",
"value": {
"enabled": true,
"id": "custom-header"
}
}
The plugin reads the object from metadata.value. If metadata_schema sets additionalProperties to false, declare the injected id as an optional string property, as the example does. Clients still omit id from requests.
Store and Verify Metadata
Reuse the exported test group ID and API key. Send the metadata object as the entire request body:
METADATA_URL="https://localhost:7443/apisix/admin/plugin_metadata/custom-header?gateway_group_id=${GATEWAY_GROUP_ID}"
curl -k -i -X PUT "$METADATA_URL" \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"enabled": true
}'
Expect HTTP 200. The control plane validates the request body, then adds id: custom-header to the object synchronized to the gateway.
Send the test request again:
curl -sS "http://localhost:9080/get"
The httpbin response should now contain both headers under headers:
X-Plugin-Metadata-Id: custom-header
X-Trace-Id: docs-test
HTTP header names are case-insensitive. The JSON response displays them with the capitalization shown above.
Verify Schema Rejection
Send a string where metadata_schema requires a boolean:
curl -k -i -X PUT "$METADATA_URL" \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"enabled": "yes"
}'
Expect HTTP 400. The invalid update leaves the previous metadata in place, so another test request should still include X-Plugin-Metadata-Id: custom-header. If the control plane returns plugin doesn't have metadata_schema, verify that the uploaded plugin defines the schema and that the request targets the test gateway group.
Add Dependency Libraries
The example plugin is self-contained. When another plugin needs additional code, choose the dependency method by ownership and file type.
Package Private Lua Dependencies
API7 Gateway 3.9.18 and later can distribute private Lua modules in the same ZIP package as the plugin. Earlier releases require a single-file plugin or filesystem installation.
Use the plugin name for the entry file and dependency directory:
custom-header.lua
custom-header/
└── validation.lua
metadata.json
Create custom-header/validation.lua:
local _M = {}
function _M.header_value(value)
return "private:" .. value
end
return _M
In the custom-header.lua created earlier, load the private module:
local validation = require("apisix.plugins.custom-header.validation")
Then use it when setting the configured header:
core.request.set_header(
ctx,
conf.header_name,
validation.header_value(conf.header_value)
)
Define the same plugin identity and schemas in metadata.json:
{
"name": "custom-header",
"version": "0.1",
"catalog": "General",
"description": "Adds a configured header to the upstream request.",
"documentation_link": "https://docs.example.com/custom-header",
"author": "Acme Platform Team",
"schema": {
"type": "object",
"properties": {
"header_name": { "type": "string", "default": "X-Custom-Lua" },
"header_value": { "type": "string", "default": "loaded" }
}
},
"metadata_schema": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"id": { "type": "string" }
},
"required": ["enabled"]
}
}
Create and upload the package:
zip -r custom-header.zip custom-header.lua custom-header metadata.json
In the Dashboard, edit the existing custom-header plugin, replace Plugin Source Code File with custom-header.zip, and save. The package loader accepts Lua modules private to this plugin; it ignores other dependency files and does not install LuaRocks or native libraries.
Send the test request again. The upstream response should contain X-Trace-Id: private:docs-test, confirming that the packaged private module was loaded.
Add Shared or Native Libraries
Install code used by multiple plugins, LuaRocks modules, and native libraries on every gateway node. Do not upload a helper as another custom plugin and depend on plugin load order.
- Lua modules use
lua_package_pathandextra_lua_path. - Native Lua/C modules use
lua_package_cpathandextra_lua_cpath.
For example, keep custom paths separate from the gateway runtime:
apisix:
extra_lua_path: "/data/lua/?.lua"
extra_lua_cpath: "/data/clib/?.so"
Mount the files into every Kubernetes gateway pod or bind-mount them into every gateway container before startup. Reload or restart the gateways after adding or changing these dependencies. See Custom Plugin Paths for deployment details.
A native library loaded with ffi.load() follows the system library path, not lua_package_cpath. Install it in a system location such as /usr/local/lib, or set LD_LIBRARY_PATH for the gateway.
Roll Out Across Gateway Groups
One control-plane-wide custom plugin object has a list of Deployed Gateway Group values. Roll out a new plugin as follows:
- Upload the plugin and select only a non-production group.
- Enable and validate it on a test route.
- Add the production group to Deployed Gateway Group.
Updating the plugin code changes every selected group at once. To validate a production-plugin change, create a uniquely named test plugin and validate it in the test group. Then apply the reviewed change to the production plugin.
Before removing a group from the deployment list, confirm that no resource in that group still references the plugin. Plugin names are unique across the control plane.
Troubleshoot the Plugin
| Symptom | Check |
|---|---|
| Upload is rejected. | Confirm all required Dashboard fields are set and schemas are self-contained. Parse the file with the LuaJIT version used by the target gateway; luac -p is only an initial syntax check. |
| Plugin is missing from Add Plugin. | Confirm the test group remains selected in Deployed Gateway Group. |
Admin API returns plugin doesn't have metadata_schema. | Confirm the uploaded code defines metadata_schema and the request uses the same test group ID. |
The test route returns 404 Route Not Found immediately after creation. | Wait for configuration propagation and retry. |
| Plugin runs with an unexpected configuration. | Confirm the API7 Gateway payload uses paths and service_id, and inspect /usr/local/apisix/logs/error.log on the gateway. |
Next Steps
- Plugin Development Best Practices: write plugin code that is correct, fast, and maintainable.
- Serverless Functions or Custom Plugins: choose the right extension mechanism for your use case.
- Plugins: understand plugin execution order and scopes.