Skip to content
Kong Logo | Kong Docs Logo
search
  • We're Hiring!
  • Docs
    • Kong Gateway
    • Kong Konnect
    • Kong Mesh
    • Plugin Hub
    • decK
    • Kubernetes Ingress Controller
    • Insomnia
    • Kuma

    • Docs contribution guidelines
  • Plugin Hub
  • Support
  • Community
  • Kong Academy
Get a Demo Start Free Trial
  • Kong Gateway
  • Kong Konnect
  • Kong Mesh
  • Plugin Hub
  • decK
  • Kubernetes Ingress Controller
  • Insomnia
  • Kuma

  • Docs contribution guidelines
  • 3.2.x (latest)
  • 3.1.x
  • 3.0.x
  • 2.8.x
  • 2.7.x
  • 2.6.x
  • Older Enterprise versions (2.1-2.5)
  • Older OSS versions (2.1-2.5)
  • Archive (pre-2.1)
    • Overview of Kong Gateway
      • Version Support Policy
      • Supported Installation Options
      • Supported Linux Distributions
    • Stability
    • Release Notes
      • Services
        • Overview
        • Configure Routes with Expressions
      • Upstreams
      • Plugins
      • Routing Traffic
      • Load Balancing
      • Health Checks and Circuit Breakers
      • Kong Performance Testing
    • Glossary
    • Get Kong
    • Services and Routes
    • Rate Limiting
    • Proxy Caching
    • Key Authentication
    • Load-Balancing
      • Overview
        • Overview
        • Deploy Kong Gateway in Hybrid mode
      • DB-less Deployment
      • Traditional
      • Overview
        • Helm
        • OpenShift with Helm
        • kubectl apply
        • Kubernetes Deployment Options
        • Using docker run
        • Build your own Docker images
        • Amazon Linux
        • Debian
        • Red Hat
        • Ubuntu
      • Running Kong as a non-root user
      • Securing the Admin API
      • Using systemd
      • Start Kong Gateway Securely
      • Programatically Creating Admins
      • Enabling RBAC
      • Overview
      • Download your License
      • Deploy Enterprise License
      • Using the License API
      • Monitor Licenses Usage
      • Default Ports
      • DNS Considerations
      • Network and Firewall
      • CP/DP Communication through a Forward Proxy
    • Kong Configuration File
    • Environment Variables
    • Serving a Website and APIs from Kong
      • Overview
      • Prometheus
      • StatsD
      • Datadog
      • Overview
      • Writing a Custom Trace Exporter
      • Tracing API Reference
    • Resource Sizing Guidelines
    • Security Update Process
    • Blue-Green Deployments
    • Canary Deployments
    • Clustering Reference
      • Log Reference
      • Dynamic log level updates
      • Customize Gateway Logs
      • Upgrade Kong Gateway 3.1.x
      • Migrate from OSS to Enterprise
    • Overview
      • Overview
      • Metrics
      • Analytics with InfluxDB
      • Analytics with Prometheus
      • Estimate Analytics Storage in PostgreSQL
      • Overview
      • Getting Started
      • Advanced Usage
        • Overview
        • Environment Variables
        • AWS Secrets Manager
        • Google Secrets Manager
        • Hashicorp Vault
        • Securing the Database with AWS Secrets Manager
      • Reference Format
      • Overview
      • Get Started with Dynamic Plugin Ordering
      • Overview
      • Enable the Dev Portal
      • Publish an OpenAPI Spec
      • Structure and File Types
      • Themes Files
      • Working with Templates
      • Using the Editor
        • Basic Auth
        • Key Auth
        • OIDC
        • Sessions
        • Adding Custom Registration Fields
        • Manage Developers
        • Developer Roles and Content Permissions
        • 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
        • 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
      • SMTP
      • Workspaces
      • Helpers CLI
      • Portal API Documentation
    • Audit Logging
    • Keyring and Data Encryption
    • Workspaces
    • Consumer Groups
    • Event Hooks
    • FIPS 140-2
    • Overview
    • Enable Kong Manager
      • Services and Routes
      • Rate Limiting
      • Proxy Caching
      • Authentication with Consumers
      • Load Balancing
      • Overview
      • Create a Super Admin
      • Workspaces and Teams
      • Reset Passwords and RBAC Tokens
      • Basic Auth
        • Configure LDAP
        • LDAP Service Directory Mapping
        • Configure OIDC
        • OIDC Authenticated Group Mapping
      • Sessions
        • Overview
        • Enable RBAC
        • Add a Role and Permissions
        • Create a User
        • Create an Admin
    • Networking Configuration
    • Workspaces
    • Create Consumer Groups
    • Sending Email
    • Overview
    • File Structure
    • Implementing Custom Logic
    • Plugin Configuration
    • Accessing the Data Store
    • Storing Custom Entities
    • Caching Custom Entities
    • Extending the Admin API
    • Writing Tests
    • (un)Installing your Plugin
      • Overview
      • kong.client
      • kong.client.tls
      • kong.cluster
      • kong.ctx
      • kong.ip
      • kong.jwe
      • kong.log
      • kong.nginx
      • kong.node
      • kong.request
      • kong.response
      • kong.router
      • kong.service
      • kong.service.request
      • kong.service.response
      • kong.table
      • kong.tracing
      • kong.vault
      • kong.websocket.client
      • kong.websocket.upstream
      • Go
      • Javascript
      • Python
      • Running Plugins in Containers
      • External Plugin Performance
    • Overview
        • Overview
        • 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
      • Authentication Reference
      • Allow Multiple Authentication Plugins
    • Rate Limiting Plugin
      • Add a Body Value
    • GraphQL
      • gRPC Plugins
      • Configure a gRPC service
    • Overview
    • Information Routes
    • Health Routes
    • Tags
    • Debug Routes
    • Services
    • Routes
    • Consumers
    • Plugins
    • Certificates
    • CA Certificates
    • SNIs
    • Upstreams
    • Targets
    • Vaults
    • Keys
    • Licenses
    • Workspaces
    • RBAC
    • Admins
    • Developers
    • Consumer Groups
    • Event Hooks
    • Keyring and Data Encryption
    • Audit Logs
    • kong.conf
    • Injecting Nginx Directives
    • CLI
    • File Permissions Reference
    • Key Management
    • Performance Testing Framework
    • Router Expressions Language
    • FAQ

