Routing confusion - Solved - Working Examples Included

Edit: Here are some small working hash-based routing examples:


Original post:

I’m trying to restore the “Save Gist” button to TryPurescript, and I believe incorporating routing is a prerequisite for that. The github OAuth guide recommends redirecting back to a /callback url.

But I’m having a lot of trouble figuring out what to piece together from the routing guide in order to introduce routing to an app. It’s also unclear why one would choose Routing.Hash versus Routing.PushState. A small cookbook example demonstrating routing would be really helpful.

Here’s an attempt where I observe the following:

  • Route parsing appears to be working. If I uncomment main = logRouteTests, then I see this expected output:
(Right (PostEdit 8))
(Right (Post 8))
(Right (PostBrowse "foo" "bar"))
(Right PostIndex)

Steps to reproduce:

git clone --branch routing git@github.com:milesfrain/halogen.git routing-help
cd routing-help
npm run build
npm run serve 

I assume that routing code can’t be shared and troubleshooted via TryPurescript.

The clue is in the module name for where you’re importing matches from here: Routing.Hash!

Try these out:

1 Like

Oh, as for why hash vs pushstate: it depends on how your webserver and app is configured:

If you’re using hash routing, you don’t need to do anything special, since the hash isn’t part of the path to the resource.

If you use pushstate then your server needs to serve the same page for every path under some location. If you arrive at http://localhost:1234, then navigate to http://localhost:1234/8/edit in the app, and then you reload the page, you’ll now get a 404 if the server doesn’t know to serve the same HTML file at both those locations. Also means all the paths in your app need to be absolute rather than relative, since if the HTML references style/page.css that won’t work under /8/, it’ll need to be /style/page.css, etc. Likewise for all images and other resources.

Is PushState routing applicable for SPAs?

Sure, that’s what the PushState API was invented for, since it lets you change the non-hash part of the browser’s URI without causing navigation to take place. It’s just it needs a bit more setup to work.

Thanks. Did some additional research and found these guides helpful.

I originally assumed Hash and PushState were library-specific details (e.g. doing something with hashing urls or pushing to a list of url states), rather than established web dev terms.