Conditional headers
The ConditionalHeaders plugin (previously known as feature) avoids sending the body of content if it has not changed since the last request. This is achieved by using the following headers:
The
Last-Modified
response header contains a resource modification time. For example, if the client request contains theIf-Modified-Since
value, Ktor will send a full response only if a resource has been modified after the given date. Note that for static files Ktor appends theLast-Modified
header automatically after installingConditionalHeaders
.The
Etag
response header is an identifier for a specific resource version. For instance, if the client request contains theIf-None-Match
value, Ktor won't send a full response in case this value matches theEtag
. You can specify theEtag
value when configuringConditionalHeaders
.
Install ConditionalHeaders
To install the ConditionalHeaders
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.
Configure headers
To configure ConditionalHeaders
, you need to call the version function inside the install
block. This function provides access to a list of resource versions for a given OutgoingContent. You can specify the required versions by using the EntityTagVersion and LastModifiedVersion class objects.
The code snippet below shows how to add a Etag
and Last-Modified
headers for CSS:
You can find the full example here: conditional-headers.