Is there any difference between these two groups of Phoenix live routes definitions?

To me, there seems to be no difference, but I would like to confirm if I’m correct. If I am, please let me know if there are any considerations I should be aware of in your opinion. Could you please take a look? Thank you.

The first group contains a Plugs pipeline inside the live_session for the admin, while the second group has the Plugs pipeline outside the live_session but scoped to it. Here are the two code examples for reference:

First group:

live_session :admin, on_mount: MyAppWeb.AdminLiveAuth do
  scope "/" do
    # Plugs pipeline inside live_session
    pipe_through [MyAppWeb.AdminPlugAuth]

    # Live routes
    live "/admin", AdminDashboardLive, :index
    live "/admin/posts", AdminPostLive, :index
  end
end

Second group:

scope "/" do
  # Plugs pipeline outside live_session but scoped to it
  pipe_through [MyAppWeb.AdminPlugAuth]
  
  live_session :admin, on_mount: MyAppWeb.AdminLiveAuth do  
    # Live routes
    live "/admin", AdminDashboardLive, :index
    live "/admin/posts", AdminPostLive, :index
  end
end
1 Like

I was also wondering this. The first way is given as an example in Phoenix.LiveView.Router — Phoenix LiveView v1.0.2, but the second way is used by the phx.gen.auth generator in phoenix 1.7.

There is no difference.

Scopes simply augment any route (or nested scope) in their body. So does live_session. In the end all that’s left is a list of Route structs.

Technically the order does not matter.

If you want to confirm you can use Routex and write a simple extension module with…

defmodule InspectExtension do
  transform(routes, _backend, _env) do
    IO.inspect(routes)
  end
end

Both variants should render the exact same list of routes.

(from mobile, untested, if you do feel free to open a PR as it’s a nice addition)

3 Likes

You’re right, both code snippets achieve the same outcome: the MyAppWeb.AdminPlugAuth pipeline will be applied to the /admin and /admin/posts live routes. The main difference is code organization. The first group keeps the plug pipeline inside the live_session, which might be more readable for associating authentication with the session. The second group places it outside but scoped to the session, offering slightly more flexibility if you later need routes within the same scope without admin authentication. The order of execution is slightly different but unlikely to have practical consequences in most scenarios. Choose the style you find more maintainable.

1 Like