Pre-function Plugin Explained with Practical Example
Kong Gateway is a multifunctional API gateway, but did you know you can embed lightweight serverless functions directly inside it?
This time, we’ll introduce a practical example using Lua scripts to extract a UUID from the request body, add it to the header, and output it to the log.
What is the Pre-function Plugin?
As described in the official documentation, the pre-function
plugin is a flexible feature that allows you to write Lua code to process requests before they are sent to the API.
It can be used for:
- Conditional filtering
- Customizing headers/bodies
- Lightweight logging or monitoring
- Simple maintenance blocking
It’s perfect for cases where you don’t need a full plugin, but want to do “just a little processing”.
Practical Example
This time, we’ll use the serverless feature to extract a UUID from the request body and add it to the header and log.
Processing Flow
- Extract UUID from the request body (parse JSON)
- If a UUID exists, add it to the
x-uuid
header - Output the extraction result to the log (using the File Log plugin)
Preparation: Create Service and Route
|
|
Output Log with File Log Plugin (to stdout)
|
|
Pre-function Configuration
You can execute custom code at each Nginx phase. For details on phases, see: https://nginx.org/en/docs/dev/development_guide.html#http_phases
|
|
The above code inserts the following into the access
and log
phases. Comments explain each part:
|
|
|
|
Sending a Request
Send a request with uuid
in the body.
|
|
When the API is reached, the header will include "Uuid": "123e4567-e89b-12d3-a456-426614174000"
.
|
|
From the log, you can see the details of the request and response, including both the header and the body.
|
|
Conclusion
By combining Kong’s pre-function and file-log plugins, you can process and visualize API request content without calling external services.
Kong can be used as more than just a gateway—it can serve as a “lightweight edge processing engine.” With Lua scripts, you can smartly automate preprocessing for REST APIs!