Use a WebSocket transport
The examples use Ewe to serve HTTP and WebSockets. If your application uses Mist, use the Mist setup. Both transports use the same beryl runtime, configuration, authentication, origin checks, connection limits, and wire codecs.
Add WebSocket upgrades
Section titled “Add WebSocket upgrades”Use ewe_transport.handler to combine WebSocket upgrades and regular HTTP
routing in one Ewe listener:
import berylimport beryl/transport/serverimport beryl_ewe as ewe_transportimport eweimport gleam/http/request.{type Request}import gleam/http/response.{type Response}
pub fn start_ewe(sockets: beryl.Sockets) -> Nil { let assert Ok(_) = ewe_transport.handler( sockets, server.default_config("/socket/websocket"), fn( http_request: Request(ewe.Connection), ) -> Response(ewe.Body) { case request.path_segments(http_request) { [] -> response.new(200) |> response.set_body(ewe.Text("Hello!")) _ -> response.new(404) |> response.set_body(ewe.Empty) } }, ) |> ewe.new |> ewe.listening(on: 8000) |> ewe.start
Nil}handler sends matching WebSocket requests through the beryl admission
pipeline and sends every other request to the fallback function. Use
ewe_transport.upgrade instead when an existing Ewe handler already controls
the fallback.
If you already serve HTTP with Mist, pass your HTTP handler to beryl_mist.handler.
Keep your beryl configuration and socket path:
import berylimport beryl/transport/serverimport beryl_mistimport gleam/bytes_treeimport gleam/http/requestimport gleam/http/responseimport mist
pub fn start_mist(sockets: beryl.Sockets) -> Nil { let assert Ok(_) = beryl_mist.handler( sockets, server.default_config("/socket/websocket"), fn(req) { case request.path_segments(req) { [] -> response.new(200) |> response.set_body(mist.Bytes(bytes_tree.from_string("Hello!"))) _ -> response.new(404) |> response.set_body(mist.Bytes(bytes_tree.new())) } }, ) |> mist.new |> mist.port(8000) |> mist.start Nil}Both transports work with both beryl APIs. A handle from
channel.child_spec is the same beryl.Sockets type as one from
beryl.child_spec, so the setup is identical for both.
Authenticate before the upgrade
Section titled “Authenticate before the upgrade”Use with_on_connect to authenticate a connection before the upgrade. It is
similar to Phoenix UserSocket.connect/3. The hook runs once for each socket
before any channel join. It can reject the connection.
Pass the resulting configuration to ewe_transport.handler. With Mist,
use Request(mist.Connection) in the callback and pass the configuration to
beryl_mist.handler. Both adapters use the same configuration builders.
let websocket_config = server.default_config("/socket/websocket") |> server.with_on_connect(fn(http_request: Request(ewe.Connection)) { // Check auth token, session, etc. case validate_token(http_request) { Ok(_user) -> Ok([]) // Allow; no connect metadata Error(_) -> Error(server.ConnectRejected) // Reject with 403 } })
ewe_transport.handler(channels, websocket_config, http_fallback)Return Error(server.ConnectRejected) to send HTTP 403 before the WebSocket
upgrade. See
Reject a connection during authentication
for the client error. See
Authentication failures for
diagnostic steps.
Block cross-site WebSocket hijacking (CSWSH)
Section titled “Block cross-site WebSocket hijacking (CSWSH)”Browsers include cookies on WebSocket handshakes. If your socket authentication
uses cookies, a malicious site can open a WebSocket to your application from a
victim's browser unless you validate the Origin header. This is Cross-Site
WebSocket Hijacking (CSWSH).
Use with_allowed_origins to allow only your application origins. Values match
the full Origin header exactly: scheme, host, and port when present.
let websocket_config = server.default_config("/socket/websocket") |> server.with_allowed_origins(["https://app.example.com"]) |> server.with_on_connect(fn(http_request: Request(ewe.Connection)) { validate_cookie_session(http_request) })Requests with missing or non-matching origins are rejected with HTTP 403 before
the WebSocket handshake. Without an explicit allow-list, the default
SameAuthority policy compares the Origin authority (host and explicit port)
with the request Host, without regard to case. It ignores the scheme, so
http://app.example.com and https://app.example.com both match
Host: app.example.com. Explicit ports must match: default ports are not
normalized, so https://app.example.com:443 does not match that Host.
Requests without Origin, such as those from native clients, are admitted.
Behind a reverse proxy, preserve the public Host header or configure
with_allowed_origins with the public origins. beryl does not trust
X-Forwarded-Host or other forwarded-host headers. Ewe's HTTP/2 extended
CONNECT path uses the parsed :authority when Host is absent.
For both Mist and Ewe, replace explicit references to
beryl/transport/origin.SameOrigin with SameAuthority. The old constructor
was renamed to describe the existing rule, not to change it.
server.default_config calls need no changes. Use with_allowed_origins
when the scheme must also match; its exact-match and absent-header rules
are unchanged.
If you cannot use an origin allow-list, avoid cookie-based WebSocket
authentication. Use a token passed explicitly to on_connect and reject invalid
tokens before upgrading.
Read request data from ConnectSeed
Section titled “Read request data from ConnectSeed”on_connect accepts or rejects the upgrade. The transport puts the request
path, query parameters, and headers in a ConnectSeed, and your init
function receives it as ConnectInfo.seed:
| Field | Type | Description |
|---|---|---|
path | String | The request path the client connected to. |
query | List(#(String, String)) | Parsed query parameters. |
headers | List(#(String, String)) | Request headers. |
metadata | List(#(String, String)) | Whatever on_connect returned. |
on_connect does not return Ok(Nil). It returns Ok(metadata), a
list of string pairs that reaches init as seed.metadata. Resolve the identity once during the handshake and return it as metadata.
Then init can read it instead of decoding the request again:
let websocket_config = server.default_config("/socket/websocket") |> server.with_on_connect(fn(http_request: Request(ewe.Connection)) { // Validate once; reject the whole connection on failure. case validate_token(http_request) { Ok(user_id) -> Ok([#("user_id", user_id)]) Error(_) -> Error(server.ConnectRejected) // Reject with 403 } })// init reads what on_connect already resolved. It does not decode again.beryl.child_spec( config, init: fn(info: socket.ConnectInfo(Message)) { let user_id = list.key_find(info.seed.metadata, "user_id") |> result.unwrap("anonymous") #(Model(user_id: user_id), []) }, update: update,)Return Ok([]) when there is nothing to pass on. The list keeps the order
on_connect produced and keeps duplicate keys, so list.key_find returns the
first pair for a key. Values are strings only: encode anything richer, such as
a list of roles, into one. Transports never log metadata values, but the seed
reaches every join callback on that socket, so put an identity there rather
than a secret.
With the channel layer, the same seed arrives in every handler's join
callback as channel.JoinContext.seed, metadata included; there is no
app-level init. See
Authentication with beryl/channel.
Choose the wire protocol
Section titled “Choose the wire protocol”Pass wire.phoenix_codec() to beryl.config to use the Phoenix JSON array format:
[join_ref, ref, topic, event, payload]Applications can pass a custom codec to beryl.config(codec). The codec can
use another text or binary message format. The transport sends each outbound
frame as the type that the codec returns.
wire.phoenix_codec() uses beryl's Phoenix wire implementation and adds no
dependencies. The public beryl/wire/codec.Codec API and wire format are
stable, so applications can supply a codec for another message format.
| Field | JSON type | Description |
|---|---|---|
join_ref | string | null | Reference from the join (for reply routing) |
ref | string | null | Unique message reference (for reply matching) |
topic | string | Topic name (e.g., "room:lobby") |
event | string | Event name (e.g., "phx_join", "new_message") |
payload | any | JSON payload |
Phoenix protocol events
Section titled “Phoenix protocol events”| Event | Direction | Purpose |
|---|---|---|
phx_join | Client -> Server | Join a channel |
phx_leave | Client -> Server | Leave a channel |
heartbeat | Client -> Server | Keepalive ping |
phx_reply | Server -> Client | Reply to a client message |
phx_error | Server -> Client | Error notification |
phx_close | Server -> Client | Channel closed |
Join request and reply
Section titled “Join request and reply”Client sends:
["1", "1", "room:lobby", "phx_join", {"user": "alice"}]Server replies:
["1", "1", "room:lobby", "phx_reply", {"status": "ok", "response": {}}]Connection steps
Section titled “Connection steps”- Client connects via WebSocket to the configured path
- The
on_connectcallback runs, if configured. Rejection returns HTTP 403. - The transport connection process builds the
ConnectSeed, generates a unique socket ID, and starts a socket actor. The router admits and monitors that actor, which runs yourinit. - The client sends
phx_joinmessages to subscribe to topics. Each one arrives atupdateas aJoinevent. - Messages are routed through the runtime to
updateasMessageevents - On disconnect,
updatereceives aClosedevent for every joined topic
Heartbeats
Section titled “Heartbeats”Clients should send periodic heartbeat messages to stay connected:
[null, "ref_123", "phoenix", "heartbeat", {}]Configure heartbeat timing in the beryl config:
let config = beryl.config(wire.phoenix_codec()) |> beryl.with_heartbeat( timeout_ms: 60_000, // Server evicts after 60s silence (must be >= 2) )Limit inbound traffic
Section titled “Limit inbound traffic”Protect against flood attacks with built-in rate limiting:
let config = beryl.config(wire.phoenix_codec()) |> beryl.with_frame_rate(per_second: 150, burst: 300) |> beryl.with_message_rate(per_second: 100, burst: 200) |> beryl.with_join_rate(per_second: 5, burst: 10) |> beryl.with_channel_rate(per_second: 50, burst: 100)| Limiter | Applies to | Enforced at |
|---|---|---|
frame_rate | Per connection, all complete frames | Transport, before decode |
message_rate | Per socket, decoded non-join traffic | Runtime |
join_rate | Per socket, joins | Runtime |
channel_rate | Per socket+topic | Runtime |
topic_rates | Topics matching a pattern; overrides channel_rate | Runtime |
Frame and message buckets are independent. Malformed frames and joins consume frame tokens; joins do not consume message tokens.
Limit connections by IP address
Section titled “Limit connections by IP address”Cap both the connection-attempt rate and the number of concurrent connections a single client IP may hold. Both controls default to unlimited.
let config = beryl.config(wire.phoenix_codec()) |> beryl.with_connection_rate_per_ip(per_second: 2, burst: 5) |> beryl.with_max_connections_per_ip(max_connections: 5)When a peer reaches either limit, the transport rejects the upgrade with
429 Too Many Requests before the handshake. A closed connection releases its
concurrent capacity. The per-IP rate bucket remains after reconnects and app
runtime restarts. Thus, a reconnect does not provide a new rate allowance.
Reverse proxies and X-Forwarded-For
Section titled “Reverse proxies and X-Forwarded-For”Both controls default to the real TCP peer IP. Mist and Ewe ignore
forwarded headers such as X-Forwarded-For and Forwarded. Clients can forge
these headers.
Behind a proxy, all clients share its address by default. Enforce per-client limits at the proxy, or opt in to your own trusted-proxy extractor through the shared transport configuration:
let websocket_config = server.default_config("/socket/websocket") |> server.with_client_ip_extractor(my_trusted_proxy_extractor)my_trusted_proxy_extractor has the type
fn(Request(body), Result(String, Nil)) -> Result(String, server.ClientIpError).
The second argument is the real TCP peer lookup result. Verify that peer against your trusted-proxy policy before reading forwarded headers. The extractor owns trusted-hop traversal, duplicate and malformed header handling, numeric IP parsing, and canonical formatting. beryl does not provide those checks. For an untrusted direct peer, ignore its forwarded headers and return the peer address, or reject it according to your policy.
Return Ok(ip) with a canonical numeric IP address,
Error(server.ClientIpUnavailable) when no trustworthy address is available,
or Error(server.ClientIpExtractionFailed) when extraction fails. Empty
strings and the reserved "unknown" value are extraction failures. Return a
Result rather than raising an exception. The callback runs once after
origin/version checks and before admission and authentication.
With either per-IP control enabled, an address failure rejects with 403.
It emits client_ip_unavailable or client_ip_extraction_failed upgrade
telemetry when telemetry is enabled. No rate token or connection slot is
consumed. There is no fallback to the peer after extractor failure.
Without either per-IP control, an unavailable address does not block the
upgrade. The admission pipeline retains "unknown" only as an unused per-IP
key; a total connection ceiling still applies. Previously, unidentified
clients shared an "unknown" bucket even with per-IP controls enabled.
Deployments that relied on that behavior must now provide a trustworthy IP
or disable those controls.
The extracted address keys both concurrent connections and connection-attempt rate accounting. Frame, message, join, and channel rates are unchanged. See deployment hardening for trust and deployment guidance.
Next steps
Section titled “Next steps”- Error Handling guide: rejected joins, malformed frames, and client errors
- Channels guide: use the transport with the channel layer
- Supervision guide: understand runtime restarts and shutdown
- Troubleshooting: diagnose connection, join, and message delivery failures
