Default Headers

The DefaultHeaders feature adds the standard Server and Date headers into each response. Moreover, you can provide additional default headers and override the Server header.

Install DefaultHeaders

To install the DefaultHeaders feature, pass it to the install function in the application initialization code. This can be the main function …

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.main() {
  4. install(DefaultHeaders)
  5. // ...
  6. }

… or a specified module:

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.module() {
  4. install(DefaultHeaders)
  5. // ...
  6. }

The DefaultHeaders feature adds the Server and Date headers into each response. If necessary, you can override the Server, as described in Override Headers.

Add Additional Headers

To customize a list of default headers, pass a desired header to install by using the header(name, value) function. The name parameter accepts an HttpHeaders value, for example:

  1. install(DefaultHeaders) {
  2. header(HttpHeaders.ETag, "7c876b7e")
  3. }

To add a custom header, pass its name as a string value:

  1. install(DefaultHeaders) {
  2. header("Custom-Header", "Some value")
  3. }

Override Headers

To override the Server header, use a corresponding HttpHeaders value:

  1. install(DefaultHeaders) {
  2. header(HttpHeaders.Server, "Custom")
  3. }

Note that the Date header is cached due to performance reasons and cannot be overridden by using DefaultHeaders. If you need to override it, do not install the DefaultHeaders feature and use route interception instead.

Customize Headers for Specific Routes

If you need to add headers for a specific route only, you can append desired headers into a response. The code snippet below shows how to do this for the /order request:

  1. get("/order") {
  2. call.response.headers.append(HttpHeaders.ETag, "7c876b7e")
  3. }

You can learn more about routing in Ktor from Routing in Ktor.