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¶
-
Add mankai-sockets to your
Gemfile. The:cligroup makes thehanami socketscommands available: -
Install the bundle:
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:
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 = :memorykeeps broadcasts inside this process, which is fine for development.allow_anonymous = trueaccepts clients without checking who they are. Replace it with an authenticator before production; see Authenticate connections.allowed_origins = :same_originaccepts connections only from the app's own pages.channelslists 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 aschannels.chatforapp/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¶
-
Add a base class for your channels, in the same way that
app/action.rbis 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: -
Create
app/channels/chat.rb. Hanami registers it aschannels.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¶
-
Add a route for the chat page, next to the mount:
-
Add the action:
-
Add the view:
-
Add the template:
-
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.
-
The client is in
app/assets/js, next toapp.js, the entry point that your layout loads withjavascript_tag "app".app.jsruns on every page, so start the chat only on the chat page: -
Make sure that
bin/devruns the assets watcher, so that the bundle is rebuilt. -
Create
app/assets/js/chat.jswith the code in Write the chat code.
-
The client is in
public/js, which Hanami doesn't serve on its own. Serve that directory withRack::Static: -
Load the page script at the end of the template:
-
Create the page script:
-
Create
public/js/chat.jswith the code in Write the chat code. -
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¶
- Open http://localhost:2300/chat in two browser tabs. Each tab shows Joined room 1.
- In one tab, type a message and click Send. The message appears in both tabs, because
receivebroadcasts it to thechat:1stream.
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 Protocolsresponse 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_originsdoesn'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.
-
Add mankai-sockets-sql to your
Gemfile: -
Install the bundle, generate the migration, and run it:
-
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 -
Restart
bin/dev, and open http://localhost:2300/chat. -
In another terminal, start a console:
-
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_messagestable, 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_anonymousis for this tutorial only. - Set
allowed_originsto 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¶
- How WebSockets work: the connection and backend model.
- Build channels and broadcast: operations, streams, and audiences.
- Authenticate connections: sessions and short-lived tokens.
- Use the browser client: actions, reconnection, and closing.
- Run and test WebSockets: limits, separate processes, and specs.
- mankai-sockets reference: every setting and API.