I’m trying to send analytics events between LiveViews loads. Is there a way to hook into the router?
Yup, group your LiveView routes into live session(s) via Phoenix.LiveView.Router.live_session/3 and then use its :on_mount
option to attach one or more hooks to the mount lifecycle of each LiveView in the session.
Here’s an example from the Phoenix.LiveView.on_mount/1 docs:
# lib/my_app_web/live/init_assigns.ex
defmodule MyAppWeb.InitAssigns do
@moduledoc """
Ensures common `assigns` are applied to all LiveViews attaching this hook.
"""
import Phoenix.LiveView
import Phoenix.Component
def on_mount(:default, _params, _session, socket) do
{:cont, assign(socket, :page_title, "DemoWeb")}
end
...
end
# lib/my_app_web/router.ex
defmodule MyAppWeb.Router do
use MyAppWeb, :router
# pipelines, plugs, etc.
live_session :default, on_mount: MyAppWeb.InitAssigns do
scope "/", MyAppWeb do
pipe_through :browser
live "/", PageLive, :index
end
end
...
end
Oh thought on_mount was fired once per “live_session”. I’ll have to dig into that.
Yup, one of featured use cases for on_mount
is handling auth across LiveView redirects which don’t get pipe_through
ed the usual auth plugs that typically gets fired once before the stateful connection is established.
Once again, it is worth remembering that LiveViews require their own security checks, so we use
pipe_through
above to protect the regular routes (get, post, etc.) and the LiveViews should run their own checks usingon_mount
hooks.
…
Finally, you can even combinelive_session
withon_mount
. Instead of declaringon_mount
on every LiveView, you can declare it at the router level and it will enforce it on all LiveViews under it:
source: Security considerations of the LiveView model: live_session and live_redirect