Related Documentation
Made by
Kong Inc.
Supported Gateway Topologies
hybrid db-less traditional
Supported Konnect Deployments
hybrid cloud-gateways serverless
Compatible Protocols
grpc grpcs http https tcp tls tls_passthrough udp ws wss
Minimum Version
Kong Gateway - 1.0

The Pre-Function plugin (also known as Kong Functions, Pre-Plugin) lets you dynamically run Lua code from Kong Gateway before other plugins in each phase.

This plugin is part of a pair of serverless plugins. If you need to run Lua code after other plugins in each phase, see the Post-Function plugin.

Warning: The Pre-Function and Post-Function serverless plugins allow anyone who can enable the plugin to execute arbitrary code. If your organization has security concerns about this, disable the plugins in your kong.conf file.

Note: This plugin does not support conditional expressions.

Phases

The Pre-Function plugin can run custom Lua code in any of the following phases in Kong Gateway’s lifecycle:

  • access
  • body_filter
  • certificate
  • header_filter
  • log
  • rewrite
  • ws_client_frame
  • ws_close
  • ws_handshake
  • ws_upstream_frame

To run the Pre-Function plugin in a specific phase, use a config.PHASE_NAME parameter. For example, to run the plugin in the header_filter phase, use config.header_filter.

You can also run the plugin in multiple phases. See Running Pre-Function in multiple phases for an example.

Passing Lua code to the plugin

Since Kong Gateway expects the Lua code in a string format, we recommend either uploading a file through the Admin API using the @file.lua syntax, or minifying your Lua code using a minifier.

The syntax for passing a file to the Pre-Function plugin depends on the tool you’re using.

Upvalues

You can return a function to run on each request, allowing for upvalues to keep state in between requests:

-- this runs once on the first request
local count = 0

return function()
  -- this runs on each request
  count = count + 1
  ngx.log(ngx.ERR, "hello world: ", count)
end

Sandboxing

The provided Lua environment is sandboxed.

Sandboxing imposes several limitations on how custom Lua code can be executed, for heightened security. The Lua (or LuaJIT) language itself is not limited — only the available environment and the set of usable modules are restricted.

The limitations can be adjusted with the untrusted_lua=off|strict|lax|sandbox|on setting.

See the sandboxing reference for more information.

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!