https://kotlinlang.org logo
#ktor
Title
# ktor
r

Robert Jaros

03/15/2024, 12:02 PM
Hello, I'm trying to develop SPA SSR with Ktor by using existing features of
singePageApplication()
, but with a server generated
index.html
. I've created this configuration:
Copy code
routing {
        get("/index.html") {
            call.respondText(
                "<html><head><title>Custom index.html</title></head><body></body></html>",
                ContentType.Text.Html
            )
        }
        singlePageApplication {
            defaultPage = "index.html"
            filesPath = "/assets"
            useResources = true
        }
    }
but unfortunately it doesn't work (not existing urls are redirected to
/assets/index.html
file instead of my
/index.html
endpoint). Can I somehow do this with a simple configuration or do I have to implement the whole thing from scratch?
a

Aleksei Tirman [JB]

03/15/2024, 1:35 PM
I don't see an easy way to do it. Can you describe the logic of the
/index.html
route's handler in your application?
r

Robert Jaros

03/15/2024, 2:18 PM
I would need access to the requested URL. Then call an external API and return some html code.
a

Aleksei Tirman [JB]

03/15/2024, 2:20 PM
I suggest filing a feature request to support your use case.
r

Robert Jaros

03/15/2024, 3:09 PM
After some experiments and digging in Ktor sources I've come up with this:
Copy code
routing {
    get("/index.html") {
        call.respondText("Hello, world!", ContentType.Text.Plain)
    }
    singlePageApplication {
        defaultPage = "NOT_EXISTING_RESOURCE"
        filesPath = "/assets"
        useResources = true
    }
    route("/") {
        route("{static-content-path-parameter...}") { // !!! Important name copied from Ktor sources
            get {
                call.respondText("Hello, world!", ContentType.Text.Plain)
            }
        }
    }
}
It seems to do exactly what I want.
👍 1
4 Views