Blog
  • AI Gateway
  • AI Security
  • AIOps
  • API Security
  • API Gateway
|
    • API Management
    • API Development
    • API Design
    • Automation
    • Service Mesh
    • Insomnia
    • View All Blogs
  1. Home
  2. Blog
  3. Engineering
  4. Building a Kong Gateway Plugin with JavaScript
Engineering
May 26, 2021
4 min read

Building a Kong Gateway Plugin with JavaScript

Michael Heap
Sr Director Developer Experience, Kong

We recently sat down to discuss the language for the next Kong Gateway Plugin Development Kit (PDK). Given the number of JavaScript developers in the world and the variety of libraries and debugging tools available, there was only one logical choice. I'm excited to share that with the Kong Gateway (OSS) 2.4 release, that functionality is now available to you all!

To show the power of the new JavaScript PDK, we're going to implement a plugin that adds X-Clacks-Overhead, a non-standardized HTTP header based on the work of Terry Pratchett to all responses.

Bootstrapping Your Development Environment

The JavaScript plugin support in Kong Gateway works by running a Node.js server on the same machine as Kong Gateway and passing messages back and forth using msgpack.

This means that we need a development environment that can run both the Kong Gateway and a Node.js process. You can configure this on your local machine, but to make things easier, I've put together a docker–based environment for you to use.

It might take a minute or two to download the images and build our Node.js environment. I recommend running it now in the background as you keep reading:

Creating Your First Plugin

The configuration provided in the environment we created reads all plugins from the plugins directory. It's currently empty as we have not created our first plugin yet.

The JavaScript PDK uses the name of the JS file as the name of the plugin. Let's go ahead and create a file called clacks.js in the plugins directory with the following contents:

The kong object passed into the access method is an instance of the JavaScript PDK provided by the plugin server. This means that we do not need to require kong-pdk in our plugins, as it is automatically made available.

There are five phases available for HTTP requests in the life-cycle of a Kong Gateway request:

  • certificate – Executed once per request when the connection is SSL/TLS enabled
  • rewrite – Performed before the API gateway does any routing
  • access – All routing is done, and the plugin knows which service the request is bound to. This is the last phase before the API gateway makes a request to upstream
  • response – Allows you to manipulate the response from the upstream. Implementing this phase has a performance penalty as it enables request buffering
  • log – Executed after the request has been completed

Enable the Plugin

The environment we're running uses Kong's declarative config capability. That means that we need to update the config file to enable our new plugin. Open up config/kong.yml, and you should see a service defined that proxies to mockbin.org:

As our file name was clacks.js, our plugin will be called clacks. Let's enable the plugin in the definition now:

Kong Gateway only allows you to use plugins that are on an allowlist for security purposes, so we'll also need to add clacks to that list. Open up docker-compose.yml and edit the value of KONG_PLUGINS so that it looks like the following:

Making a Request

At this point the API gateway is ready to run our new plugin, so let's go ahead and start it:

The docker-compose.yml file forwards the API gateway port to our local machine. That means we can make requests to localhost:8000 to test our service.

I can see the X-Clacks-Overhead header in the response, which means that our plugin works as intended!

Making It Configurable

The custom JavaScript plugin we built today is a simple plugin that does one thing and does it well. I want to take a moment to show you how you can make that behavior customizable using plugin configuration too.

There is an ongoing discussion based on RFC 6648 about if custom headers need an X- prefix. Let's make our plugin configurable so that people can decide if they want to use the X- prefix.

Plugin configuration is controlled using the Schema property in module.exports at the end of clacks.js. Let's add an entry to define a use_prefix option that's a boolean with a default value of true:

Any configuration provided to the plugin is passed in using the constructor. Let's go ahead and capture that in clacks.js so that we can use it in our access method and update access so that it only adds the X- prefix if use_prefix is true:

If we run our plugin now, it will behave the same way as it did with a hardcoded X- prefix. Let's update our API gateway config in config/kong.yml to set use_prefix to false.

If we restart our API gateway by pressing Ctrl+C then running docker-compose up again, we should now be able to make a request to localhost:8000 and see Clacks-Overhead header without the X- prefix:

Conclusion

Just 20 lines of Javascript, and we have a working Kong Gateway plugin, complete with configuration options!

What we've built together is a trivial plugin, but using the environment provided and what you've learned about Kong's configuration, you can go ahead and build plugins to your heart’s content.

If you're looking for more plugin examples, take a look at some demo plugins:

  • Convert GitHub API responses from JSON to YAML (config)
  • Extract a Pokemon evolution chain from PokeAPI (config)

If you have any questions, post them on Kong Nation.

To stay in touch, join the Kong Community.

Once you've successfully set up a custom Kong plugin with JavaScript, you may find these other tutorials helpful:

  • How to Use the Kong Gateway JWT Plugin for Service Authentication
  • 4 Steps to Authorizing Services With the Kong Gateway OAuth2 Plugin
  • Getting Started With Kuma Service Mesh
API GatewayKong GatewayPlugins

More on this topic

Videos

Leveraging Kong for Secure Healthcare Interoperability

Videos

Kong Builders Nov 16- Introducing Kong Gateway Operator

See Kong in action

Accelerate deployments, reduce vulnerabilities, and gain real-time visibility. 

Get a Demo
Topics
API GatewayKong GatewayPlugins
Share on Social
Michael Heap
Sr Director Developer Experience, Kong

Recommended posts

API Gateway Cache With Kong's Proxy Cache Plugin

Kong Logo
EngineeringFebruary 24, 2022

In applications built on a system of microservices , developers should always be on the lookout for opportunities to eliminate unnecessary use of resources, such as database queries, network hops or service requests. API gateway cache (or response

Viktor Gamov

Reworked Plugin Queues in Kong Gateway 3.3

Kong Logo
Product ReleasesMay 25, 2023

Starting with the 3.3 release, Kong Gateway includes a new implementation of the internal queues that are used by several plugins to decouple the production of data in the proxy path and its submission to a receiving server, such as a log server. We

Hans Hübner

How to Track Service Level Objectives with Kong and OpenTelemetry

Kong Logo
EngineeringFebruary 6, 2025

In this blog post, we will explore how organizations can leverage Kong and OpenTelemetry to establish and monitor Service Level Objectives (SLOs) and manage error budgets more effectively. By tracking performance metrics and error rates against pred

Sachin Ghumbre

Kong Konnect EKS Marketplace Add-on for Kong Gateway Data Planes

Kong Logo
EngineeringDecember 7, 2023

Today, we’re excited to release the Kong Konnect EKS Marketplace add-on as a means to deploy your Kong Gateway dataplanes in AWS. The add-ons are a step forward in providing fully managed Kubernetes clusters. It is here to simplify the post-procurem

Danny Freese

Gateway API: From Early Years to GA

Kong Logo
EngineeringNovember 7, 2023

In the Kubernetes world, the Ingress API has been the longstanding staple for getting access to your Services from outside your cluster network. Ingress has served us well over the years and can be found present in several dozen different implementa

Shane Utt

Governing GraphQL APIs with Kong Gateway

Kong Logo
EngineeringOctober 20, 2023

Modern software design relies heavily on distributed systems architecture, requiring all APIs to be robust and secure. GraphQL is no exception and is commonly served over HTTP, subjecting it to the same management concerns as any REST-based API. In

Rick Spurgeon

Using Kong Gateway to Adapt SOAP Services to the JSON World

Kong Logo
EngineeringSeptember 6, 2023

While JSON-based APIs are ubiquitous in the API-centric world of today, many industries adapted internet-based protocols for automated information exchange way before REST and JSON became popular. One attempt to establish a standardized protocol sui

Hans Hübner

Ready to see Kong in action?

Get a personalized walkthrough of Kong's platform tailored to your architecture, use cases, and scale requirements.

Get a Demo
Powering the API world

Increase developer productivity, security, and performance at scale with the unified platform for API management, AI gateways, service mesh, and ingress controller.

Sign up for Kong newsletter

    • Platform
    • Kong Konnect
    • Kong Gateway
    • Kong AI Gateway
    • Kong Insomnia
    • Developer Portal
    • Gateway Manager
    • Cloud Gateway
    • Get a Demo
    • Explore More
    • Open Banking API Solutions
    • API Governance Solutions
    • Istio API Gateway Integration
    • Kubernetes API Management
    • API Gateway: Build vs Buy
    • Kong vs Postman
    • Kong vs MuleSoft
    • Kong vs Apigee
    • Documentation
    • Kong Konnect Docs
    • Kong Gateway Docs
    • Kong Mesh Docs
    • Kong AI Gateway
    • Kong Insomnia Docs
    • Kong Plugin Hub
    • Open Source
    • Kong Gateway
    • Kuma
    • Insomnia
    • Kong Community
    • Company
    • About Kong
    • Customers
    • Careers
    • Press
    • Events
    • Contact
    • Pricing
  • Terms
  • Privacy
  • Trust and Compliance
  • © Kong Inc. 2025