Ktor: How to handle single page applications routing?

Created on 21 Nov 2018  路  3Comments  路  Source: ktorio/ktor

If I just serve statically resources when i make a call like mywebsite.com/hello/world an error 404 is risen because of course the resource does not exist. How can I make a redirect to /index.html but without changing the URL shown in the browser, otherwise the SPA router does not know how to show the proper page.

It would be awesome to have a Feature called like SinglePageApplication which automatically exposes resources and handles the 404s redirects to a default /index.html. Then with the configuration lambda you could configure the default html path of eventually choose between resources() of files() extensions.

question

Most helpful comment

Well I managed to handle it! The repo is ready 馃槃 Hope it's compliant with the codestyle of Ktor!

All 3 comments

Have you read https://ktor.io/servers/features/static-content.html ?

default("index.html") should do what you need

It is something different. default() returns something if the root of the folder is requested. What a SPA needs instead is to redirect every 404 to a specific index.html keeping the URL into the browser intact.

For example, say you have index.html, index.js and index.css in the root of your resources and you have 3 routes in your, say, Angular SPA:

  • /home
  • /login/yolo
  • /about/pikachu

Now if I write in my browser mywebsite.com/home I want the root index.html to be served, same should do for /login/yolo and /about/pikachu. But if the browser makes a get request for index.js or index.css they should be served.

Of course I don't want to write every route 2 times once on the Angular router, once in Ktor routing, serving always index.html and putting that page to default for every possible root. It definitely is error prone.

Hope I've been clear enough.

Btw digging more inside Ktor documentation (which btw is amazing, good job there as well, as always JetBrains 馃槈) I realized that writing a custom feature should do the trick so I'm doing it (help wanted)!. I'll publish it on Jitpack when ready. Just few questions if someone can help:

  • What is the bare minimum dependencies to make it work keeping the feature engine-agnostic?
  • How do I intercept a ApplicationCallPipeline after all the set up routes have failed to intercept it? pipeline.intercept(ApplicationCallPipeline.Fallback) is not working 馃槩

Well I managed to handle it! The repo is ready 馃槃 Hope it's compliant with the codestyle of Ktor!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

KennethanCeyer picture KennethanCeyer  路  4Comments

scorsi picture scorsi  路  4Comments

PatrickLemke picture PatrickLemke  路  3Comments

seanf picture seanf  路  3Comments

evgfilim1 picture evgfilim1  路  4Comments