MQTT Fundamentals

MQTT vs WebSocket: Protocol or Transport?

WebSocket and MQTT are often compared, but one is a transport and the other a messaging protocol. Learn what raw WebSocket apps must build themselves and how to run MQTT over secure WebSocket in the browser.

Layered diagram showing MQTT packets carried inside a WebSocket connection from a browser to a broker, explaining MQTT vs WebSocket
Run this on your own MQTT brokerGet a private, managed MQTT broker on the Free plan and start from ready-made code samples.
Try it free Code samples No card required

MQTT vs WebSocket sounds like a choice between two competing protocols, but it is really a question about layers. WebSocket is a transport that gives a browser a full-duplex pipe to a server; MQTT is a messaging protocol that defines topics, subscriptions, delivery guarantees and session state, and it can run over that pipe. This guide explains the difference, shows what a raw WebSocket app has to build by hand, and walks through connecting a browser to an MQTT broker over secure WebSocket.

What WebSocket Actually Is

WebSocket (RFC 6455) starts as an HTTP request with an Upgrade: websocket header. Once the server agrees, the connection switches to a lightweight framing format where either side can send text or binary messages at any time. It solves one specific problem: browsers could not hold an open, bidirectional connection to a server before it existed.

What WebSocket does not define is just as important. There are no topics, no subscriptions, no acknowledgments beyond TCP, no notion of who should receive a message, no reconnection behavior and no state that survives a dropped connection. Every application on top of a raw WebSocket invents its own message format and semantics.

What MQTT Adds

MQTT is an application protocol with a well-defined packet set: CONNECT, PUBLISH, SUBSCRIBE, acknowledgments and so on. It gives you:

  • Topic-based routing through a broker, with + and # wildcards.
  • QoS 0, 1 and 2 delivery guarantees per message.
  • Retained messages so a new client immediately gets the last known value.
  • Persistent sessions that queue messages while a client is offline.
  • Keep alive and Last Will for online/offline detection.
  • MQTT 5 extras such as message expiry, response topics for request/response, user properties and reason codes.

MQTT normally runs over plain TCP or TLS, but the specification also defines how to carry it over WebSocket, using the mqtt subprotocol. That is what lets a browser speak the same protocol as an ESP32. For the background on how the broker routes all this, see how MQTT works.

MQTT vs WebSocket Comparison Table

Aspect Raw WebSocket MQTT (over TCP or WebSocket)
Layer Transport (framed, full-duplex) Application messaging protocol
Message format Whatever you define Standard packets with topics and properties
Routing Your server code decides Broker routes by topic and wildcard
Fan-out to many clients You track connections and loop Broker delivers to all matching subscribers
Delivery guarantees None beyond TCP QoS 0, 1, 2
Last-known state You build a cache Retained messages
Offline buffering You build it Persistent sessions
Presence You build heartbeats Keep alive and Last Will
Device support Mostly browsers and servers Microcontrollers, gateways, servers, browsers
Interoperability Only with your own server Any MQTT client and broker

What a Raw WebSocket App Has to Build

Here is a realistic picture of a raw WebSocket dashboard backend. The server keeps a map of connected browsers. Devices post readings over HTTP or their own socket. When a reading arrives, the server decides who should get it, loops through the matching sockets and sends JSON. Then the requirements arrive:

  1. Browsers should only receive data for the sites they are viewing, so you add a "subscribe" message type and a filtering scheme.
  2. A newly opened dashboard should show current values immediately, so you add a cache of last values.
  3. Mobile clients drop off often, so you add heartbeats and reconnect logic in the browser.
  4. Commands need confirmation, so you add message IDs and acknowledgments.
  5. You need a second server for load, so you add a pub/sub layer between servers so a reading on one reaches browsers on the other.

At that point you have rebuilt a broker, without the interoperability. With MQTT over WebSocket, each of those features already exists and devices and browsers share one system.

Raw WebSocket is still the right choice for some jobs: a chat feature inside an existing web app, collaborative editing, a game server, or any case where both ends are your own code and the message semantics are unique to your application.

Connect a Browser to MQTT over WebSocket

ConnectMQ exposes MQTT over WebSocket on port 8083 and over secure WebSocket on port 8084, both on the path /mqtt. Browsers served over HTTPS must use the secure variant. The example below uses MQTT.js from a CDN and the free public MQTT broker, so you can save it as an HTML file and open it directly.

// Load MQTT.js first, for example:
// <script src="https://unpkg.com/mqtt@5.10.1/dist/mqtt.min.js"></script>

const prefix = "connectmq/demo/" + Math.random().toString(16).slice(2, 10);
const clientId = "browser-" + Math.random().toString(16).slice(2, 10);

const client = mqtt.connect("wss://broker.connectmq.com:8084/mqtt", {
  clientId,
  protocolVersion: 5,
  clean: true,
  keepalive: 30,
  reconnectPeriod: 2000,
});

