🔥 Firehook

Blog · mqtt

MQTT over WebSockets: when and why to use it

Use MQTT in browsers with WebSockets: tradeoffs, security, and performance considerations.

Isometric glossy broker pillar with branching device tokens and glowing publish/subscribe dots

Why WebSockets exist for MQTT

Browsers cannot open raw TCP sockets, so MQTT over WebSockets is the standard way to bring MQTT into web apps.

It allows dashboards and admin tools to subscribe to live device data without custom polling.

Performance considerations

WebSocket frames add some overhead compared to raw MQTT, but the persistent connection still avoids HTTP polling costs.

For real-time dashboards, MQTT over WebSockets often feels faster and more reliable than repeated HTTP requests.

Security in the browser

Use WSS (TLS) and short-lived tokens. Browsers expose tokens more easily than devices, so you must reduce blast radius.

Apply topic ACLs that limit what a web client can subscribe to or publish.

Connection limits and scaling

Browser clients can create many connections, especially in multi-tab scenarios. Implement client-side singleton connections where possible.

On the broker side, limit per-user connections and enforce idle timeouts.

Payload sizing for UI

Web UIs should not receive heavy payloads. Publish compact messages and let the UI fetch heavy data via HTTP when necessary.

This hybrid approach keeps MQTT real-time while preserving UI performance.

Fallback strategies

If WebSockets are blocked (enterprise networks), consider a fallback to HTTP polling for a limited subset of features.

Make the fallback explicit so users understand any delay.

When to avoid it

If your app only needs occasional updates, HTTP polling may be simpler. MQTT over WebSockets shines when you need continuous, low-latency updates.

Use it for real-time dashboards, presence indicators, and command status tracking.

FAQ

Is MQTT over WebSockets secure?
Yes, with WSS and short-lived auth tokens.
Is it slower than raw MQTT?
A bit, but still far more efficient than HTTP polling.
Can browsers publish commands?
Yes, but restrict topics and validate on the server side.
Does it work on mobile?
Yes, modern mobile browsers support WebSockets.
Should I still offer HTTP APIs?
Usually yes, for configuration and bulk data.