Use Verified Routes in Phoenix 1.7+

An image showing how to use verified routes

Phoenix 1.7+ includes the Verified Routes, which provides compile-time checks of your router paths. This is a great way to make sure that your paths are always correct! It can help you avoid potential errors in your code.

How do I

Use the verified route?

# Use it with the new sigil `~p` e.g.
~p"/"
~p"/user/profile"
~p"/posts"

Add params to verified routes?

# route get "/posts/:post", PostController, :show

# Using string interpolation
post = %{slug: "post-about-verified-routes"}
iex> ~p"/posts/#{post.slug}"
"/posts/post-about-verified-routes"

# In liveview using assings
~p"/posts/#{@post.slug}"


Using Phoenix.Param protocol

~p"/posts/#{@post}"

Add query params to verified routes?

# route get "/posts", PostController, :index

# Hardcode the params
# Note that this doesn't url encode the params:
iex> ~p"/posts?post=1&search=verified routes"
"/posts?post=1&search=verified routes"

# String interpolation
page = 1
search = "verified routes"
iex> ~p"/posts?page=#{page}&search=#{search}"
"/posts?page=1&search=verified+routes"

# Keyword list
keyword_list = [posts: 1, search: "verified routes"]
iex> ~p"/posts?#{keyword_list}"
"/posts?posts=1&search=verified+routes"

# Map of values
map_of_values = %{"posts" => 1, "search" => "verified routes"}
iex> ~p"/posts?#{map_of_values}"
"/posts?posts=1&search=verified+routes"

Hope this helps, have a nice day!