+++ template = "article.html" title = "Ktor: Altering served content" date = 2022-09-06T14:00:00+10:00 description = "Learn how to create Ktor plugins that transform response content, with a practical example of injecting scripts into HTML files." [taxonomies] tags = ["kotlin", "ktor", "web"] +++ When serving files with [Ktor](https://ktor.io), there might be times when you need to alter those files. For example, you might want to inject a script in every served HTML file. For this purpose, we can leverage [plugins](https://ktor.io/docs/plugins.html). Plugins can hook at different stages of the request/response pipeline: {% mermaid(caption="Ktor request/response pipeline") %} graph LR Request --> Plugin1[Plugin] Plugin1 --> Handler Handler --> Plugin2[Plugin] Plugin2 --> Response {% end %} Let's write a plugin that transforms a specific type of files - going with the previous example of injecting a script to every served HTML file. Our plugin needs to: - Take a script URL as an input. If not provided, it won't do anything. - Add that script as a `