Ktor 2.3.10 Help

Serving single-page applications

Ktor provides the ability to serve single-page applications, including React, Angular, or Vue.

Add dependencies

To serve a single-page application, you only need the ktor-server-core dependency. Any specific dependencies are not required.

Serve an application

To serve a single-page application, you need to define where you want the content to be served from: a local filesystem or the classpath. You need at least to specify a folder/resource package containing a single-page application.

Serve framework-specific applications

You can serve a build of your single-page application created using a specific framework, such as React, Angular, Vue, and so on. Suppose we have the react-app folder in a project root containing a React application. The application has the following structure and the index.html file as the main page:

react-app ├── index.html ├── ... └── static └── ...

To serve this application, call singlePageApplication inside the routing block and pass the folder name to the react function:

import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.routing.* fun Application.module() { routing { singlePageApplication { react("react-app") } } }

Ktor looks up index.html automatically. To learn how to customize a default page, see Customize serving settings.

Customize serving settings

To demonstrate how to serve a single-page application from resources, let's suppose our application is placed inside the sample-web-app resource package, which has the following structure:

sample-web-app ├── main.html ├── ktor_logo.png ├── css │ └──styles.css └── js └── script.js

To serve this application, the following configuration is used:

import io.ktor.server.application.* import io.ktor.server.http.content.* import io.ktor.server.routing.* fun Application.module() { routing { singlePageApplication { useResources = true filesPath = "sample-web-app" defaultPage = "main.html" ignoreFiles { it.endsWith(".txt") } } } }
  • useResources: Enables serving an application from a resource package.

  • filesPath: Specifies the path under which an application is located.

  • defaultPage: Specifies main.html as a default resource to serve.

  • ignoreFiles: Ignores paths that contain .txt at the end.

You can find the full example here: single-page-application.

Last modified: 02 April 2024