github-edit-pageEdit this page

report-issueReport an issue

enterprise-switcher-iconSwitch to OSS

On this page
  • kong.response.get_status()
  • kong.response.get_header(name)
  • kong.response.get_headers([max_headers])
  • kong.response.get_source()
  • kong.response.set_status(status)
  • kong.response.set_header(name, value)
  • kong.response.add_header(name, value)
  • kong.response.clear_header(name)
  • kong.response.set_headers(headers)
  • kong.response.get_raw_body()
  • kong.response.set_raw_body(body)
  • kong.response.exit(status[, body[, headers]])
  • kong.response.error(status[, message[, headers]])
Kong Gateway
3.1.x
  • Home
  • Kong Gateway
  • Plugin Development
  • PDK
  • kong.response
You are browsing documentation for an outdated version. See the latest documentation here.

kong.response

Client response module.

The downstream response module contains a set of functions for producing and manipulating responses sent back to the client (downstream). Responses can be produced by Kong (for example, an authentication plugin rejecting a request), or proxied back from an Service’s response body.

Unlike kong.service.response, this module allows mutating the response before sending it back to the client.

kong.response.get_status()

Returns the HTTP status code currently set for the downstream response (as a Lua number).

If the request was proxied (as per kong.response.get_source()), the return value is the response from the Service (identical to kong.service.response.get_status()).

If the request was not proxied and the response was produced by Kong itself (i.e. via kong.response.exit()), the return value is returned as-is.

Phases

  • header_filter, response, body_filter, log, admin_api

Returns

  • number: status The HTTP status code currently set for the downstream response.

Usage

kong.response.get_status() -- 200

kong.response.get_header(name)

Returns the value of the specified response header, as would be seen by the client once received.

The list of headers returned by this function can consist of both response headers from the proxied Service and headers added by Kong (e.g. via kong.response.add_header()).

