# 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 gateway groups where it is deployed.

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[​](#before-you-begin "Direct link to Before You Begin")

Prepare the following:

* Access to the Dashboard and a non-production gateway group.
* A [Dashboard token](https://docs.api7.ai/api7-gateway/reference/obtain-dashboard-token.md) with permission to manage the test resources.
* The gateway group ID and name, Admin API endpoint, and proxy endpoint. The commands use `https://localhost:7443` and `http://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[​](#build-the-plugin "Direct link to 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](https://docs.api7.ai/api7-gateway/how-to-guides/plugin-development/best-practices.md) for phase selection, priority, and `apisix.core` guidance.

## Keep Uploaded Schemas Self-Contained[​](#keep-uploaded-schemas-self-contained "Direct link to 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[​](#register-the-plugin-in-api7-gateway "Direct link to Register the Plugin in API7 Gateway")

Upload `custom-header.lua` from the Dashboard. The Dashboard location and ownership model depend on the release:

| Release            | Dashboard location                                           | Plugin scope                                                                                           |
| ------------------ | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| 3.10.6 and later   | Open the test gateway group, then select **Custom Plugins**. | The uploaded plugin belongs only to that gateway group.                                                |
| 3.10.5 and earlier | Open **Gateway Settings → Custom Plugin**.                   | One control-plane-wide plugin object is deployed to the groups selected in **Deployed Gateway Group**. |

In the appropriate location, 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.

On 3.10.5 and earlier, select only the test group under **Deployed Gateway Group**. On later releases, the group is established by where you opened **Custom Plugins**.

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](https://docs.api7.ai/api7-gateway/enterprise-features/custom-plugins.md).

## Test the Plugin[​](#test-the-plugin "Direct link to 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"

      }

    }

  }'
```

adc.yaml

```
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[​](#store-plugin-metadata "Direct link to 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[​](#store-and-verify-metadata "Direct link to 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[​](#verify-schema-rejection "Direct link to 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 Dependencies[​](#add-dependencies "Direct link to Add Dependencies")

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[​](#package-private-lua-dependencies "Direct link to Package Private Lua Dependencies")

API7 Gateway 3.10.5 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](#add-shared-or-native-libraries).

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`:

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](#test-the-plugin) 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[​](#add-shared-or-native-libraries "Direct link to 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_path` and `extra_lua_path`.
* Native Lua/C modules use `lua_package_cpath` and `extra_lua_cpath`.

For example, keep custom paths separate from the gateway runtime:

config.yaml

```
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](https://docs.api7.ai/api7-gateway/configure-and-manage/configure-data-plane.md#custom-plugin-paths) for deployment details.

note

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[​](#roll-out-across-gateway-groups "Direct link to Roll Out Across Gateway Groups")

From 3.10.6, each [gateway group](https://docs.api7.ai/api7-gateway/enterprise-features/gateway-groups.md) owns an independent copy of a custom plugin. Roll out a new plugin or update without changing its name:

1. Upload the plugin to a non-production group.
2. Enable and validate it on a test route.
3. Upload the same reviewed file to the production group.

An upload replaces the code only in that group. Deletion is blocked while resources in the group still reference the plugin. Other groups can use the same plugin name without sharing code or metadata.

On 3.10.5 and earlier, one control-plane-wide plugin object has a list of **Deployed Gateway Group** values. Updating its code changes every selected group at once. To validate a change without affecting production, create a uniquely named test plugin, then apply the reviewed change to the production plugin.

Before 3.10.6, a resource could reference a plugin that its gateway group did not receive, and the gateway would not run it. Later releases reject that resource. Upload the plugin to the group before enabling it.

## Troubleshoot the Plugin[​](#troubleshoot-the-plugin "Direct link to 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 it was uploaded to the gateway group being configured.                                                                                                                              |
| 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[​](#next-steps "Direct link to Next Steps")

* [Plugin Development Best Practices](https://docs.api7.ai/api7-gateway/how-to-guides/plugin-development/best-practices.md): write plugin code that is correct, fast, and maintainable.
* [Serverless Functions or Custom Plugins](https://docs.api7.ai/api7-gateway/how-to-guides/plugin-development/serverless-or-custom-plugins.md): choose the right extension mechanism for your use case.
* [Plugins](https://docs.api7.ai/api7-gateway/key-concepts/plugins.md): understand plugin execution order and scopes.
