Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Channels and PubSub

Phoenix Channels and Sockets

Build realtime features with Phoenix Channels: UserSocket, topic patterns, join/3, handle_in/3, push and broadcast, the JavaScript client and the wire format.

LiveView is the quickest way to build realtime pages, but it is not the only way. Channels are Phoenix's general realtime layer: a single WebSocket connection carries many conversations ("topics") between a client and the server, in both directions. Mobile apps, games, dashboards, third-party widgets and plain JavaScript front ends all use channels. In fact, LiveView itself is built on the same socket machinery.

This lesson explains the pieces (socket, topic, channel, message), shows real Phoenix server and client code in read-only blocks, and gives you a runnable JavaScript model of the routing and protocol. You should know how processes and messages work, because every joined channel is an Elixir process.

The big picture

flowchart LR
    C1["Browser A<br/>one WebSocket"] --> S["UserSocket<br/>connect/3, id/1"]
    C2["Browser B<br/>one WebSocket"] --> S
    S --> R1["Channel process<br/>room:lobby (A)"]
    S --> R2["Channel process<br/>room:lobby (B)"]
    S --> R3["Channel process<br/>user:42 (B)"]

One socket per client; every topic a client joins gets its own channel process.

Four terms to learn:

  • Socket: the long-lived WebSocket connection. It is created once and authenticated in connect/3.
  • Topic: a string naming a conversation, by convention "topic:subtopic", such as "room:lobby" or "user:42".
  • Channel: a module that handles join and incoming events for topics matching a pattern.
  • Message: an event name plus a payload (a map). Events go both ways: handle_in/3 for incoming ones, push/3 and broadcast/3 for outgoing.

The server side

First, the endpoint declares the socket route, and the socket module maps topic patterns to channel modules:

ELIXIR
# lib/my_app_web/endpoint.ex
socket "/socket", MyAppWeb.UserSocket,
  websocket: true,
  longpoll: false

# lib/my_app_web/channels/user_socket.ex
defmodule MyAppWeb.UserSocket do
  use Phoenix.Socket

  channel "room:*", MyAppWeb.RoomChannel

  @impl true
  def connect(%{"token" => token}, socket, _connect_info) do
    case Phoenix.Token.verify(MyAppWeb.Endpoint, "user socket", token, max_age: 86_400) do
      {:ok, user_id} -> {:ok, assign(socket, :user_id, user_id)}
      {:error, _reason} -> :error
    end
  end

  def connect(_params, _socket, _connect_info), do: :error

  @impl true
  def id(socket), do: "user_socket:#{socket.assigns.user_id}"
end

connect/3 runs once per connection. Returning :error refuses it. The id/1 callback names the connection so that you can disconnect all of a user's sockets later with MyAppWeb.Endpoint.broadcast("user_socket:42", "disconnect", %{}), for example after a password change.

Then the channel:

ELIXIR
defmodule MyAppWeb.RoomChannel do
  use MyAppWeb, :channel

  @impl true
  def join("room:lobby", _payload, socket) do
    {:ok, socket}
  end

  def join("room:" <> room_id, _payload, socket) do
    if Chat.member?(socket.assigns.user_id, room_id) do
      {:ok, assign(socket, :room_id, room_id)}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end

  @impl true
  def handle_in("new_msg", %{"body" => body}, socket) do
    broadcast!(socket, "new_msg", %{body: body, user_id: socket.assigns.user_id})
    {:reply, :ok, socket}
  end

  def handle_in("ping", _payload, socket) do
    {:reply, {:ok, %{pong: true}}, socket}
  end
end

How to read it:

  • join/3 is the authorization point for a topic. Return {:ok, socket} to allow, {:error, map} to deny. Pattern match on the topic string (as in "room:" <> room_id) to handle subtopics.
  • handle_in/3 receives an event the client sent. Return {:noreply, socket} or {:reply, :ok | {:ok, map} | {:error, map}, socket}; the reply is delivered to the matching receive("ok", ...) on the client.
  • broadcast!/3 sends an event to everyone subscribed to the topic, including the sender. broadcast_from!/3 skips the sender. push/3 sends to just this client.
  • socket.assigns holds per-connection (or per-channel) state, like conn assigns.

The JavaScript client

The phoenix npm package, already included in a Phoenix project's assets/, is the client:

JavaScript
import { Socket } from "phoenix";

const socket = new Socket("/socket", { params: { token: window.userToken } });
socket.connect();

const channel = socket.channel("room:lobby", {});

channel.on("new_msg", (payload) => {
  list.insertAdjacentHTML("beforeend", `<li>${escapeHtml(payload.body)}</li>`);
});

channel
  .join()
  .receive("ok", () => console.log("joined"))
  .receive("error", (resp) => console.log("refused", resp.reason));

form.addEventListener("submit", (e) => {
  e.preventDefault();
  channel
    .push("new_msg", { body: input.value }, 5000)
    .receive("ok", () => (input.value = ""))
    .receive("timeout", () => console.log("server too slow"));
});

The client also reconnects with exponential backoff when the network drops and automatically rejoins its channels. Always escape payload text before inserting it into HTML; the data came from other users.

A model of topics and routing

The stand-in below implements the three server ideas from this lesson in a few lines: topic patterns, join as authorization, and broadcast to subscribers. It is not the Phoenix implementation, only its behaviour.

Node.js Topic routing, join and broadcast (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The wire format

You rarely see it, but knowing the wire format demystifies debugging in DevTools. With the default V2 serializer, every message is a JSON array of five parts: [join_ref, ref, topic, event, payload]. The ref ties a reply to its request; join_ref ties messages to one join of the topic.

Node.js Encoding and decoding channel messages (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The phx_join, phx_reply, phx_leave and phx_error events are reserved, and the client sends a heartbeat on the phoenix topic every 30 seconds so that proxies do not close an idle socket.

Design advice

  • Keep payloads small and flat. Send ids and deltas, not whole records.
  • Authorize in join/3 and again in sensitive handle_in/3 clauses. Joining "room:42" must check that the user belongs to room 42; never assume the topic name is secret.
  • Validate payloads with pattern matching and changesets, exactly as you would params in a controller.
  • Prefer LiveView for server-rendered UI. Use channels when the client is not a Phoenix page, or when you want full control of the protocol.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a topic in Phoenix Channels?

    Clients join topics; the socket routes each topic pattern to a channel module.
  2. 2. Where do you authorize access to a particular room?

    join/3 decides whether the client may subscribe to that topic. Returning {:error, map} refuses it.
  3. 3. What is the difference between broadcast! and push in a channel?

    broadcast! fans out through PubSub to all subscribers; push is a direct message to the connected client.
  4. 4. What does returning :error from UserSocket.connect/3 do?

    connect/3 is the authentication point of the socket. :error rejects the connection.

Summary

  • A socket is one WebSocket per client; each joined topic gets its own channel process.
  • Authenticate in UserSocket.connect/3, authorize topics in join/3.
  • handle_in/3 receives client events; broadcast!, broadcast_from! and push send events out.
  • The phoenix.js client joins, pushes, listens with channel.on, and reconnects automatically.
  • Messages are JSON arrays: [join_ref, ref, topic, event, payload].

Next: PubSub and Broadcasting