Tracking online users using Phoenix sockets and Presence?

Everything is done automaticaly, Presence will detect disconnection as well…

This is a simple code I put in my channels

  def join("schedule", _params, socket) do
    send(self(), :after_join)
    {:ok, socket}
  end

  def handle_info(:after_join, socket) do
    user = socket.assigns.user
    {:ok, _} = Presence.track(socket, user.id, %{
      username: user.name,
      online_at: System.system_time(:second)
    })
    push(socket, "presence_state", Presence.list(socket))
    {:noreply, socket}
  end

It does imply the socket is assigned to a user, for this, i extract user from a phoenix token.

You also need a client library supporting Phoenix websocket and channels.

And this library needs to be compliant with the Phoenix version.