Caching headers
The CachingHeaders plugin adds the capability to configure the Cache-Control and Expires headers used for HTTP caching. You can configure caching in the following ways:
Configure different caching strategies for specific content types, such as images, CSS and JavaScript files, and so on.
Specify caching options on different levels: globally on the application level, on a route level, or for specific calls.
Add dependencies
To use CachingHeaders, you need to include the ktor-server-caching-headers artifact in the build script:
Install CachingHeaders
To install the CachingHeaders plugin to the application, pass it to the install function in the specified module. The code snippets below show how to install CachingHeaders...
... inside the
embeddedServerfunction call.... inside the explicitly defined
module, which is an extension function of theApplicationclass.
The CachingHeaders plugin can also be installed to specific routes. This might be useful if you need different CachingHeaders configurations for different application resources.
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 a plain text and HTML:
The CachingOptions object accepts Cache-Control and Expires header values as parameters:
The
cacheControlparameter accepts a CacheControl value. You can useCacheControl.MaxAgeto specify themax-ageparameter and related settings, such as visibility, revalidation options, and so on. You can disable caching by usingCacheControl.NoCache/CacheControl.NoStore.The
expiresparameter allows you to specify theExpiresheader as aGMTDateorZonedDateTimevalue.
Route level
You can install plugins not only globally but also to specific routes. For instance, the example below shows how to add the specified caching header for the /index route:
Call level
If you need more fine-grained caching setup, you can configure caching options on a call level using the ApplicationCall.caching property. The example below shows how to configure caching options depending on whether a user is logged in or not: