Engineering
March 18, 2021
4 min read

How to Create a Custom Lua Plugin for Kong Gateway

Thijs Schreijer

This tutorial shows you how easy it is to build a custom Lua plugin for Kong Gateway. My Kong Lua plugin example will automatically add a custom header to any response sent out, indicating the current plugin version.

Kong API Gateway is built on OpenResty, which extends the NGINX proxy server to run Lua scripts. It sits as a proxy between a client’s requests and routes them to defined services.

With the open source Kong Gateway, developers can build plugins on a per-service basis. These plugins help you build policies and Lua functions important to your architecture. You can build plugins in real time, on requests your services receive or on custom responses sent back to the client. These plugins provide an easy way to add advanced functionality and features to your implementation. For example, you could create a plugin to implement logging, rate limiting, authentication and more. Kong even had a customer create a custom plugin for Open Policy Agent.

Kong Hub has a wide range of existing plugins created by both Kong and third-party plugin authors. A few exciting plugins include:

  • Bot Detection – protects a service or route from most common bots
  • StatsD – logs metrics to a StatsD server
  • Rate limiting – limits how many HTTP requests are received in a given period of time
  • Kong Upstream API – a community-built plugin that adds a signed JWT into the HTTP header
  • Inspur Response Transform – a community-built plugin that transforms the response sent by the upstream server from JSON to XML

In addition to using pre-built plugins, you can also build your own. For example, you could create a custom Lua plugin for Kong API Gateway that hooks into the request/response phases or even works with streaming data. Kong's plugin development kit (PDK) allows you to write plugins with functionality ranging from authentication and traffic control to logging and monitoring. Plugins can be written in Lua, Go, Python or Javascript. The plugin development kit has open source templates and tools designed to get you started.

Automated API Creation Mastered: Self-Service APIs with Konnect for Agility

Setting Up Your Development Environment

Kong helps you get started building plugins through Pongo, which serves several roles. Pongo provides a framework for you to test your plugin. It also ensures that you configure your system for Kong, including fetching any dependencies. And it sets up a test Kong environment so that you can run your plugin in real time.

Pongo requires docker-compose and curl. After installing those, clone Pongo and install the Pongo CLI (a symlink to a script file) like this:

The kong-plugin repository provides a simple template to get started writing a custom Lua plugin for Kong API Gateway. Go ahead and clone that repo into a new directory called kong-api-version-plugin:

In the kong-api-version-plugin project, there are two directories to focus on:

  1. kong/plugins/myplugin: this is where the source code for the plugin lives. Go ahead and rename this to kong/plugins/api-version.
  2. spec/myplugin: this is where the tests for your plugin reside. Rename this directory to spec/api-version and then open up each spec file and set PLUGIN_NAME to “api-version."

Once those tests pass, the test setup is complete! Next, get access to a local Kong instance. Type pongo shell, which drops you into the Kong container. No need to start the dependencies since they were already started automatically by the pongo run command above. In this prompt, enter the next two lines:

Manually Testing the Custom Lua Plugin for Kong Gateway

With the Service set up, you'll need to add a route so that the requests can be proxied through Kong:

If you see a header with the key name of Bye-World, you’re ready to write some code!

  1. handler.lua: This is where the main functionality of your plugin resides. Each phase of the request/response lifecycle has a function, which your plugin implements to provide custom behavior. I'll go into this in more detail below.
  2. schema.lua: If your plugin requires additional configuration, such as key/value pairs a user can provide to alter behavior, the logic for that is stored here.

Adding a Custom Header

Another pongo run should confirm that the test now passes.

For a final code cleanup, you can run pongo lint to run LuaCheck. LuaCheck will do a static analysis of the code and report any obvious problems (e.g., accidental global variables, etc.). It's always a good idea to lint your code because Lua is a dynamic language, and you could easily miss typos.

Enhancing Your Kong Gateway

Kong plugins are a powerful way to instantly implement policies and functionality in your API gateway. With Pongo and the kong-plugin template, Kong provides much of the starting boilerplate for you. In this example, I've only just begun to explore how plugins can allow Kong Gateway to gain expanded capabilities. If you’d like a more in-depth look at some of the things you can build, check out the Plugin Development Guide in Kong's documentation.

Check out the following further information:

Have questions or want to stay in touch with the Kong community? Join us wherever you hang out:

Star us on GitHub

🐦 Follow us on Twitter

🌎 Join the Kong Community

🍻 Join our Meetups

❓ ️Ask and answer questions on Kong Nation

💯 Apply to become a Kong Champion

Developer agility meets compliance and security. Discover how Kong can help you become an API-first company.