Ktor 1.6.3 Help

Default headers

The DefaultHeaders plugin (previously known as 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 plugin, pass it to the install function in the application initialization code. Depending on the way used to create a server, this can be the embeddedServer function call ...

import io.ktor.features.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(DefaultHeaders) // ... }.start(wait = true) }

... or a specified module.

import io.ktor.features.* // ... fun Application.module() { install(DefaultHeaders) // ... }

The DefaultHeaders plugin 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:

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. If you need to override it, do not install the DefaultHeaders plugin 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:

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

You can learn more about routing in Ktor from Routing.

Last modified: 27 May 2021