Fine tuning routing for a better UX

jrowah

jrowah

yesterday

Phoenix gives you a very cool and easier way to fine tune your routing and be able to effectively handle cases where, say a user has a typo in the url whenever they, for some reason, might have to manually type your app’s url on the browser, or when a redirect to your app has a typo, or some part of it is invalid, or broken links etc, but the domain is valid.

Here is how.

defmodule MyAppWeb.Router do
  use MyAppWeb, :router
# All your possible routes and pipelines get declared above and so this becomes
# the "catch all" that handles non-existent routes or those with typos.
scope "/*rest", MyAppWeb do
    pipe_through(:browser)
    match(:*, "/", PageController, :not_found)
  end
end

Then in the page controller you implement a function that renders a 404 component or file, and inside here you put valid links as you render the 404. Typically you would do:

defmodule MyAppWeb.PageController do
  use MyAppWeb, :controller

  def not_found(conn, _) do
    conn
    |> assign(:page_title, "MyApp - Not Found")
    |> put_root_layout(html: {MyAppWeb.Layouts, :root})
    |> render("not_found.html") #Call this file whatever name
  end
end

And then you can have your 404 design page in the page_html folder that you rendered in the last line above.

I find this a better user experience. Read more about the match() macro here.