Skip to content
Edit this page View source of this page

Add your first WebSocket channel

In this tutorial, you add a WebSocket endpoint and a chat channel to a Hanami app, build a page that connects from the browser, and send a message that every open tab receives. You don't need experience with Action Cable or other WebSocket libraries. Allow about 20 minutes.

This tutorial keeps everything in one process. It uses Mankai's memory backend, which delivers broadcasts only to connections in the same process. That's all a single development server needs. To share broadcasts between processes, see Optional: Share broadcasts between processes.

Before you begin

You need the following:

  • A Hanami 3 app that starts with bin/dev.
  • A web server that supports Rack full hijack, which lets an app take over the client's TCP socket. Puma, Hanami's default server, supports it.
  • Ruby 3.3 or later and Rack 3.

Run all commands from the app's root directory. The examples use Bookshelf as the app module; replace it with your app's module.

Step 1: Add the gem

  1. Add mankai-sockets to your Gemfile. The :cli group makes the hanami sockets commands available:

    # Gemfile
    gem "mankai-sockets", group: [:default, :cli]
    
  2. Install the bundle:

    bundle install
    

Step 2: Install the browser client

Run the installer with the memory backend. The default, --backend=sql, also writes a database migration, which this tutorial doesn't need:

bundle exec hanami sockets install --backend=memory

The installer copies the browser client into your app and prints the snippets that you add in the next steps. Where it copies the client depends on whether your app uses hanami-assets:

  • With hanami-assets, the default for hanami new: app/assets/js/mankai-sockets.js.
  • Without hanami-assets: public/js/mankai-sockets.js.

Step 3: Register the provider

Create config/providers/sockets.rb:

# config/providers/sockets.rb
require "mankai/sockets"

Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
  configure do |config|
    config.backend = :memory
    config.allow_anonymous = true
    config.allowed_origins = :same_origin
    config.channels = {"chat" => "channels.chat"}
  end
end

Each setting does the following:

  • backend = :memory keeps broadcasts inside this process, which is fine for development.
  • allow_anonymous = true accepts clients without checking who they are. Replace it with an authenticator before production; see Authenticate connections.
  • allowed_origins = :same_origin accepts connections only from the app's own pages.
  • channels lists every channel that the browser can use. It maps the name that the browser sends, "chat", to the channel's container key: the name that Hanami registers the class under, such as channels.chat for app/channels/chat.rb.

The provider registers several components. This tutorial uses two: sockets.endpoint, the Rack app that you mount in step 4, and sockets.broadcaster, which sends messages in step 5.

The app doesn't boot until you create channels.chat in step 5, because the provider checks every channel key at boot.

Step 4: Mount the endpoint

Add the endpoint to config/routes.rb:

# config/routes.rb
module Bookshelf
  class Routes < Hanami::Routes
    mount Hanami.app["sockets.endpoint"], at: "/sockets"
  end
end

The endpoint is a Rack app inside your app's middleware stack, so sessions, logging, and security middleware also run for WebSocket requests.

Step 5: Write a channel

  1. Add a base class for your channels, in the same way that app/action.rb is the base class for actions. The file requires the gem, so your channels load in specs and in the console as well as in the server:

    # app/channel.rb
    # auto_register: false
    require "mankai/sockets"
    
    module Bookshelf
      class Channel < Mankai::Sockets::Channel
      end
    end
    
  2. Create app/channels/chat.rb. Hanami registers it as channels.chat, the key that you listed in step 3:

    # app/channels/chat.rb
    module Bookshelf
      module Channels
        class Chat < Bookshelf::Channel
          include Deps["sockets.broadcaster"]
    
          params do
            required(:room).filled(:integer)
          end
    
          def subscribe(subscription)
            room = subscription.params[:room]
            Success(streams: [Mankai::Sockets::Stream.of("chat", room)], data: {room: room})
          end
    
          def receive(subscription, message)
            case message.name
            when "speak"
              broadcaster.call(
                Mankai::Sockets::Stream.of("chat", subscription.params[:room]),
                body: message.data[:body].to_s
              )
            else
              Failure(:unknown_action)
            end
          end
        end
      end
    end
    

