Best Way to Assign a User to a Phoenix Socket?

When I try to use the following function to assign a user to a socket, I see protocol String.Chars not implemented error in my console at line #4. If I convert the returned struct to a string using “inspect,” the error goes away but I can’t reference individual keys, like “email”, on the client side. Not sure what I’m doing wrong as I’ve seen the appended snippet in a few tutorials.

How do I assign a User to a Phoenix.socket so that I can reference keys like email and name on the client side?

def connect(%{"token" => token}, socket) do
  case Phoenix.Token.verify(socket, "user", token, max_age: 1209600) do
    {:ok, user_id} ->
      socket = assign(socket, :user, Repo.get!(User, user_id))
      {:ok, socket}
    {:error, _} -> #...

Found my mistake. The error was really coming from room_channel.ex. I was assigning the entire User struct in Presence.track(socket, socket.assigns…)

I figured it out by watching Chris’s Presence sneak peek a few more times. Thanks for reading.

1 Like