Ktor 2.0.0 Help

Caching headers

The CachingHeaders plugin adds the capability to configure the Cache-Control and Expires headers used for HTTP caching. You can introduce different caching strategies for specific content types, such as images, CSS and JavaScript files, and so on.

Add dependencies

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

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

Install CachingHeaders

To install the CachingHeaders 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.server.plugins.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(CachingHeaders) // ... }.start(wait = true) }

... or a specified module.

import io.ktor.server.plugins.* // ... fun Application.module() { install(CachingHeaders) // ... }

After installing CachingHeaders, you can configure caching settings for various content types.

Configure caching

To configure the CachingHeaders plugin, you need to define the options function to provide specified caching options for a given ApplicationCall and content type. The code snippet from the caching-headers example shows how to add the Cache-Control header with the max-age option for CSS and JSON:

install(CachingHeaders) { options { call, outgoingContent -> when (outgoingContent.contentType?.withoutParameters()) { ContentType.Text.CSS -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 3600)) ContentType.Application.Json -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 60)) else -> null } } }

The CachingOptions object accepts Cache-Control and Expires header values as parameters:

  • The cacheControl parameter accepts a CacheControl value. You can use CacheControl.MaxAge to specify the max-age parameter and related settings, such as visibility, revalidation options, and so on. You can disable caching by using CacheControl.NoCache/CacheControl.NoStore.

  • The expires parameter allows you to specify the Expires header as a GMTDate or ZonedDateTime value.

Last modified: 08 April 2022