The return value is either a string, or can be nil if a header with name is not found in the response. If a header with the same name is present multiple times in the request, this function returns the value of the first occurrence of this header.

Phases

  • header_filter, response, body_filter, log, admin_api

Parameters

  • name (string): The name of the header.

Header names are case-insensitive and dashes (-) can be written as underscores (_). For example, the header X-Custom-Header can also be retrieved as x_custom_header.

Returns

  • string|nil: The value of the header.

Usage

-- Given a response with the following headers:
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz

kong.response.get_header("x-custom-header") -- "bla"
kong.response.get_header("X-Another")       -- "foo bar"
kong.response.get_header("X-None")          -- nil

kong.response.get_headers([max_headers])

Returns a Lua table holding the response headers. Keys are header names. Values are either a string with the header value, or an array of strings if a header was sent multiple times. Header names in this table are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_). For example, the header X-Custom-Header can also be retrieved as x_custom_header.

A response initially has no headers. Headers are added when a plugin short-circuits the proxying by producing a header (e.g. an authentication plugin rejecting a request), or if the request has been proxied, and one of the latter execution phases is currently running.

Unlike kong.service.response.get_headers(), this function returns all headers as the client would see them upon reception, including headers added by Kong itself.

By default, this function returns up to 100 headers. The optional max_headers argument can be specified to customize this limit, but must be greater than 1 and equal to or less than 1000.

Phases

  • header_filter, response, body_filter, log, admin_api

Parameters

  • max_headers (number, optional): Limits the number of headers parsed.

Returns

  1. table: headers A table representation of the headers in the response.

  2. string: err If more headers than max_headers were present, returns a string with the error "truncated".

Usage

-- Given an response from the Service with the following headers:
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz

local headers = kong.response.get_headers()

headers.x_custom_header -- "bla"
headers.x_another[1]    -- "foo bar"
headers["X-Another"][2] -- "baz"

kong.response.get_source()

This function helps determine where the current response originated from. Since Kong is a reverse proxy, it can short-circuit a request and produce a response of its own, or the response can come from the proxied Service.

Returns a string with three possible values:

  • "exit" is returned when, at some point during the processing of the request, there has been a call to kong.response.exit(). This happens when the request was short-circuited by a plugin or by Kong itself (e.g. invalid credentials).
  • "error" is returned when an error has happened while processing the request. For example, a timeout while connecting to the upstream service.
  • "service" is returned when the response was originated by successfully contacting the proxied Service.

Phases

  • header_filter, response, body_filter, log, admin_api

Returns

  • string: The source.

Usage

if kong.response.get_source() == "service" then
  kong.log("The response comes from the Service")
elseif kong.response.get_source() == "error" then
  kong.log("There was an error while processing the request")
elseif kong.response.get_source() == "exit" then
  kong.log("There was an early exit while processing the request")
end

kong.response.set_status(status)

Allows changing the downstream response HTTP status code before sending it to the client.

Phases

  • rewrite, access, header_filter, response, admin_api

Parameters

  • status (number): The new status.

Returns

  • Nothing; throws an error on invalid input.

Usage

kong.response.set_status(404)

kong.response.set_header(name, value)

Sets a response header with the given value. This function overrides any existing header with the same name.

Note: Underscores in header names are automatically transformed into dashes by default. If you want to deactivate this behavior, set the lua_transform_underscores_in_response_headers Nginx config option to off.

This setting can be set in the Kong Config file:

 nginx_http_lua_transform_underscores_in_response_headers = off

Be aware that changing this setting might break any plugins that rely on the automatic underscore conversion. You cannot set Transfer-Encoding header with this function. It will be ignored.

Phases

  • rewrite, access, header_filter, response, admin_api

Parameters

  • name (string): The name of the header
  • value (string|number|boolean): The new value for the header.

Returns

  • Nothing; throws an error on invalid input.

Usage

kong.response.set_header("X-Foo", "value")

kong.response.add_header(name, value)

Adds a response header with the given value. Unlike kong.response.set_header(), this function does not remove any existing header with the same name. Instead, another header with the same name is added to the response. If no header with this name already exists on the response, then it is added with the given value, similarly to kong.response.set_header().

