I am busy creating an elm SPA. When a link is clicked, the app parses it as expected, however when someone types “http://localhost:8000/blog” it will reload the page looking to serve a blog page, but there is no such page because the whole SPA is on the single index.html page. How can I intercept that browser url change and tell my SPA to parse it as a normal blog route and act accordingly, as it does with url clicks?
Hi David,
this only depends on the way you serve your index.html file. It has nothing to do with our elm application.
You need to make sure that however you are hosting / starting the application, all the traffic is serving your index.html
http://localhost:8000/ -> index.html
http://localhost:8000/blog -> index.html
The elm app handles the routing internally after the runtime takes over.
Thanks for the quick response. I understand now. Could you please elaborate on how to do that?
What are you using to start your elm app at the moment? You could use something like create-elm-app which has the setup you want built in https://github.com/halfzebra/create-elm-app.
There are many different options out there to do that.
I’m using http-server from npm.
Another way is to use elm-live
with the -u | --pushstate
option instead of your http-server
. It will serve index.html
instead of 404. As a bonus, you will get live reloading.
For example:
$ elm-live src/Main.elm -u
or if you prefer to build a javascript file:
$ elm-live src/Main.elm -u -- --output=elm.js
Thank you very much!
seems like http-server does not have an option for SPA.
you could also use https://github.com/zeit/serve.
serve -s
you’ve correctly identified that the problem is “there is no such page”. so, you just need to configure your web server to serve your spa index.html as the 404 Not Found
page
The http-server’s github page does mention GitHub - http-party/http-server: a simple zero-configuration command-line http server
404.html
will be served if a file is not found. This can be used for Single-Page App (SPA) hosting to serve the entry page.
So, the trick is: instead of serving your SPA with index.html
, just serve it with 404.html
If you ever need to use a different web server (e.g. nginx), the same strategy will work too: configure your SPA as the 404 Not Found
page
This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.