Ktor 3.0.0 Help

Webjars

The Webjars plugin enables serving the client-side libraries provided by WebJars. It allows you to package your assets such as JavaScript and CSS libraries as part of your fat JAR.

Add dependencies

To enable Webjars, you need to include the following artifacts in the build script:

  • Add the ktor-server-webjars dependency:

    implementation("io.ktor:ktor-server-webjars:$ktor_version")
    implementation "io.ktor:ktor-server-webjars:$ktor_version"
    <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-webjars-jvm</artifactId> <version>${ktor_version}</version> </dependency>
  • Add a dependency for a required client-side library. The example below shows how to add a Bootstrap artifact:

    implementation("org.webjars:bootstrap:$bootstrap_version")
    implementation "org.webjars:bootstrap:$bootstrap_version"
    <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>${bootstrap_version}</version> </dependency>

    You can replace $bootstrap_version with the required version of the bootstrap artifact, for example, 5.2.3.

Install Webjars

To install the Webjars plugin to the application, pass it to the install function in the specified module. The code snippets below show how to install Webjars...

  • ... inside the embeddedServer function call.

  • ... inside the explicitly defined module, which is an extension function of the Application class.

import io.ktor.server.application.* import io.ktor.server.webjars.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(Webjars) // ... }.start(wait = true) }
import io.ktor.server.application.* import io.ktor.server.webjars.* // ... fun Application.module() { install(Webjars) // ... }

Configure Webjars

By default, Webjars serves WebJars assets on the /webjars path. The example below shows how to change this and serve any WebJars assets on the /assets path:

import io.ktor.server.application.* import io.ktor.server.webjars.* fun Application.module() { install(Webjars) { path = "assets" } }

For instance, if you've installed the org.webjars:bootstrap dependency, you can add bootstrap.css as follows:

<head> <link rel="stylesheet" href="/assets/bootstrap/bootstrap.css"> </head>

Note that Webjars allows you to change the versions of the dependencies without changing the path used to load them.

Last modified: 26 October 2022