Caching Headers

The CachingHeaders feature 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.

Install CachingHeaders

To install the CachingHeaders 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(CachingHeaders)
  5. // ...
  6. }

… or a specified module:

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

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

Configure Caching

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

  1. install(CachingHeaders) {
  2. options { outgoingContent ->
  3. when (outgoingContent.contentType?.withoutParameters()) {
  4. ContentType.Text.CSS -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 3600))
  5. else -> null
  6. }
  7. }
  8. }

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.

Customize Headers for Specific Routes

If you need to add caching headers for a specific route only, you can append the desired headers into a response. In this case, you don’t need to install CachingHeaders. The code snippet below shows how to disable caching for the /profile route:

  1. get("/profile") {
  2. call.response.headers.append(HttpHeaders.CacheControl, "no-cache, no-store")
  3. // ...
  4. }

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