Ktor 3.0.0-beta-1 Help

Default headers

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

Add dependencies

To use DefaultHeaders, you need to include the ktor-server-default-headers artifact in the build script:

implementation("io.ktor:ktor-server-default-headers:$ktor_version")
implementation "io.ktor:ktor-server-default-headers:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-default-headers-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install DefaultHeaders

To install the DefaultHeaders plugin to the application, pass it to the install function in the specified module. The code snippets below show how to install DefaultHeaders...

  • ... inside the embeddedServer function call.

  • ... inside the explicitly defined module, which is an extension function of the Application class.

import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.application.* import io.ktor.server.plugins.defaultheaders.* fun main() { embeddedServer(Netty, port = 8080) { install(DefaultHeaders) // ... }.start(wait = true) }
import io.ktor.server.application.* import io.ktor.server.plugins.defaultheaders.* // ... fun Application.module() { install(DefaultHeaders) // ... }

The DefaultHeaders plugin can also be installed to specific routes. This might be useful if you need different DefaultHeaders configurations for different application resources.

Configure DefaultHeaders

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:

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

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

install(DefaultHeaders) { header("Custom-Header", "Some value") }

Override headers

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

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

Note that the Date header is cached due to performance reasons and cannot be overridden by using DefaultHeaders.

Last modified: 30 April 2024