client.on("connect", () => {
  console.log("connected as", clientId);
  client.subscribe(prefix + "/sensors/+/temperature", { qos: 1 });

  // Publish a retained reading so late joiners see it immediately
  client.publish(
    prefix + "/sensors/room1/temperature",
    JSON.stringify({ value: 22.3, ts: Date.now() }),
    { qos: 1, retain: true }
  );
});

client.on("message", (topic, payload, packet) => {
  console.log(topic, payload.toString(), "retain:", packet.retain);
});

client.on("reconnect", () => console.log("reconnecting..."));
client.on("error", (err) => console.error("mqtt error:", err.message));

console.log("Publish test data with:");
console.log(`mosquitto_pub -h broker.connectmq.com -p 1883 -i cli-${clientId} -t "${prefix}/sensors/room2/temperature" -m '{"value":19.8}'`);

Run the printed mosquitto_pub command from a terminal and the browser console shows the message arriving from a plain TCP client. That is the point of MQTT over WebSocket: the transport differs, the topics and semantics are the same.

For a private broker, replace the URL host with your broker address and add username: "YOUR_USERNAME" and password: "YOUR_PASSWORD" to the options, with clientId: "YOUR_CLIENT_ID". Remember that anything shipped to a browser is visible to its user, so give browser clients their own limited credentials rather than reusing device or backend credentials. The MQTT over WebSocket guide covers ports, proxies and troubleshooting in more depth, and MQTT in the browser with JavaScript builds a complete dashboard.

Performance and Overhead

MQTT over WebSocket adds a small WebSocket frame header on top of each MQTT packet, plus the initial HTTP upgrade. For dashboard traffic that cost is negligible. For constrained devices there is no reason to use WebSocket at all; connect over TCP on 1883 or TLS on 8883 and save the bytes. A common split is devices on 8883 and browsers on 8084, both talking to the same broker.

Common Pitfalls

  • Wrong path. Many brokers, including ConnectMQ, expect /mqtt. Connecting to the root path fails with a handshake error.
  • Mixed content. A page served over HTTPS cannot open a ws:// connection. Use wss:// and port 8084.
  • Shared client IDs. Two browser tabs with the same hard-coded client ID will kick each other off repeatedly. Generate one per tab.
  • Corporate proxies. Some proxies interfere with WebSocket upgrades on non-standard ports. Test from the networks your users actually use.
  • Leaking secrets. Never embed backend or device credentials in front-end code.

Which Should You Choose?

If you are building a real-time feature where both ends are your own web code and the semantics are unique, raw WebSocket is fine. If browsers need to see data from devices, if several clients share the same data, or if you need guarantees, retained state and presence, choose MQTT and use WebSocket as its transport in the browser. A managed MQTT broker gives you both endpoints, TCP for devices and WSS for browsers, without running the infrastructure yourself. For a full introduction to the protocol, start with the MQTT tutorial.

Build Real-Time Dashboards on ConnectMQ

ConnectMQ serves MQTT on 1883 and 8883 and MQTT over WebSocket on 8083 and 8084 with a Let's Encrypt certificate, so devices and browsers connect to the same broker. Create a free Serverless broker at app.connectmq.com, no credit card required, and test it with the portal's in-browser MQTT client before you write a line of front-end code.

Frequently Asked Questions

Is MQTT better than WebSocket?

They are not alternatives at the same layer. WebSocket is a transport; MQTT is a messaging protocol that can run over WebSocket. Use MQTT when you need topics, fan-out and delivery guarantees.

Can a browser connect directly to an MQTT broker?

Yes, if the broker supports MQTT over WebSocket. With ConnectMQ, use wss://broker.connectmq.com:8084/mqtt and a library such as MQTT.js.

Why does my MQTT WebSocket connection fail on an HTTPS page?

Browsers block insecure ws:// connections from HTTPS pages. Switch to wss:// on port 8084 and check that the path is /mqtt.

Should IoT devices use MQTT over WebSocket?

Usually not. Devices should use MQTT over TCP or TLS directly, which has less overhead. WebSocket is mainly for browsers and networks that only allow web traffic.

Related articles

Why Your MQTT Client Keeps Disconnecting (and How to Fix It)

Reconnect loops are one of the most common MQTT problems. Learn the five usual causes, from duplicate client IDs to keep alive timeouts and oversized packets, and follow a diagnosis flow that pinpoints yours.

8 min read

Who Invented MQTT? The History from Oil Pipelines to IoT

MQTT was invented in 1999 by Andy Stanford-Clark of IBM and Arlen Nipper of Arcom to monitor oil pipelines over satellite. Follow its path to open source, OASIS, ISO and today's managed cloud brokers.

7 min read

MQTT Maximum Message Size: Limits and Large Payload Strategies

MQTT can technically carry a 256 MB packet, but brokers, client libraries and devices impose far lower limits. Learn where the real limits are, what happens when you exceed them, and how to send large payloads.

7 min read

All articles →

Your private MQTT broker is a few clicks away

Create an account, get your broker credentials and connect your first device — no servers to install, patch or scale.