Skip to content
Kong Docs are moving soon! Our docs are migrating to a new home. You'll be automatically redirected to the new site in the future. In the meantime, view this page on the new site!
Kong Logo | Kong Docs Logo
  • Docs
    • Explore the API Specs
      View all API Specs View all API Specs View all API Specs arrow image
    • Documentation
      API Specs
      Kong Gateway
      Lightweight, fast, and flexible cloud-native API gateway
      Kong Konnect
      Single platform for SaaS end-to-end connectivity
      Kong AI Gateway
      Multi-LLM AI Gateway for GenAI infrastructure
      Kong Mesh
      Enterprise service mesh based on Kuma and Envoy
      decK
      Helps manage Kong’s configuration in a declarative fashion
      Kong Ingress Controller
      Works inside a Kubernetes cluster and configures Kong to proxy traffic
      Kong Gateway Operator
      Manage your Kong deployments on Kubernetes using YAML Manifests
      Insomnia
      Collaborative API development platform
  • Plugin Hub
    • Explore the Plugin Hub
      View all plugins View all plugins View all plugins arrow image
    • Functionality View all View all arrow image
      View all plugins
      AI's icon
      AI
      Govern, secure, and control AI traffic with multi-LLM AI Gateway plugins
      Authentication's icon
      Authentication
      Protect your services with an authentication layer
      Security's icon
      Security
      Protect your services with additional security layer
      Traffic Control's icon
      Traffic Control
      Manage, throttle and restrict inbound and outbound API traffic
      Serverless's icon
      Serverless
      Invoke serverless functions in combination with other plugins
      Analytics & Monitoring's icon
      Analytics & Monitoring
      Visualize, inspect and monitor APIs and microservices traffic
      Transformations's icon
      Transformations
      Transform request and responses on the fly on Kong
      Logging's icon
      Logging
      Log request and response data using the best transport for your infrastructure
  • Support
  • Community
  • Kong Academy
Get a Demo Start Free Trial
Kong Gateway
2.8.x LTS
  • Home icon
  • Kong Gateway
  • Admin API
  • Event Hooks
  • Event Hooks Examples
