Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: A Chat Room with Channels and Presence

Build a chat room in Phoenix: an authenticated socket, a room channel with join checks, message validation, history on join, typing and presence, plus a JavaScript client.

Chat is the classic Phoenix showcase, and it exercises every part of the real-time stack: sockets, channels, PubSub and Presence. In this project you build a room where signed-in users send messages, see who is online and see who is typing. You can do the same with LiveView (see the live poll); here we use channels so you can also serve mobile or JavaScript clients.

Phoenix is not runnable on this site, so the Elixir and JavaScript client code is read-only. The runnable editors model the server in JavaScript so you can test the rules.

Architecture

flowchart TB
  C1["Browser A"] -->|"WebSocket + token"| S["UserSocket connect"]
  C2["Browser B"] --> S
  S --> R["RoomChannel room:lobby"]
  R --> P["Phoenix.PubSub"]
  R --> PR["Presence track"]
  R --> DB[("messages table")]
  P --> C1
  P --> C2

One socket per browser, one channel process per joined room.

1. The socket authenticates

The page embeds a signed token for the current user (see API tokens). The socket verifies it before anything else can happen:

ELIXIR
defmodule MyAppWeb.UserSocket do
  use Phoenix.Socket

  channel "room:*", MyAppWeb.RoomChannel

  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, _} -> :error
    end
  end

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

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

The id/1 callback names the socket so that MyAppWeb.Endpoint.broadcast("user_socket:7", "disconnect", %{}) can kick a user out.

2. The channel

ELIXIR
defmodule MyAppWeb.RoomChannel do
  use MyAppWeb, :channel
  alias MyApp.Chat
  alias MyAppWeb.Presence

  def join("room:" <> room_id, _params, socket) do
    if Chat.can_join?(socket.assigns.user_id, room_id) do
      send(self(), :after_join)
      {:ok, %{messages: Chat.recent_messages(room_id, 50)}, assign(socket, :room_id, room_id)}
    else
      {:error, %{reason: "not allowed"}}
    end
  end

  def handle_info(:after_join, socket) do
    user = Chat.get_user!(socket.assigns.user_id)
    {:ok, _} = Presence.track(socket, user.id, %{name: user.name})
    push(socket, "presence_state", Presence.list(socket))
    {:noreply, socket}
  end

  def handle_in("new_msg", %{"body" => body}, socket) do
    case Chat.create_message(socket.assigns.room_id, socket.assigns.user_id, body) do
      {:ok, message} ->
        broadcast!(socket, "new_msg", %{id: message.id, user_id: message.user_id, body: message.body})
        {:reply, :ok, socket}

      {:error, changeset} ->
        {:reply, {:error, %{errors: format_errors(changeset)}}, socket}
    end
  end

  def handle_in("typing", _payload, socket) do
    broadcast_from!(socket, "typing", %{user_id: socket.assigns.user_id})
    {:noreply, socket}
  end
end

Points worth noticing:

  • join/3 is the authorization point. Anyone with a socket could try to join any room, so check membership here, never in the client.
  • Presence tracking happens in :after_join, because track/3 needs the channel to be fully joined.
  • The message is validated and saved first; only then is it broadcast. A client that sends 10,000 characters gets an error reply, not a broadcast.
  • broadcast_from! skips the sender, which is right for "typing" because you do not need to see your own typing indicator.

3. The JavaScript client

JavaScript
import { Socket, Presence } from "phoenix"

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

const channel = socket.channel("room:lobby", {})
const presence = new Presence(channel)

presence.onSync(() => renderUsers(presence.list((id, { metas }) => metas[0].name)))

channel.on("new_msg", (msg) => appendMessage(msg))
channel.on("typing", ({ user_id }) => showTyping(user_id))

channel.join()
  .receive("ok", ({ messages }) => messages.forEach(appendMessage))
  .receive("error", ({ reason }) => alert(reason))

form.addEventListener("submit", (e) => {
  e.preventDefault()
  channel.push("new_msg", { body: input.value })
    .receive("error", ({ errors }) => showErrors(errors))
  input.value = ""
})

The client appends messages from new_msg events, including its own, which keeps every browser identical. The join reply carries the history so a new arrival sees recent messages immediately.

4. A runnable model of the server

This stand-in has the same pieces: a verified connect, an authorized join with history, message validation, broadcast to the other members, and a broadcast_from for typing.

Node.js Room channel with join check and validation (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 second model shows presence: it counts connections per user, so a user with two tabs appears once and leaves only when the last tab closes (this is what Presence's metas list is for).

Node.js Presence with several tabs per user (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.

5. Hardening

  • Rate limit new_msg per user (for example 5 per second) so one client cannot flood a room.
  • Escape on output. Messages are user text; render them with textContent, never innerHTML (see web security).
  • Check authorization per message if memberships can change while a user is connected.
  • Reconnect handling: the JS client reconnects with backoff and rejoins; the join reply restores history, which is why history belongs in join/3 and not in a one-time push.

Exercises

  1. Store inserted_at and show times in the client, formatted in the user's time zone.
  2. Add "room:" <> id private rooms backed by a memberships table.
  3. Move the UI to a LiveView that subscribes to the same PubSub topic.
  4. Write a channel test with Phoenix.ChannelTest (socket/3, subscribe_and_join/3, push/3, assert_broadcast/2).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you check whether a user may enter a room?

    Clients cannot be trusted. join/3 runs on the server for every join attempt.
  2. 2. Why is the message saved before it is broadcast?

    Validation and persistence come first, so everyone sees exactly what the database holds.
  3. 3. Which function sends an event to every member except the sender?

    broadcast_from! skips the sending channel process; it is ideal for typing indicators.
  4. 4. Why does Presence keep a list of metas per user?

    A user is shown as online while at least one connection remains.

Summary

  • Authenticate the socket with a signed token and authorize each room in join/3.
  • Validate and save messages, then broadcast; return errors with {:reply, {:error, ...}, socket}.
  • Track presence after join, and let the client sync with Presence.
  • Harden with rate limits, output escaping and per-message authorization.

Next: Project: A JSON Notes API