WebSockets and Browser Clients
Connect to Pub/Sub with WebSockets
Pub/Sub allows you to both publish and subscribe from within a web browser or other WebSocket capable client. Every Pub/Sub Broker supports MQTT over WebSockets natively, without further configuration.
With Pub/Sub’s WebSocket support, you can:
- Subscribe to a topic in the browser and push near real-time updates (such as notifications or chat messages) to those clients from your backend services.
- Publish telemetry directly from WebSocket clients and then aggregate those messages in a centralized service or by using Workers Analytics Engine ↗ to consume them on your behalf.
- Publish and subscribe directly between a browser client and your MQTT-capable IoT devices in the field.
When clients are connecting from a browser, you should use token
authentication and ensure you are issuing clients unique credentials.
WebSocket support in Pub/Sub works by encapsulating MQTT packets (Pub/Sub’s underlying native protocol) within WebSocket frames ↗.
- In many MQTT libraries, you can replace the
mqtts://
scheme withwss://
, and your code will use a WebSocket transport instead of the native “raw” TCP transport. - The WebSocket listener is available on both TCP ports
443
and8884
versus8883
for native MQTT. - WebSocket clients need to speak MQTT over WebSockets. Pub/Sub does not support other message serialization methods over WebSockets at present.
- Clients should include a
sec-websocket-protocol: mqtt
request header in the initial HTTP GET request to distinguish an “MQTT over WebSocket” request from future, non-MQTT protocol support over WebSockets. - Authentication is performed within the WebSocket connection itself. An MQTT
CONNECT
packet inside the WebSocket tunnel includes the required username and password. The WebSocket connection itself does not need to be authenticated at the HTTP level.
We recommend using MQTT.js ↗, one of the most popular JavaScript libraries, for client-side JavaScript support. It can be used in both the browser via Webpack or Browserify and in a Node.js environment.
In this example, we use MQTT.js’s WebSocket support to subscribe to a topic and publish messages to it.
In a real-world deployment, our publisher could be another client, a native MQTT client, or a WebSocket client running on a remote server elsewhere.
You can use a JavaScript bundler, such as Webpack, to include the library into a script you can include in your web application.