A stream is a named destination for broadcasts, such as chat:1. The browser never picks streams; the channel picks them when it accepts a subscription.

subscribe runs when the browser subscribes. It returns the streams that this subscription listens to, plus optional data for the browser. To reject the subscription instead, return Failure(reason).

receive handles one action from the browser. Here it broadcasts the message to the room's stream and returns the broadcaster's result. If receive returns Success, the browser's perform promise resolves. If it returns Failure, the promise rejects.

The channel is a component, so it gets the broadcaster through Deps. In a real app, keep database writes and other business logic in an operation and inject that instead; see Build channels and broadcast.

Step 6: Add a page

  1. Add a route for the chat page, next to the mount:

    # config/routes.rb
    get "/chat", to: "chat.show"
    mount Hanami.app["sockets.endpoint"], at: "/sockets"
    
  2. Add the action:

    # app/actions/chat/show.rb
    module Bookshelf
      module Actions
        module Chat
          class Show < Bookshelf::Action
          end
        end
      end
    end
    
  3. Add the view:

    # app/views/chat/show.rb
    module Bookshelf
      module Views
        module Chat
          class Show < Bookshelf::View
          end
        end
      end
    end
    
  4. Add the template:

    <%# app/templates/chat/show.html.erb %>
    <h1>Chat</h1>
    
    <div id="chat" data-room="1">
      <ul id="messages"></ul>
      <form id="chat-form">
        <input id="chat-input" type="text" autocomplete="off" disabled>
        <button type="submit" disabled>Send</button>
      </form>
      <p id="status">Connecting…</p>
    </div>
    
  5. To confirm that the page renders, open http://localhost:2300/chat. The page shows Connecting…. Nothing connects yet.

Step 7: Connect from the browser

Hanami's default Content Security Policy blocks inline <script> tags, so the page's code goes in a JavaScript file. Follow the tab that matches your app, and then write the chat code.

  1. The client is in app/assets/js, next to app.js, the entry point that your layout loads with javascript_tag "app". app.js runs on every page, so start the chat only on the chat page:

    // app/assets/js/app.js
    import {startChat} from "./chat.js";
    
    const chat = document.getElementById("chat");
    if (chat) startChat(chat);
    
  2. Make sure that bin/dev runs the assets watcher, so that the bundle is rebuilt.

  3. Create app/assets/js/chat.js with the code in Write the chat code.

  1. The client is in public/js, which Hanami doesn't serve on its own. Serve that directory with Rack::Static:

    # config/app.rb
    require "hanami"
    require "rack/static"
    
    module Bookshelf
      class App < Hanami::App
        config.middleware.use Rack::Static, urls: ["/js"], root: File.expand_path("../public", __dir__)
      end
    end
    
  2. Load the page script at the end of the template:

    <%# app/templates/chat/show.html.erb %>
    <script type="module" src="/js/app.js"></script>
    
  3. Create the page script:

    // public/js/app.js
    import {startChat} from "./chat.js";
    
    const chat = document.getElementById("chat");
    if (chat) startChat(chat);
    
  4. Create public/js/chat.js with the code in Write the chat code.

  5. After you change config/app.rb, restart the server.

Write the chat code

The chat code is the same with or without hanami-assets. Put it in chat.js, next to mankai-sockets.js:

// chat.js, next to mankai-sockets.js
import {createConsumer} from "./mankai-sockets.js";

