Caching headers
The CachingHeaders plugin (previously known as 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 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 ...
... or a specified module.
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 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:
The CachingOptions object accepts Cache-Control and Expires header values as parameters:
The
cacheControlparameter accepts a CacheControl value. You can use CacheControl.MaxAge to 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.
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:
You can learn more about routing in Ktor from Routing.