github-edit-pageEdit this page
report-issueReport an issue
  • Kong Gateway
  • Kong Konnect
  • Kong Mesh
  • Kong AI Gateway
  • Plugin Hub
  • decK
  • Kong Ingress Controller
  • Kong Gateway Operator
  • Insomnia
  • Kuma

  • Docs contribution guidelines
  • 3.10.x (latest)
  • 3.9.x
  • 3.8.x
  • 3.7.x
  • 3.6.x
  • 3.5.x
  • 3.4.x (LTS)
  • 3.3.x
  • 2.8.x (LTS)
  • Archive (3.0.x and pre-2.8.x)
  • Introduction
    • Overview of Kong Gateway
    • Version Support Policy
    • Stages of Software Availability
    • Changelog
  • Install and Run
    • Overview
    • Kubernetes
    • Helm
    • OpenShift with Helm
    • Docker
    • Amazon Linux
    • CentOS
    • Debian
    • RHEL
    • Ubuntu
    • Migrating from OSS to EE
    • Upgrade Kong Gateway
    • Upgrade Kong Gateway OSS
    • Upgrade from 2.8 LTS to 3.4 LTS
  • Get Started
    • Quickstart Guide
      • Configuring a Service
      • Configuring a gRPC Service
      • Enabling Plugins
      • Adding Consumers
    • Comprehensive Guide
      • Prepare to Administer
      • Expose your Services
      • Protect your Services
      • Improve Performance
      • Secure Services
      • Set Up Intelligent Load Balancing
      • Manage Administrative Teams
      • Publish, Locate, and Consume Services
  • Plan and Deploy
    • Running Kong as a Non-Root User
    • Resource Sizing Guidelines
    • Hybrid Mode
      • Deploy Kong Gateway in Hybrid Mode
    • Kubernetes Deployment Options
    • Control Kong Gateway through systemd
    • Performance Testing Framework
    • DNS Considerations
    • Default Ports
    • Licenses
      • Access Your License
      • Deploy Your License
      • Monitor License Usage
    • Security
      • Start Kong Gateway Securely
      • Keyring and Data Encryption
      • Kong Security Update Process
      • Secrets Management
        • Getting Started
        • Advanced Usage
        • Backends
          • Environment Variables
          • AWS Secrets Manager
          • GCP Secret Manager
          • HashiCorp Vault
        • Reference Format
  • Configure
    • Authentication and Authorization
      • Authentication Reference
      • OpenID Connect Plugin
        • OpenID Connect with Curity
        • OpenID Connect with Azure AD
        • OpenID Connect with Google
        • OpenID Connect with Okta
        • OpenID Connect with Auth0
        • OpenID Connect with Cognito
        • OpenID Connect Plugin Reference
      • Allowing Multiple Authentication Methods
      • Auth for Kong Manager
        • Create a Super Admin
        • Configure Networking
        • Configure Kong Manager to Send Email
        • Reset Passwords and RBAC Tokens
        • Configure Workspaces
        • Basic Auth
        • LDAP
        • OIDC
        • Sessions
      • Role-based Access Control (RBAC)
        • Add a Role
        • Add a User
        • Add an Admin
      • Mapping LDAP Service Directory Groups to Kong Roles
    • Configure gRPC Plugins
    • GraphQL Quickstart
    • Logging Reference
    • Network and Firewall
  • Dev Portal
    • Overview
    • Enable the Dev Portal
    • Structure and File Types
    • Portal API Documentation
    • Working with Templates
    • Using the Editor
    • Configuration
      • Authentication
        • Basic Auth
        • Key Auth
        • OIDC
        • Sessions
        • Adding Custom Registration Fields
      • SMTP
      • Workspaces
    • Administration
      • Manage Developers
      • Developer Roles and Content Permissions
      • Application Registration
        • Authorization Provider Strategy
        • Enable Application Registration
        • Enable Key Authentication for Application Registration
        • External OAuth2 Support
        • Set up Okta and Kong for external OAuth
        • Set Up Azure AD and Kong for External Authentication
        • Manage Applications
    • Customization
      • Easy Theme Editing
      • Migrating Templates Between Workspaces
      • Markdown Rendering Module
      • Customizing Portal Emails
      • Adding and Using JavaScript Assets
      • Single Page App in Dev Portal
      • Alternate OpenAPI Renderer
    • Helpers CLI
  • Monitor
    • Kong Vitals
      • Metrics
      • Reports
      • Vitals with InfluxDB
      • Vitals with Prometheus
      • Estimate Vitals Storage in PostgreSQL
    • Prometheus plugin
    • Zipkin plugin
  • Reference
    • Admin API
      • DB-less Mode
      • Declarative Configuration
      • Supported Content Types
      • Information Routes
      • Health Routes
      • Tags
      • Service Object
      • Route Object
      • Consumer Object
      • Plugin Object
      • Certificate Object
      • CA Certificate Object
      • SNI Object
      • Upstream Object
      • Target Object
      • Vaults Beta
      • Licenses
        • Licenses Reference
        • Licenses Examples
      • Workspaces
        • Workspaces Reference
        • Workspace Examples
      • RBAC
        • RBAC Reference
        • RBAC Examples
      • Admins
        • API Reference
        • Examples
      • Developers
      • Consumer Groups
        • API Reference
        • Examples
      • Event Hooks
        • Event Hooks Reference
        • Examples
      • Audit Logging
      • Keyring and Data Encryption
      • Securing the Admin API
    • DB-less and Declarative Configuration
    • Configuration Reference
    • CLI Reference
    • Load Balancing Reference
    • Proxy Reference
    • Rate Limiting Library
    • Health Checks and Circuit Breakers Reference
    • Clustering Reference
    • Plugin Development Kit
      • kong.client
      • kong.client.tls
      • kong.cluster
      • kong.ctx
      • kong.ip
      • kong.log
      • kong.nginx
      • kong.node
      • kong.request
      • kong.response
      • kong.router
      • kong.service
      • kong.service.request
      • kong.service.response
      • kong.table
      • kong.vault
    • Plugin Development Guide
      • Introduction
      • File structure
      • Implementing custom logic
      • Plugin configuration
      • Accessing the datastore
      • Storing custom entities
      • Caching custom entities
      • Extending the Admin API
      • Writing tests
      • (un)Installing your plugin
    • Plugins in Other Languages
    • File Permissions Reference
enterprise-switcher-icon Switch to OSS
On this pageOn this page
  • Webhook
  • Custom webhook
  • Log
  • Lambda
You are browsing documentation for an older version. See the latest documentation here.

Event Hooks Examples