Phases

  • rewrite, access, header_filter, response, admin_api

Parameters

  • name (string): The header name.
  • value (string|number|boolean): The header value.

Returns

  • Nothing; throws an error on invalid input.

Usage

kong.response.add_header("Cache-Control", "no-cache")
kong.response.add_header("Cache-Control", "no-store")

kong.response.clear_header(name)

Removes all occurrences of the specified header in the response sent to the client.

Phases

  • rewrite, access, header_filter, response, admin_api

Parameters

  • name (string): The name of the header to be cleared

Returns

  • Nothing; throws an error on invalid input.

Usage

kong.response.set_header("X-Foo", "foo")
kong.response.add_header("X-Foo", "bar")

kong.response.clear_header("X-Foo")
-- from here onwards, no X-Foo headers will exist in the response

kong.response.set_headers(headers)

Sets the headers for the response. Unlike kong.response.set_header(), the headers argument must be a table in which each key is a string corresponding to a header’s name, and each value is a string, or an array of strings.

The resulting headers are produced in lexicographical order. The order of entries with the same name (when values are given as an array) is retained.

This function overrides any existing header bearing the same name as those specified in the headers argument. Other headers remain unchanged.

You cannot set Transfer-Encoding header with this function. It will be ignored.

Phases

  • rewrite, access, header_filter, response, admin_api

Parameters

  • headers (table):

Returns

  • Nothing; throws an error on invalid input.

Usage

kong.response.set_headers({
  ["Bla"] = "boo",
  ["X-Foo"] = "foo3",
  ["Cache-Control"] = { "no-store", "no-cache" }
})

-- Will add the following headers to the response, in this order:
-- X-Bar: bar1
-- Bla: boo
-- Cache-Control: no-store
-- Cache-Control: no-cache
-- X-Foo: foo3

kong.response.get_raw_body()

Returns the full body when the last chunk has been read.

Calling this function starts buffering the body in an internal request context variable, and sets the current chunk (ngx.arg[1]) to nil when the chunk is not the last one. When it reads the last chunk, the function returns the full buffered body.

Phases

  • body_filter

Returns

  • string: body The full body when the last chunk has been read, otherwise returns nil.

Usage

local body = kong.response.get_raw_body()
if body then
  body = transform(body)
  kong.response.set_raw_body(body)
end

kong.response.set_raw_body(body)

Sets the body of the response.

The body argument must be a string and is not processed in any way. This function can’t change the Content-Length header if one was added. If you decide to use this function, the Content-Length header should also be cleared, for example in the header_filter phase.

Phases

  • body_filter

Parameters

  • body (string): The raw body.

Returns

  • Nothing; throws an error on invalid inputs.

Usage

kong.response.set_raw_body("Hello, world!")
-- or
local body = kong.response.get_raw_body()
if body then
  body = transform(body)
  kong.response.set_raw_body(body)
end

kong.response.exit(status[, body[, headers]])

This function interrupts the current processing and produces a response. It is typical to see plugins using it to produce a response before Kong has a chance to proxy the request (e.g. an authentication plugin rejecting a request, or a caching plugin serving a cached response).

It is recommended to use this function in conjunction with the return operator, to better reflect its meaning:

 return kong.response.exit(200, "Success")

Calling kong.response.exit() interrupts the execution flow of plugins in the current phase. Subsequent phases will still be invoked. For example, if a plugin calls kong.response.exit() in the access phase, no other plugin is executed in that phase, but the header_filter, body_filter, and log phases are still executed, along with their plugins. Plugins should be programmed defensively against cases when a request is not proxied to the Service, but instead is produced by Kong itself.

  1. The first argument status sets the status code of the response that is seen by the client.

    In L4 proxy mode, the status code provided is primarily for logging and statistical purposes, and is not visible to the client directly. In this mode, only the following status codes are supported:

    • 200 - OK
    • 400 - Bad request
    • 403 - Forbidden
    • 500 - Internal server error
    • 502 - Bad gateway
    • 503 - Service unavailable
  2. The second, optional, body argument sets the response body. If it is a string, no special processing is done, and the body is sent as-is. It is the caller’s responsibility to set the appropriate Content-Type header via the third argument.

    As a convenience, body can be specified as a table. In that case, the body is JSON-encoded and has the application/json Content-Type header set.

    On gRPC, we cannot send the body with this function, so it sends "body" in the grpc-message header instead.

    • If the body is a table, it looks for the message field in the body, and uses that as a grpc-message header.
    • If you specify application/grpc in the Content-Type header, the body is sent without needing the grpc-message header.

    In L4 proxy mode, body can only be nil or a string. Automatic JSON encoding is not available. When body is provided, depending on the value of status, the following happens:

    • When status is 500, 502 or 503, then body is logged in the Kong error log file.
    • When the status is anything else, body is sent back to the L4 client.
  3. The third, optional, headers argument can be a table specifying response headers to send. If specified, its behavior is similar to kong.response.set_headers(). This argument is ignored in L4 proxy mode.