export function startChat(root) {
  const room = Number(root.dataset.room);
  const messages = root.querySelector("#messages");
  const status = root.querySelector("#status");
  const form = root.querySelector("#chat-form");
  const input = root.querySelector("#chat-input");
  const button = form.querySelector("button");

  const setEnabled = (enabled) => {
    input.disabled = !enabled;
    button.disabled = !enabled;
  };

  const consumer = createConsumer("/sockets", {logger: console});

  const subscription = consumer.subscriptions.create(
    {channel: "chat", params: {room}},
    {
      connected(data) {
        status.textContent = `Joined room ${data.room}`;
        setEnabled(true);
      },
      received(data) {
        const item = document.createElement("li");
        item.textContent = data.body;
        messages.appendChild(item);
      },
      rejected(reason) {
        status.textContent = `Rejected: ${reason}`;
      },
      disconnected() {
        status.textContent = "Reconnecting…";
        setEnabled(false);
      },
    },
  );

  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    try {
      await subscription.perform("speak", {body: input.value});
      input.value = "";
    } catch (error) {
      status.textContent = `Not sent: ${error.message}`;
    }
  });

  consumer.connect();
}

The code keeps the form disabled until connected runs, because perform rejects with not connected until the server accepts the connection. No connection opens until consumer.connect(). After that, the client replies to the server's keep-alive pings and reconnects on its own, re-sending its subscriptions.

Step 8: Send a message

  1. Open http://localhost:2300/chat in two browser tabs. Each tab shows Joined room 1.
  2. In one tab, type a message and click Send. The message appears in both tabs, because receive broadcasts it to the chat:1 stream.

Verify your work

Check that the following are true:

  • The status changes to Joined room 1 after the page loads.
  • A message sent from one tab appears in every open tab.
  • The browser's network panel shows a 101 Switching Protocols response for /sockets.
  • Opening http://localhost:2300/sockets directly shows Upgrade Required, which means that the endpoint is mounted.

If the status stays at Connecting…, open the browser console and check for the following:

  • A failed import: the page requests the client from a path where it isn't served.
  • A 403 response: allowed_origins doesn't match the page's origin.
  • A close code logged right after connecting: the console logger shows why the server closed the connection. For what each code means, see Close codes.

Optional: Share broadcasts between processes

The memory backend reaches only subscriptions in the same process. A broadcast from a job worker, or from hanami console, runs in another process and never reaches the browser. To broadcast from another process, switch to the SQL backend. Your app needs a database configured with hanami-db.

  1. Add mankai-sockets-sql to your Gemfile:

    # Gemfile
    gem "mankai-sockets", group: [:default, :cli]
    gem "mankai-sockets-sql", group: [:default, :cli]
    
  2. Install the bundle, generate the migration, and run it:

    bundle install
    bundle exec hanami sockets install --backend=sql
    bundle exec hanami db migrate
    
  3. Point the provider at the SQL backend, and keep the other settings:

    # config/providers/sockets.rb
    require "mankai/sockets"
    require "mankai/sockets/sql"
    
    Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
      configure do |config|
        config.backend = Mankai::Sockets::SQL.backend(gateway: "db.gateway")
        config.allow_anonymous = true
        config.allowed_origins = :same_origin
        config.channels = {"chat" => "channels.chat"}
      end
    end
    
  4. Restart bin/dev, and open http://localhost:2300/chat.

  5. In another terminal, start a console:

    bundle exec hanami console
    
  6. In the console, broadcast to room 1:

    Hanami.app["sockets.broadcaster"].call(
      Mankai::Sockets::Stream.of("chat", 1),
      body: "Hello from the console"
    )
    

    The message appears in the open tab. The console process inserts the message into the sockets_messages table, and the web process polls that table and delivers the message.

Before you use WebSockets in production

Before you deploy, make the following changes:

  • Authenticate connections with an authenticator. allow_anonymous is for this tutorial only.
  • Set allowed_origins to the exact origins that can connect.
  • Decide whether WebSocket connections run in the web process or in a separate one. A separate process needs the SQL backend.
  • Review the limits: frame size, payload size, subscriptions, connections per identity, and heartbeat interval.

What's next