DEV Community

Cover image for Use Verified Routes in Phoenix 1.7+
Mykolas Mankevicius
Mykolas Mankevicius

Posted on • Edited on

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"
Enter fullscreen mode Exit fullscreen mode

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}"


Enter fullscreen mode Exit fullscreen mode

Using Phoenix.Param protocol

~p"/posts/#{@post}"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Hope this helps, have a nice day!

Top comments (0)