kong.response

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 (e.g. 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 will be that of 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 will be 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

  1. kong.response.get_status() -- 200

Back to top

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 was not found in the response. If a header with the same name is present multiple times in the request, this function will return 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 (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header.

Returns

  • string|nil The value of the header

Usage

  1. -- Given a response with the following headers:
  2. -- X-Custom-Header: bla
  3. -- X-Another: foo bar
  4. -- X-Another: baz
  5. kong.response.get_header("x-custom-header") -- "bla"
  6. kong.response.get_header("X-Another") -- "foo bar"
  7. kong.response.get_header("X-None") -- nil

Back to top

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 (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header.

A response initially has no headers until a plugin short-circuits the proxying by producing one (e.g. an authentication plugin rejecting a request), or 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 not greater than 1000.

Phases

  • header_filter, response, body_filter, log, admin_api

Parameters

  • max_headers (number, optional): Limits how many headers are 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, a string with the error "truncated".

Usage

  1. -- Given an response from the Service with the following headers:
  2. -- X-Custom-Header: bla
  3. -- X-Another: foo bar
  4. -- X-Another: baz
  5. local headers = kong.response.get_headers()
  6. headers.x_custom_header -- "bla"
  7. headers.x_another[1] -- "foo bar"
  8. headers["X-Another"][2] -- "baz"

Back to top

kong.response.get_source()

This function helps determining where the current response originated from. Kong being 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(). In other words, 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

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

Back to top

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

  1. kong.response.set_status(404)

Back to top

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 you should set the lua_transform_underscores_in_response_headers nginx config option to off

This setting can be set in the Kong Config file:

  1. nginx_http_lua_transform_underscores_in_response_headers = off

Be aware that changing this setting might slightly break any plugins that rely on the automatic underscore conversion.

Phases

  • rewrite, access, header_filter, response, admin_api

Parameters

  • name (string): The name of the header
  • value (stringnumberboolean): The new value for the header

Returns

  • Nothing; throws an error on invalid input.

Usage

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

Back to top

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 will be 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 (stringnumberboolean): The header value

Returns

  • Nothing; throws an error on invalid input.

Usage

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

Back to top

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

  1. kong.response.set_header("X-Foo", "foo")
  2. kong.response.add_header("X-Foo", "bar")
  3. kong.response.clear_header("X-Foo")
  4. -- from here onwards, no X-Foo headers will exist in the response

Back to top

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.

Phases

  • rewrite, access, header_filter, response, admin_api

Parameters

  • headers (table):

Returns

  • Nothing; throws an error on invalid input.

Usage

  1. kong.response.set_headers({
  2. ["Bla"] = "boo",
  3. ["X-Foo"] = "foo3",
  4. ["Cache-Control"] = { "no-store", "no-cache" }
  5. })
  6. -- Will add the following headers to the response, in this order:
  7. -- X-Bar: bar1
  8. -- Bla: boo
  9. -- Cache-Control: no-store
  10. -- Cache-Control: no-cache
  11. -- X-Foo: foo3

Back to top

kong.response.get_raw_body()

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

Calling this function will start to buffer the body in an internal request context variable, and set the current chunk (ngx.arg[1]) to nil when the chunk is not the last one. Otherwise it 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

  1. local body = kong.response.get_raw_body()
  2. if body then
  3. body = transform(body)
  4. kong.response.set_raw_body(body)
  5. end

Back to top

kong.response.set_raw_body(body)

Sets the body of the response

The body argument must be a string and will not be processed in any way. This function cannot anymore change the Content-Length header if one was added. So if you decide to use this function, the Content-Length header should also be cleared, e.g. in header_filter phase.

Phases

  • body_filter

Parameters

  • body (string): The raw body

Returns

  • Nothing; throws an error on invalid inputs.

Usage

  1. kong.response.set_raw_body("Hello, world!")
  2. -- or
  3. local body = kong.response.get_raw_body()
  4. if body then
  5. body = transform(body)
  6. kong.response.set_raw_body(body)
  7. end

Back to top

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:

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

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

The first argument status will set the status code of the response that will be seen by the client.

In L4 proxy mode, only the following status code are supported:

  • 200 - OK
  • 400 - Bad request
  • 403 - Forbidden
  • 500 - Internal server error
  • 502 - Bad gateway
  • 503 - Service unavailable

For L4 proxy mode the status code provided is primarily for logging and statistical purpose, and is not visible to the client directly.

The second, optional, body argument will set the response body. If it is a string, no special processing will be done, and the body will be 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 which case, it will be JSON-encoded and the application/json Content-Type header will be set. On gRPC we cannot send the body with this function at the moment at least, so what it does instead is that it sends “body” in grpc-message header instead. If the body is a table it looks for a field message in it, and uses that as a grpc-message header. Though, if you have specified Content-Type header starting with application/grpc, the body will be sent.

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

When status is 500, 502 or 503, then body will be logged in the Kong error log file. Otherwise body will be sent back to the L4 client.

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 will automatically set 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 (tablestring, optional): The body to be used
  • headers (table, optional): The headers to be used

Returns

  • Nothing; throws an error on invalid input.

Usage

  1. return kong.response.exit(403, "Access Forbidden", {
  2. ["Content-Type"] = "text/plain",
  3. ["WWW-Authenticate"] = "Basic"
  4. })
  5. ---
  6. return kong.response.exit(403, [[{"message":"Access Forbidden"}]], {
  7. ["Content-Type"] = "application/json",
  8. ["WWW-Authenticate"] = "Basic"
  9. })
  10. ---
  11. return kong.response.exit(403, { message = "Access Forbidden" }, {
  12. ["WWW-Authenticate"] = "Basic"
  13. })
  14. ---
  15. -- In L4 proxy mode
  16. return kong.response.exit(200, "Success")

Back to top

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:

  1. return kong.response.error(500, "Error", {["Content-Type"] = "text/html"})

The first argument status will set the status code of the response that will be seen by the client. The status code must be of an error, i.e.

399.

The second, optional, message argument will set the message describing the error, which will be written in the body.

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 method will send the response formatted in JSON, XML, HTML or plain text. The actual format is chosen using one of the following options:

  • Manually specifying in headers argument using the Content-Type header.
  • Conform to the Accept header from the request.
  • If none of the above is found, fallback to JSON format. 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

  1. return kong.response.error(403, "Access Forbidden", {
  2. ["Content-Type"] = "text/plain",
  3. ["WWW-Authenticate"] = "Basic"
  4. })
  5. ---
  6. return kong.response.error(403, "Access Forbidden")
  7. ---
  8. return kong.response.error(403)

Back to top