Event hooks are outbound calls from Kong Gateway. With event hooks, the Kong Gateway can communicate with target services or resources, letting the target know that an event was triggered. When an event is triggered in Kong, it calls a URL with information about that event. Event hooks add a layer of configuration for subscribing to worker events using the admin interface. Worker events are integrated into Kong Gateway to communicate within the gateway context. For example, when an entity is created, the Kong Gateway fires an event with information about the entity. Parts of the Kong Gateway codebase can subscribe to these events, then process the events using callbacks.

In Kong Gateway, these callbacks can be defined using one of the following “handlers”:

  • webhook: Makes a JSON POST request to a provided URL with the event data as a payload. Useful for building a middle tier integration (your own webhook that receives Kong hooks). Specific headers can be configured for the request.

  • webhook-custom: Fully configurable request. Useful for building a direct integration with a service (for example, a Slack webhook). Because it’s fully configurable, it’s more complex to configure. It supports templating on a configurable body, a configurable form payload, and headers.

  • log: This handler, which requires no configuration, logs the event and the content of the payload into the Kong Gateway logs. If using hybrid mode, the crud and dao:crud sources will log on the control plane logs and the balancer and rate-limiting-advanced sources will log on the data plane logs.

  • lambda: This handler runs specified Lua code after an event is triggered.

Event hooks are exclusive to Kong Gateway and are not available in Konnect.

Webhook

Webhook event hooks make JSON POST requests to a provided URL with the event data as a payload. For this example, we will use a site that is helpful for testing webhooks: https://webhook.site.

To create a webhook event hook:

  1. Generate a URL by navigating to https://webhook.site in your web browser.
  2. Select Copy to clipboard next to Your unique URL.
  3. Create a webhook event hook on the consumers event (Kong entity the event hook will listen to for events), on the crud source (action that triggers logging), and the URL you copied from step 2 using the following HTTP request:

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/event-hooks \
    -d source=crud \
    -d event=consumers \
    -d handler=webhook \
    -d config.url=<WEBHOOK_URL>
    http -f :8001/event-hooks \
    source=crud \
    event=consumers \
    handler=webhook \
    config.url=<WEBHOOK_URL>
  4. Navigate to the URL from step 2. You should see a POST request, of type ping, notifying our webhook endpoint about the creation of this webhook.
  5. In Kong Manager or Kong Admin API, add a consumer from any workspace.

    Kong Manager
    Admin API
    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. Select the Create button.

    Create a consumer, Ada Lovelace, by making the following HTTP request to your instance of the Kong Admin API:

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/consumers \
    -d username="Ada Lovelace"
    http -f :8001/consumers \
    username="Ada Lovelace"
  6. Check the URL from the https://webhook.site page. You should see an entry with data for the new consumer in its payload.

     {
     "source": "crud",
     "entity": {
       "created_at": 1627581878,
       "type": 0,
       "username": "Ada Lovelace",
       "id": "0fd2319f-13ea-4582-a448-8d11893026a8"
     },
     "event": "consumers",
     "operation": "create",
     "schema": "consumers"
     }
    

Custom webhook

Custom webhook event hooks are fully customizable requests. Custom webhooks are useful for building direct integration with a service. Because custom webhooks are fully configurable, they have more complex configurations. Custom webhooks support Lua templating on a configurable body, form payload, and headers. For a list of possible fields for templating, see the sources endpoint.

The following example sends a message to Slack any time a new administrator is invited to Kong Gateway. Slack allows for incoming webhooks and we can use these to build an integration with Kong’s event hooks features.

