Skip to content

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.

Use ewe_transport.handler to combine WebSocket upgrades and regular HTTP routing in one Ewe listener:

import beryl
import beryl/transport/server
import beryl_ewe as ewe_transport
import ewe
import 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 beryl
import beryl/transport/server
import beryl_mist
import gleam/bytes_tree
import gleam/http/request
import gleam/http/response
import 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.

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.

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:

FieldTypeDescription
pathStringThe request path the client connected to.
queryList(#(String, String))Parsed query parameters.
headersList(#(String, String))Request headers.
metadataList(#(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.

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.

FieldJSON typeDescription
join_refstring | nullReference from the join (for reply routing)
refstring | nullUnique message reference (for reply matching)
topicstringTopic name (e.g., "room:lobby")
eventstringEvent name (e.g., "phx_join", "new_message")
payloadanyJSON payload
EventDirectionPurpose
phx_joinClient -> ServerJoin a channel
phx_leaveClient -> ServerLeave a channel
heartbeatClient -> ServerKeepalive ping
phx_replyServer -> ClientReply to a client message
phx_errorServer -> ClientError notification
phx_closeServer -> ClientChannel closed

Client sends:

["1", "1", "room:lobby", "phx_join", {"user": "alice"}]

Server replies:

["1", "1", "room:lobby", "phx_reply", {"status": "ok", "response": {}}]
  1. Client connects via WebSocket to the configured path
  2. The on_connect callback runs, if configured. Rejection returns HTTP 403.
  3. 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 your init.
  4. The client sends phx_join messages to subscribe to topics. Each one arrives at update as a Join event.
  5. Messages are routed through the runtime to update as Message events
  6. On disconnect, update receives a Closed event for every joined topic

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)
)

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)
LimiterApplies toEnforced at
frame_ratePer connection, all complete framesTransport, before decode
message_ratePer socket, decoded non-join trafficRuntime
join_ratePer socket, joinsRuntime
channel_ratePer socket+topicRuntime
topic_ratesTopics matching a pattern; overrides channel_rateRuntime

Frame and message buckets are independent. Malformed frames and joins consume frame tokens; joins do not consume message tokens.

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.

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.