How to track visitors on all liveview pages?

Hi,

By following tutorials, I have already managed to set up “Presence” with liveview and track visitors who go to the home page.

defmodule NovySite.HomeLive.Index do
  @moduledoc false

  use NovySite, :live_view

  alias NovyAdmin.Presence

  @presence_guest "users:guest"

  @impl true
  def mount(_params, session, socket) do
    if connected?(socket) do
      {:ok, _} = Presence.track(self(), @presence_guest, UUID.uuid4(), %{})
    end

    socket = assign_defaults(session, socket)

    {:ok, socket}
  end
end

But when they change page (ex: contact page), presence no longer tracks them. On my contact page I didn’t put the code to track visitors so that’s normal I think.

defmodule NovySite.ContactLive.Index do
  @moduledoc false

  use NovySite, :live_view

  @impl true
  def mount(_params, session, socket) do
    socket = assign_defaults(session, socket)
    {:ok, socket}
  end
end

But I would like to track them on ALL the pages of my site. I have the impression that adding the piece of code of track on all page is not the right solution because at each change of page the track stops then restarts.

Is there a place where we can put “global” code for liveview? Or maybe I don’t take it the right way at all.

Sorry for my bad English :3

Thanks!

I just have a unique user ID passed in to the socket connection and register it onto the socket, that then gets inherited by all channels on that socket, and the socket just registers a presence.

2 Likes

I understand the idea but I can’t see where and how I should make changes, in endpoint.ex? Would you have a code snippet for me please?

I haven’t used liveview yet, I use drab, but it wouldn’t be in endpoint, it would be in your socket module, like the normal way you handle auth there.

Oh ok, the problem is that I do not have access to the socket module of liveview:

socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]

Maybe I can replace “Phoenix.LiveView.Socket” with my own socket but I’m afraid my project won’t work anymore :sweat_smile:. Also, I don’t see anything in the documentation that deals with this kind of case :disappointed_relieved:.