To create a custom webhook event hook:

  1. Create an app in Slack.
  2. Activate incoming webhooks in the settings for your new app.
  3. Select to Add New Webhook to Workspace, select the channel where you wish to receive notices, and select Allow.
  4. Copy the Webhook URL, for example https://hooks.slack.com/services/foo/bar/baz.
  5. Create a webhook event hook on the admins event (Kong entity the event hook will listen to for events), and the crud source (action that triggers logging), and format the payload as, “Admin account `{{ entity.username }}` {{ operation }}d; e-mail address set to `{{ entity.email }}`”, using the following HTTP request:

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/event-hooks \
    -d source=crud \
    -d event=admins \
    -d handler=webhook-custom \
    -d config.method=POST \
    -d config.url=<WEBHOOK_URL> \
    -d config.headers.content-type="application/json" \
    -d config.payload.text="Admin account \`{{ entity.username }}\` {{ operation}}d; email address set to \`{{ entity.email }}\`"
    http -f :8001/event-hooks \
    source=crud \
    event=admins \
    handler=webhook-custom \
    config.method=POST \
    config.url=<WEBHOOK_URL> \
    config.headers.content-type="application/json" \
    config.payload.text="Admin account \`{{ entity.username }}\` {{ operation}}d; email address set to \`{{ entity.email }}\`"
  6. Turn on RBAC.

    To enable RBAC, you will need the initial KONG_PASSWORD that was used when you first installed Kong Gateway and ran migrations. This is also the default password for the Super Admin, and will be required once RBAC is on.

    UNIX-based system or Windows
    Docker
    1. Modify configuration settings below in your kong.conf file. Navigate to the file at /etc/kong/kong.conf:
       cd /etc/kong/
    2. Copy the kong.conf.default file so you know you have a working copy to fall back to.
       cp kong.conf.default kong.conf
    3. Now, edit the following settings in kong.conf:

       echo >> “enforce_rbac = on” >> /etc/kong/kong.conf
       echo >> “admin_gui_auth = basic-auth” >> /etc/kong.conf
       echo >> “admin_gui_session_conf = {"secret":"secret","storage":"kong","cookie_secure":false}”

      This turns on RBAC, tells Kong Gateway to use basic authentication (username/password), and tells the Sessions plugin how to create a session cookie.

      The cookie is used for all subsequent requests to authenticate the user until it expires. The session has a limited duration and renews at a configurable interval, which helps prevent an attacker from obtaining and using a stale cookie after the session has ended.

    4. Restart Kong Gateway and point to the new config file:
       kong restart -c /etc/kong/kong.conf

    If you have a Docker installation, run the following command to set the needed environment variables and reload the gateway’s configuration.

    Note: Make sure to replace {KONG-CONTAINER-ID} with the ID of your container.

    echo "KONG_ENFORCE_RBAC=on
    KONG_ADMIN_GUI_AUTH=basic-auth
    KONG_ADMIN_GUI_SESSION_CONF='{\"secret\":\"secret\",\"storage\":\"kong\",\"cookie_secure\":false}'
    kong reload exit" | docker exec -i {KONG_CONTAINER_ID} /bin/sh

    This turns RBAC on, tells Kong Gateway to use basic authentication (username/password), and tells the Sessions plugin how to create a session cookie.

    The cookie is used for all subsequent requests to authenticate the user, until it expires. The session has a limited duration and renews at a configurable interval, which helps prevent an attacker from obtaining and using a stale cookie after the session has ended.

    Outside of this guide, you will likely want to modify these settings differently, depending on your installation. You can read more about these settings here: Basic Auth for Kong Manager.

  7. Invite an Admin using Kong Manager or the Kong Admin API.

    Kong Manager
    Admin API
    1. Go to Kong Manager, or reload the page if you already have it open and you will see a login screen.
    2. Log in to Kong Manager with the built-in Super Admin account, kong_admin, and its password. This is the initial KONG_PASSWORD you used when you ran migrations during installation.
    3. From the Teams > Admins tab, click Invite Admin.
    4. Enter the new administrator’s Email address and Username.
    5. Click Invite Admin to send the invite. At this point in the getting started guide, you likely haven’t set up SMTP yet, so no email will be sent.

    Create an admin, Arya Stark, by making the following HTTP request to your instance of the Kong Admin API:

    Note: Replace <KONG_ADMIN_PASSWORD> with your kong_admin password. This is the initial KONG_PASSWORD you used when you ran migrations during installation.

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/admins \
    -d username="Arya Stark" \
    -d email=arya@gameofthrones.com \
    -H Kong-Admin-Token:<KONG_ADMIN_PASSWORD>
    http -f :8001/admins \
    username="Arya Stark" \
    email=arya@gameofthrones.com \
    Kong-Admin-Token=<KONG_ADMIN_PASSWORD>

Afterwards, you should receive a message in the Slack channel you selected with the message you included as the config.payload.text.

Log

Log event hooks log the specified event and content of the payload into the Kong Gateway logs.

