Parsing URLs with elm/url

I wrote a fairly extensive guide to parsing URLs in Elm: routing, handling query strings, working with hash fragments, reusing parsers and dealing with path segment prefixes.

Probably most useful to those who are new to Elm.

7 Likes

That doesn’t seem to handle the case where path prefix is e.g. /foo but you have link to /bar.

Do you mean a link to, say, example.com/elm when my app is served from example.com/elm/catalog/? That would be an external URL, so in my situation I just use a full URL like example.com/elm in those links.

Yes. So is full URL always sent to onUrlRequest handler even when within current domain?

(Link to /elm would be sent to onUrlChange and would require custom code to be handled correctly, which your example doesn’t have.)

You could do something like

case urlRequest of
    Internal url ->
        if not <| String.startsWith ("/" ++ model.urlPrefix) <| url.path then
            ( model, Nav.load <| Url.toString url )

        else
            ( model, Nav.pushUrl model.navKey <| Url.toString url )

    External url ->
        ( model, Nav.load url )

This check would fail if the prefix is empty, but the other problem is that when you’re just running the app on localhost by itself, /elm is not a valid link (there is no “parent” to link to). I’m just not sure this is a particularly useful solution, that’s why I didn’t include it.

I don’t understand - localhost is as valid host as anything else, there is no difference in running Elm under localhost or example.com

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.