Search code examples
elixirphoenix-frameworkphoenix-channels

Elixir/Phoenix pass payload on joining channel


Channels have the authorized? function, and I would like to pass the generated local token when joining the channel so that I can verify user's role, like this:

const data = { token: localStorage.getItem('phoenixAuthToken') };
channel.join(data).receive('ok', (response) => {
            ...
            });
        });

However, in my channel setup, I don't seem to receive anything from client on join:

def join("settings", payload, socket) do
  IO.inspect(payload)
  if authorized?(payload) do
    {:ok, socket}
  else
    {:error, %{reason: "unauthorized"}}
  end
end

IO.inspect(payload) is just %{}. What I'm doing wrong here? Is it even possible to receive the message when joining the channel?


Solution

  • The payload that join/3 receives is the one set in the second argument of .channel() in the JS client side, not the argument passed to .join(). So, on the client side, you should be doing something like:

    const data = { token: localStorage.getItem('phoenixAuthToken') };
    const channel = socket.channel("foo", data);
    channel.join().receive(...);