To create a log event hook:

  1. Create a log event hook on the consumers event (Kong entity the event hook will listen to for events) and on the crud source (action that triggers logging) using the following HTTP request:

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/event-hooks \
    -d source=crud \
    -d event=consumers \
    -d handler=log
    http -f :8001/event-hooks \
    source=crud \
    event=consumers \
    handler=log
  2. In Kong Manager or Kong Admin API, add a consumer from any workspace.

    Kong Manager
    Admin API
    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. Select the Create button.

    Create a consumer, Elizabeth Bennet, by making the following HTTP request to your instance of the Kong Admin API:

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/consumers \
    -d username="Elizabeth Bennet"
    http -f :8001/consumers \
    username="Elizabeth Bennet"
  3. You should see an entry with data for the new consumer in the payload in Kong’s error log, which is typically accessible at /usr/local/kong/logs/error.log.

     172.19.0.1 - - [29/Jul/2021:15:57:15 +0000] "POST /consumers HTTP/1.1" 409 147 "-" "HTTPie/2.4.0"
     2021/07/29 15:57:26 [notice] 68854#0: *819021 +--------------------------------------------------+, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |[kong] event_hooks.lua:?:452 "log callback: " { "consumers", "crud", {|, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |    entity = {                                    |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |      created_at = 1627574246,                    |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |      id = "4757bd6b-8d54-4b08-bf24-01e346a9323e",|, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |      type = 0,                                   |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |      username = "Elizabeth Bennet"               |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |    },                                            |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |    operation = "create",                         |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |    schema = "consumers"                          |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 |  }, 68854 }                                      |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
     2021/07/29 15:57:26 [notice] 68854#0: *819021 +--------------------------------------------------+, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    
    

Lambda

The lambda event hook allows you to write completely custom logic in Lua code and hook it into a variety of Kong events. The following example writes a log entry any time a consumer changes, but conditionally and with custom formatting.

The lambda event hook type is extremely powerful: you can write completely custom logic to handle any use case you want. However, it’s restricted by default through the sandbox.. This sandbox is put in place to keep users safe: it’s easy to inadvertently add unsafe libraries/objects into the sandbox and leave the Kong Gateway exposed to security vulnerabilities. Use caution before modifying these sandbox settings.

To create a lambda event hook:

  1. Create a Lua script to load into the lambda event hook and save it to a file named lambda.lua on your home directory.

     return function (data, event, source, pid)
       local user = data.entity.username
       error("Event hook on consumer " .. user .. "")
     end
    
  2. Create a lambda event hook on the consumers event (Kong entity the event hook will listen to for events) and on the crud source (action that triggers logging) using the following HTTP request:

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/event-hooks \
    -d source=crud \
    -d event=consumers \
    -d handler=lambda \
    -F config.functions='return function (data, event, source, pid) local user = data.entity.username error("Event hook on consumer " .. user .. "")end'
    http -f :8001/event-hooks \
    source=crud \
    event=consumers \
    handler=lambda \
    config.functions[]=@~/lambda.lua
  3. In Kong Manager or Kong Admin API, add a consumer to any workspace.

    Kong Manager
    Admin API
    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. Select the Create button.

    Create a consumer, Lois Lane, by making the following HTTP request to your instance of the Kong Admin API:

    cURL
    HTTPie
    curl -i -X POST http://localhost:8001/consumers \
    -d username="Lois Lane"
    http -f :8001/consumers \
    username="Lois Lane"
  4. You should see an entry “Event hook on consumer Lois Lane” in Kong’s error log, which is typically accessible at /usr/local/kong/logs/error.log.

     2021/07/29 21:52:54 [error] 114#0: *153047 [kong] event_hooks.lua:190 [string "return function (data, event, source, pid)..."]:3: Event hook on consumer Lois Lane, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    
Thank you for your feedback.
Was this page useful?
Too much on your plate? close cta icon
More features, less infrastructure with Kong Konnect. 1M requests per month for free.
Try it for Free
  • Kong
    Powering the API world

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

    • Products
      • Kong Konnect
      • Kong Gateway Enterprise
      • Kong Gateway
      • Kong Mesh
      • Kong Ingress Controller
      • Kong Insomnia
      • Product Updates
      • Get Started
    • Documentation
      • Kong Konnect Docs
      • Kong Gateway Docs
      • Kong Mesh Docs
      • Kong Insomnia Docs
      • Kong Konnect Plugin Hub
    • Open Source
      • Kong Gateway
      • Kuma
      • Insomnia
      • Kong Community
    • Company
      • About Kong
      • Customers
      • Careers
      • Press
      • Events
      • Contact
  • Terms• Privacy• Trust and Compliance
© Kong Inc. 2025