Unless manually specified, this method automatically sets the Content-Length header in the produced response for convenience.

Phases

  • preread, rewrite, access, admin_api, header_filter (only if body is nil)

Parameters

  • status (number): The status to be used.
  • body (table|string, optional): The body to be used.
  • headers (table, optional): The headers to be used.

Returns

  • Nothing; throws an error on invalid input.

Usage

return kong.response.exit(403, "Access Forbidden", {
  ["Content-Type"] = "text/plain",
  ["WWW-Authenticate"] = "Basic"
})

---

return kong.response.exit(403, [[{"message":"Access Forbidden"}]], {
  ["Content-Type"] = "application/json",
  ["WWW-Authenticate"] = "Basic"
})

---

return kong.response.exit(403, { message = "Access Forbidden" }, {
  ["WWW-Authenticate"] = "Basic"
})

---

-- In L4 proxy mode
return kong.response.exit(200, "Success")

kong.response.error(status[, message[, headers]])

This function interrupts the current processing and produces an error response.

It is recommended to use this function in conjunction with the return operator, to better reflect its meaning:

 return kong.response.error(500, "Error", {["Content-Type"] = "text/html"})
  1. The status argument sets the status code of the response that is seen by the client. The status code must an error code, that is, greater than 399.

  2. The optional message argument sets the message describing the error, which is written in the body.

  3. The optional headers argument can be a table specifying response headers to send. If specified, its behavior is similar to kong.response.set_headers().

This method sends the response formatted in JSON, XML, HTML or plaintext. The actual format is determined using one of the following options, in this order:

  • Manually specified in the headers argument using the Content-Type header.
  • Conforming to the Accept header from the request.
  • If there is no setting in the Content-Type or Accept header, the response defaults to JSON format. Also see the Content-Length header in the produced response for convenience.

Phases

  • rewrite, access, admin_api, header_filter (only if body is nil)

Parameters

  • status (number): The status to be used (>399).
  • message (string, optional): The error message to be used.
  • headers (table, optional): The headers to be used.

Returns

  • Nothing; throws an error on invalid input.

Usage

return kong.response.error(403, "Access Forbidden", {
  ["Content-Type"] = "text/plain",
  ["WWW-Authenticate"] = "Basic"
})

---

return kong.response.error(403, "Access Forbidden")

---

return kong.response.error(403)
Thank you for your feedback.
Was this page useful?
  • Kong
    THE CLOUD CONNECTIVITY COMPANY

    Kong powers reliable digital connections across APIs, hybrid and multi-cloud environments.

    • Company
    • Customers
    • Events
    • Investors
    • Careers Hiring!
    • Partners
    • Press
    • Contact
  • Products
    • Kong Konnect
    • Kong Gateway
    • Kong Mesh
    • Get Started
    • Pricing
  • Resources
    • eBooks
    • Webinars
    • Briefs
    • Blog
    • API Gateway
    • Microservices
  • Open Source
    • Install Kong Gateway
    • Kong Community
    • Kubernetes Ingress
    • Kuma
    • Insomnia
  • Solutions
    • Decentralize
    • Secure & Govern
    • Create a Dev Platform
    • API Gateway
    • Kubernetes
    • Service Mesh
Star
  • Terms•Privacy
© Kong Inc. 2023