gitmyhub

MQTT.js

TypeScript ★ 9.1k updated 1mo ago

The MQTT client for Node.js and the browser

MQTT.js is a JavaScript library for sending and receiving messages between connected devices using the MQTT protocol, the standard for smart home and IoT communication, in both Node.js and the browser.

TypeScriptJavaScriptNode.jsWebSocketsetup: easycomplexity 2/5

MQTT.js is a JavaScript library that lets Node.js applications and web browsers communicate using the MQTT protocol. MQTT is a lightweight messaging standard designed for situations where devices need to send small amounts of data reliably over potentially unreliable connections, which is why it is common in smart home devices, industrial sensors, and other connected hardware.

The way MQTT works is through a publish-subscribe model. Instead of two devices talking directly to each other, they both connect to a central server called a broker. One device publishes a message to a named channel, called a topic, and any other device that has subscribed to that topic receives the message. MQTT.js handles all the client-side mechanics of this: connecting to the broker, sending messages, receiving messages, and reconnecting automatically if the connection drops.

For developers, the library is installed through npm and works in Node.js or in the browser via WebSocket connections. It includes a command-line tool so you can publish and subscribe to topics directly from a terminal without writing any code, which is useful for testing. The library supports MQTT versions 3.1, 3.1.1, and 5.0, with the latter adding features like message expiry and better error reporting.

The current major version (v5) was rewritten in TypeScript, which provides type definitions that help catch mistakes at development time in typed projects. The library handles reconnection logic, optional message delivery guarantees (called QoS levels), and authentication, including a hook for refreshing expired credentials when a connection needs to re-establish.

MQTT.js is the most widely used MQTT client in the JavaScript ecosystem and is maintained as an open source project. The full README is longer than what was shown.

Where it fits