### Install Project Dependencies Source: https://github.com/mqttjs/mqtt.js/blob/main/examples/vite-example/README.md Run this command to install all necessary packages for the project. ```sh npm install ``` -------------------------------- ### Example Output Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md The expected output when the basic MQTT subscriber and publisher example is run successfully. ```sh Hello mqtt ``` -------------------------------- ### Basic MQTT Subscriber and Publisher Example Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md A simple example demonstrating how to connect to an MQTT broker, subscribe to a topic, and publish a message. The client disconnects after receiving a message. Ensure you have a running MQTT broker accessible at the specified URI. ```js const mqtt = require("mqtt"); const client = mqtt.connect("mqtt://test.mosquitto.org"); client.on("connect", () => { client.subscribe("presence", (err) => { if (!err) { client.publish("presence", "Hello mqtt"); } }); }); client.on("message", (topic, message) => { // message is Buffer console.log(message.toString()); client.end(); }); ``` -------------------------------- ### Install MQTT.js Globally Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Install the MQTT.js command-line tools globally to use them on your system's path. ```bash npm install mqtt -g ``` -------------------------------- ### Start Development Server Source: https://github.com/mqttjs/mqtt.js/blob/main/examples/vite-example/README.md Use this command to compile the project and enable hot-reloading for development. ```sh npm run dev ``` -------------------------------- ### Install MQTT.js Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Install the MQTT.js library using npm. This command adds the package as a dependency to your project. ```sh npm install mqtt --save ``` -------------------------------- ### Subscribe to a Topic (CLI) Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Use the MQTT.js CLI to subscribe to a topic and view messages in real-time. Requires global installation. ```bash mqtt sub -t 'hello' -h 'test.mosquitto.org' -v ``` -------------------------------- ### Publish to a Topic (CLI) Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Use the MQTT.js CLI to publish a message to a specific topic. Requires global installation. ```bash mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js' ``` -------------------------------- ### Connect with TypeScript Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Connect to an MQTT broker using MQTT.js with TypeScript. Ensure you have the necessary type definitions installed. ```typescript import { connect } from "mqtt" const client = connect('mqtt://test.mosquitto.org') ``` -------------------------------- ### Enable MQTT.js Debug Logs Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Set the DEBUG environment variable to 'mqttjs*' to enable debug logging for MQTT.js. This example uses PowerShell. ```powershell $env:DEBUG='mqttjs*' ``` -------------------------------- ### MqttClient Instantiation Source: https://github.com/mqttjs/mqtt.js/wiki/client Demonstrates how to create an MqttClient instance using the factory methods. ```APIDOC ## Client Instantiation The primary method of instantiating `MqttClient` is through the factory method `mqtt.createClient` or `mqtt.createSecureClient` for a tls secured client. It is possible to instantiate `MqttClient` using `new MqttClient(...)`, but it requires the user to generate their own underlying stream (such as a `net.Socket`). Thus, it is recommended that the factory methods be used. ``` -------------------------------- ### mqtt.Client Constructor and Options Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Initializes a new MQTT client instance and outlines the available connection options. ```APIDOC ## mqtt.Client(streamBuilder, options) ### Description The `Client` class wraps a client connection to an MQTT broker over an arbitrary transport method (TCP, TLS, WebSocket, etc.). It extends `EventEmitter` and automatically handles server pings, QoS flow, and reconnections. ### Parameters #### `streamBuilder` - `function` - A function that returns a subclass of the `Stream` class supporting the `connect` event (typically a `net.Socket`). #### `options` (object) - Client connection options: - `wsOptions` (object) - WebSocket connection options. Defaults to `{}`. - `keepalive` (number) - Server ping interval in seconds. Set to `0` to disable. Defaults to `60`. - `reschedulePings` (boolean) - Reschedule ping messages after sending packets. Defaults to `true`. - `clientId` (string) - Unique client identifier. Defaults to `'mqttjs_' + Math.random().toString(16).substr(2, 8)`. - `protocolId` (string) - MQTT protocol identifier. Defaults to `'MQTT'`. - `protocolVersion` (number) - MQTT protocol version. Defaults to `4`. - `clean` (boolean) - Whether to perform a clean start. Set to `false` to receive QoS 1 and 2 messages while offline. Defaults to `true`. - `reconnectPeriod` (number) - Interval between reconnections in milliseconds. Set to `0` to disable auto reconnect. Defaults to `1000`. - `reconnectOnConnackError` (boolean) - Reconnect if a CONNACK is received with an error. Defaults to `false`. - `connectTimeout` (number) - Time to wait for CONNACK in milliseconds. Defaults to `30000`. - `username` (string) - Username for broker authentication, if required. - `password` (string) - Password for broker authentication, if required. - `socksProxy` (string) - URL for establishing connections via a SOCKS proxy (e.g., `socks5://`). - `socksTimeout` (number) - Timeout for connecting to the SOCKS proxy in milliseconds. - `incomingStore` (object) - A [Store](#store) for incoming packets. - `outgoingStore` (object) - A [Store](#store) for outgoing packets. - `queueQoSZero` (boolean) - Queue outgoing QoS zero messages if the connection is broken. Defaults to `true`. - `customHandleAcks` (function) - MQTT 5.0 feature for custom handling of puback and pubrec packets. Callback signature: `function(topic, message, packet, done) { /* logic */ }`. - `autoUseTopicAlias` (boolean) - Enable automatic Topic Alias usage. - `autoAssignTopicAlias` (boolean) - Enable automatic Topic Alias assignment. - `properties` (object) - MQTT 5.0 properties: - `sessionExpiryInterval` (number) - Session Expiry Interval in seconds. - `receiveMaximum` (number) - Maximum number of unacknowledged messages. - `maximumPacketSize` (number) - Maximum packet size the client will accept. - `topicAliasMaximum` (number) - Maximum Topic Alias value the client will accept from the server. - `requestResponseInformation` (boolean) - Request Response Information in CONNACK. - `requestProblemInformation` (boolean) - Indicate whether Reason String or User Properties are sent on failures. - `userProperties` (object) - User properties as key-value pairs. - `authenticationMethod` (string) - Authentication method name. - `authenticationData` (binary) - Binary authentication data. - `authPacket` (object) - Settings for the authentication packet. - `will` (object) - Message to be published by the broker when the client disconnects badly: - `topic` (string) - Topic to publish the will message. - `payload` (string/buffer) - The message payload. - `qos` (number) - QoS level (0, 1, or 2). - `retain` (boolean) - Retain flag. - `properties` (object) - MQTT 5.0 will properties: - `willDelayInterval` (number) - Will Delay Interval in seconds. - `payloadFormatIndicator` (boolean) - Payload is UTF-8 encoded. - `messageExpiryInterval` (number) - Lifetime of the Will Message in seconds. - `contentType` (string) - Content type of the Will Message. - `responseTopic` (string) - Topic name for a response message. - `correlationData` (binary) - Correlation data for request/response matching. - `userProperties` (object) - User properties for the will message. ``` -------------------------------- ### Create MQTT Server Source: https://github.com/mqttjs/mqtt.js/wiki/server Instantiate a standard MQTT server. This server handles client connections, including 'connect', 'publish', 'subscribe', 'pingreq', and 'disconnect' events. ```javascript var mqtt = require('mqtt'); var server = mqtt.createServer(function(client) { client.on('connect', function(packet) { // Check if connect fields are correct // Add client to list of connected clients client.connack({returnCode: 0}); }); client.on('publish', function(packet) { // Perform QoS handling if necessary // Publish message to all appropriate clients }); client.on('subscribe', function(packet) { // Add subscription to client subscription list client.suback([0]); }); client.on('pingreq', function(packet) { client.pingresp(); }); client.on('disconnect', function(packet) { // Disconnect client // Remove from list of clients }); }); ``` -------------------------------- ### Instantiate MqttClient with Factory Method Source: https://github.com/mqttjs/mqtt.js/wiki/client Use mqtt.createClient or mqtt.createSecureClient for instantiating MqttClient. Direct instantiation with 'new MqttClient' requires manual stream creation. ```javascript const client = mqtt.createClient(options); ``` ```javascript const secureClient = mqtt.createSecureClient(options); ``` -------------------------------- ### Transform WebSocket URL for Reconnection Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Customize the WebSocket URL and client options during reconnection using the `transformWsUrl` hook. This example updates username and clientId. ```javascript const transformWsUrl = (url, options, client) => { client.options.username = `token=${this.get_current_auth_token()}`; client.options.clientId = `${this.get_updated_clientId()}`; return `${this.get_signed_cloud_url(url)}`; } const connection = await mqtt.connectAsync(, { ..., transformWsUrl: transformUrl, }); ``` -------------------------------- ### Build for Production Source: https://github.com/mqttjs/mqtt.js/blob/main/examples/vite-example/README.md Execute this command to compile and minify the project for production deployment. ```sh npm run build ``` -------------------------------- ### Create and Connect MqttConnection Source: https://github.com/mqttjs/mqtt.js/wiki/connection Demonstrates how to create a raw MQTT connection using mqtt.createConnection and send a CONNECT packet with options. Requires manual handling of connection acknowledgments and subsequent operations. ```javascript var mqtt = require('mqtt'); var conn = mqtt.createConnection( 1883, 'localhost', function(err, client) { if (err) throw err; client.connect({ protocolId: 'MQIsdp', protocolVersion: 3, clientId: 'example', keepalive: 30 }); client.on('connack', function(packet) { if (packet.returnCode !== 0) { throw 'Connect error' } client.publish({ topic: 'example', payload: new Buffer('example', 'utf8') }); }); }); ``` -------------------------------- ### mqtt.connect() Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Establishes a connection to an MQTT broker. ```APIDOC ## mqtt.connect([url], options) ### Description Connects to the MQTT broker specified by the given URL and options, returning a `Client` instance. ### Method `mqtt.connect([url], options) ### Endpoint N/A (Client-side function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### URL Format The `url` parameter can be a string or an object. **String Protocols Supported**: 'mqtt', 'mqtts', 'tcp', 'tls', 'ws', 'wss', 'wxs', 'alis'. **Unix Socket**: Append `+unix` to the protocol (e.g., `mqtt+unix://...`). This automatically sets the `unixSocket` property. **Object Format**: If the `url` is an object (e.g., from `URL.parse()`), it is merged with the `options` object. ### Options #### `servers` Option - **Type**: Array of objects - **Description**: An array of server objects, each with `host` and `port` properties. The client iterates through this array to attempt connections. Example: `[{ host: 'localhost', port: 1883 }, ... ]` For all other MQTT-related options, refer to the [Client constructor](#client) documentation. ``` -------------------------------- ### Client Connection: connect() Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Manually initiates a connection to the MQTT broker. Useful when `manualConnect` is set to true during client instantiation. ```APIDOC ## mqtt.Client#connect() ### Description By default, the client connects when the constructor is called. To prevent this, you can set the `manualConnect` option to `true` and call `client.connect()` manually. ### Method `connect()` ### Endpoint N/A (Client-side method) ``` -------------------------------- ### MqttServer Creation Source: https://github.com/mqttjs/mqtt.js/wiki/server Instantiate a new MQTT server using the mqtt.createServer factory method. This method returns an instance of MqttServer. ```APIDOC ## MqttServer Creation ### Description Instantiates a new MQTT server. It is recommended to use the factory method `mqtt.createServer`. ### Method `mqtt.createServer([listener])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript var mqtt = require('mqtt'); var server = mqtt.createServer(function(client) { client.on('connect', function(packet) { client.connack({returnCode: 0}); }); client.on('publish', function(packet) { // Handle publish }); client.on('subscribe', function(packet) { client.suback([0]); }); client.on('pingreq', function(packet) { client.pingresp(); }); client.on('disconnect', function(packet) { // Handle disconnect }); }); ``` ### Response #### Success Response (200) N/A (Server creation does not return a response in the traditional sense, but emits events). #### Response Example N/A ``` -------------------------------- ### MQTT.js Client Options Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Configuration options for the MQTT.js client constructor. ```APIDOC ## MQTT.js Client Options ### transformWsUrl - **Type**: `optional (url, options, client) => url` function - **Description**: For ws/wss protocols only. Can be used to implement signing URLs which upon reconnect can have become expired. ### createWebsocket - **Type**: `optional url, websocketSubProtocols, options) => Websocket` function - **Description**: For ws/wss protocols only. Can be used to implement a custom websocket subprotocol or implementation. ### resubscribe - **Type**: `boolean` - **Default**: `true` - **Description**: If connection is broken and reconnects, subscribed topics are automatically subscribed again. ### subscribeBatchSize - **Type**: `optional number` - **Description**: Maximum number of topics per SUBSCRIBE packet. When the number of topics to subscribe exceeds this value, the client will automatically split them into multiple SUBSCRIBE packets of this size. ### messageIdProvider - **Type**: `custom messageId provider` - **Description**: Custom messageId provider. When `new UniqueMessageIdProvider()` is set, then non-conflicting messageId is provided. ### log - **Type**: `custom log function` - **Default**: Uses the [debug](https://www.npmjs.com/package/debug) package. - **Description**: Custom log function. ### manualConnect - **Type**: `boolean` - **Description**: Prevents the constructor from calling `connect`. In this case, after `mqtt.connect` is called, you should call `client.connect()` manually. ### timerVariant - **Type**: `string` or `object` - **Default**: `auto` - **Description**: Attempts to determine the most appropriate timer for your environment. If you're having detection issues, you can set it to `worker` or `native`. If none suits you, you can pass a timer object with `set` and `clear` properties. ```js timerVariant: { set: (func, timer) => setInterval(func, timer), clear: (id) => clearInterval(id) } ``` ### forceNativeWebSocket - **Type**: `boolean` - **Description**: Set to `true` if you're having detection issues (i.e., the `ws does not work in the browser` exception) to force the use of native WebSocket. If set to `true` for the first client created, then all clients will use native WebSocket. Conversely, if not set or set to `false`, all will use the detection result. ### unixSocket - **Type**: `boolean` - **Description**: Set to `true` if you want to connect to a Unix socket. ### socksProxy - **Type**: `string` - **Description**: You can also supply the same parameter via the environment variable `MQTTJS_SOCKS_PROXY`. ### tls Options - **Description**: In case `mqtts` (mqtt over tls) is required, the `options` object is passed through to [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback). - **`rejectUnauthorized`**: If using a self-signed certificate, set to `false`. Be cautious as this exposes you to potential man-in-the-middle attacks and isn't recommended for production. - **`ALPNProtocols`**: For supporting multiple TLS protocols on a single port (e.g., MQTTS and MQTT over WSS), utilize this option. It lets you define the Application Layer Protocol Negotiation (ALPN) protocol. You can set `ALPNProtocols` as a string array, Buffer, or Uint8Array based on your setup. ### MQTT 3.1 Support - **Description**: If you are connecting to a broker that supports only MQTT 3.1 (not 3.1.1 compliant), you should pass these additional options: ```js { protocolId: 'MQIsdp', protocolVersion: 3 } ``` This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto version 1.3 and 1.4 works fine without those. ``` -------------------------------- ### Run Browser Tests Source: https://github.com/mqttjs/mqtt.js/blob/main/DEVELOPMENT.md Build the browser bundle using esbuild and run tests with the Web Test Runner. ```sh npm run test:browser ``` -------------------------------- ### MQTT Server Creation Source: https://github.com/mqttjs/mqtt.js/wiki/mqtt Methods for creating MQTT server instances, both standard and secure. ```APIDOC ## mqtt#createServer([listener]) ### Description Create a new `MqttServer`. ### Method `mqtt.createServer ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ## mqtt#createSecureServer(keyPath, certPath, [listener]) ### Description Create a new `MqttSecureServer`. ### Method `mqtt.createSecureServer ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ``` -------------------------------- ### Create Secure MQTT Server Source: https://github.com/mqttjs/mqtt.js/wiki/server Instantiate a secure MQTT server using TLS. Requires paths to the private key and certificate files. It handles the same client events as the standard server. ```javascript var mqtt = require('mqtt'); var server = mqtt.createSecureServer( __dirname + 'private-key.pem', __dirname + 'cert.pem', function(client) { client.on('connect', function(packet) { // Check if connect fields are correct // Add client to list of connected clients client.connack({returnCode: 0}); }); client.on('publish', function(packet) { // Perform QoS handling if necessary // Publish message to all appropriate clients }); client.on('subscribe', function(packet) { // Add subscription to client subscription list client.suback([0]); }); client.on('pingreq', function(packet) { client.pingresp(); }); client.on('disconnect', function(packet) { // Disconnect client // Remove from list of clients }); }); ``` -------------------------------- ### Original MQTT Client (mqttjs@0.1.8) Source: https://github.com/mqttjs/mqtt.js/wiki/migration-example This code represents the original client implementation using an older version of mqttjs. It requires manual handling of connection events and uses a different callback structure for client creation. ```javascript var mqtt = require('mqtt'); mqtt.createClient(1883, 'localhost', function(err, client) { if (err) throw err; client.connect({keepalive:10000}); client.on('connack', function(packet) { if (packet.returnCode !== 0) throw 'Connect error'; client.subscribe({topic: 'example'}); client.publish({topic: 'test', payload: 'test'}); }); client.on('publish', function(packet) { var t = packet.topic , p = packet.payload; console.log('topic: ' + t + ' payload: ' + p); }); setInterval(client.pingreq.bind(client), 10000); }); ``` -------------------------------- ### Import MQTT (ES6 Default) Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Use this for default ES6 module imports. It imports the entire MQTT.js namespace and creates a client. ```javascript import mqtt from "mqtt"; // import namespace "mqtt" let client = mqtt.connect("mqtt://test.mosquitto.org"); // create a client ``` -------------------------------- ### MQTT Client Creation Source: https://github.com/mqttjs/mqtt.js/wiki/mqtt Methods for creating MQTT client instances, including standard, secure, and connection-based approaches. ```APIDOC ## mqtt#createClient([port], [host], [options]) ### Description Create a new `MqttClient`. ### Method `mqtt.createClient ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ## mqtt#createSecureClient([port], [host], options) ### Description Create a new secure `MqttClient`. ### Method `mqtt.createSecureClient ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ## mqtt#createConnection([port], [host], [callback]) ### Description Create a new `MqttConnection`. ### Method `mqtt.createConnection ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ## mqtt#connect(brokerUrl, [options]) ### Description Create a new `MqttClient` using a broker URL. ### Method `mqtt.connect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ``` -------------------------------- ### New MQTT Client API (mqttjs@0.2.0) Source: https://github.com/mqttjs/mqtt.js/wiki/migration-example This code demonstrates the updated client implementation using mqttjs@0.2.0. It features a simplified API for client creation and event handling, including a dedicated 'connect' event and a 'message' event for incoming messages. ```javascript var mqtt = require('mqtt'); var client = mqtt.createClient(1883, 'localhost', { keepalive: 10000 }); client.on('connect', function() { client.subscribe('example'); client.publish('test', 'test'); client.on('message', function(topic, message) { console.log('topic: ' + topic + ' payload: ' + message); }); }); ``` -------------------------------- ### Connect to WeChat Mini Program Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Connect to an MQTT broker from a WeChat Mini Program using the 'wxs' protocol. Polyfills for AbortController and Node.js globals might be required. ```javascript import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only' // import before mqtt. import 'esbuild-plugin-polyfill-node/polyfills/navigator' const mqtt = require("mqtt"); const client = mqtt.connect("wxs://test.mosquitto.org", { timerVariant: 'native' // more info ref issue: #1797 }); ``` -------------------------------- ### MqttClient Constructor Source: https://github.com/mqttjs/mqtt.js/wiki/client Details the constructor for the MqttClient class, including parameters and default options. ```APIDOC ## MqttClient(streamBuilder, [options]) Instantiate a new instance of `MqttClient` * `streamBuilder` is a function that returns a subclass of the `Stream` class that supports the `connect` event. Typically a `net.Socket`. * `options` is the client connection options (see: [MqttConnection#connect](connection)). Defaults: * `keepalive`: `10` * `clientId`: `'mqttjs'_ + crypto.randomBytes(16).toString('hex')` * `protocolId`: `'MQIsdp'` * `protocolVersion`: `3` * `encoding`: `'utf8'` (set to `'binary'` for receiving binary payloads) ``` -------------------------------- ### Command-line MQTT Publisher Usage Source: https://github.com/mqttjs/mqtt.js/wiki/binaries Use `mqtt_pub` to send messages to an MQTT broker. Specify the port, host, topic, and payload. ```bash mqtt_pub ``` -------------------------------- ### Connect to Ali Mini Program Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Connect to an MQTT broker from an Ali Mini Program using the 'alis' protocol. This is suitable for Alipay mini programs. ```javascript const mqtt = require("mqtt"); const client = mqtt.connect("alis://test.mosquitto.org"); ``` -------------------------------- ### Command-line MQTT Subscriber Usage Source: https://github.com/mqttjs/mqtt.js/wiki/binaries Use `mqtt_sub` to subscribe to messages on an MQTT broker. Specify the port, host, and topic. ```bash mqtt_sub ``` -------------------------------- ### MqttClient#publish Source: https://github.com/mqttjs/mqtt.js/wiki/client Explains how to publish a message to a specified topic. ```APIDOC ## MqttClient#publish(topic, message, [options], [callback]) ### Description Publish a message ### Parameters * `topic` (String) - The topic to publish to. * `message` (Buffer | String) - The message payload. * `options` (Object) - Optional. Options for publishing: * `qos` (Number) - QoS level. * `retain` (Boolean) - Retain flag. * `callback` (Function) - Optional. Callback fired when the QoS handling completes. ``` -------------------------------- ### Handle 'connect' Event Source: https://github.com/mqttjs/mqtt.js/wiki/client Emitted when the client successfully connects to the MQTT broker (connack rc=0). ```javascript client.on('connect', () => { console.log('connected'); }); ``` -------------------------------- ### MQTT 3.1 Connection Options for mqtt.js Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Use these options when connecting to a broker that only supports MQTT 3.1 and not 3.1.1 compliance. ```javascript { protocolId: 'MQIsdp', protocolVersion: 3 } ``` -------------------------------- ### Run All Tests Source: https://github.com/mqttjs/mqtt.js/blob/main/DEVELOPMENT.md Execute all available tests for both browser and Node.js environments. ```sh npm test ``` -------------------------------- ### Require MQTT (CommonJS) Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Use this to import the MQTT.js library in CommonJS environments. It requires the library and creates a client instance. ```javascript const mqtt = require("mqtt") // require mqtt const client = mqtt.connect("mqtt://test.mosquitto.org") // create a client ``` -------------------------------- ### MqttConnection#connect(options) Source: https://github.com/mqttjs/mqtt.js/wiki/connection Sends an MQTT connect packet. This method is used to establish a connection with the MQTT broker. ```APIDOC ### MqttConnection#connect(options) Send an MQTT connect packet. `options` supports the following properties: * `protocolId`: Protocol ID, usually `MQIsdp`. `string` * `protocolVersion`: Protocol version, usually 3. `number` * `keepalive`: keepalive period in seconds. `number` * `clientId`: client ID. `string` * `will`: the client's will message options. `object` that supports the following properties: * `topic`: the will topic. `string` * `payload`: the will payload. `string` * `qos`: will qos level. `number` * `retain`: will retain flag. `boolean` * `clean`: the 'clean start' flag. `boolean` * `username`: username for protocol v3.1. `string` * `password`: password for protocol v3.1. `string` ``` -------------------------------- ### Import Specific MQTT.js Bundles Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Import specific bundle formats of MQTT.js if direct import is not handled by your bundler. Choose between IIFE or ESM formats, minified or not. ```javascript import * as mqtt from 'mqtt/dist/mqtt' import * as mqtt from 'mqtt/dist/mqtt.min' import mqtt from 'mqtt/dist/mqtt.esm' ``` -------------------------------- ### MqttClient#subscribe Source: https://github.com/mqttjs/mqtt.js/wiki/client Details how to subscribe to one or more topics. ```APIDOC ## MqttClient#subscribe(topic, [options], [callback]) ### Description Subscribe to a topic or topics. ### Parameters * `topic` (String | Array) - A topic string or an array of topics to subscribe to. * `options` (Object) - Optional. Options for subscribing: * `qos` (Number) - QoS subscription level. * `callback` (Function) - Optional. Callback fired on suback. Receives `(err, granted)` where `granted` is an array of `{topic, qos}`. ``` -------------------------------- ### Connect to MQTT Broker Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Connects to the specified MQTT broker URL with optional connection options. Supports various protocols like mqtt, mqtts, ws, wss, and unix sockets. Can also accept an array of server objects for failover. ```javascript const client = mqtt.connect('mqtt://localhost', { servers: [ { host: 'localhost', port: 1883 }, { host: 'test.mosquitto.org', port: 1883 } ] }); ``` -------------------------------- ### Publish: publish() Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Publishes a message to a specified topic with optional QoS, retain flag, and MQTT 5.0 properties. ```APIDOC ## mqtt.Client#publish(topic, message, [options], [callback]) ### Description Publish a message to a topic. ### Method `publish(topic, message, [options], [callback])` ### Parameters - **topic** (String) - The topic to publish to. - **message** (Buffer | String) - The message to publish. - **options** (Object) - Optional. Options to publish with: - **qos** (Number) - QoS level, default `0`. - **retain** (Boolean) - Retain flag, default `false`. - **dup** (Boolean) - Mark as duplicate flag, default `false`. - **properties** (Object) - MQTT 5.0 properties: - **payloadFormatIndicator** (boolean) - Payload is UTF-8 Encoded Character Data or not. - **messageExpiryInterval** (number) - The lifetime of the Application Message in seconds. - **topicAlias** (number) - Value used to identify the Topic instead of using the Topic Name. - **responseTopic** (string) - Topic name for a response message. - **correlationData** (binary) - Used to identify which request a Response Message is for. - **userProperties** (object) - Multiple name, value pairs. - **subscriptionIdentifier** (number) - Identifier of the subscription. - **contentType** (string) - Description of the content of the Application Message. - **cbStorePut** (function) - Fired when message is put into `outgoingStore` if QoS is `1` or `2`. - **callback** (function) - Optional. Fired when the QoS handling completes, or at the next tick if QoS 0. Receives `(err, packet)`. ### Response Example (Callback) ```javascript function (err, packet) { if (err) { console.error('Publish error:', err); } else { console.log('Publish successful:', packet); } } ``` ``` -------------------------------- ### Create Custom WebSocket Instance Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Customize WebSocket creation with custom subprotocols or headers using the `createWebsocket` callback. This allows for proxy authentication. ```javascript const createWebsocket = (url, websocketSubProtocols, options) => { const subProtocols = [ websocketSubProtocols[0], 'myCustomSubprotocolOrOAuthToken', ] return new WebSocket(url, subProtocols) } const client = await mqtt.connectAsync(, { ..., createWebsocket: createWebsocket, }); ``` -------------------------------- ### Import Connect Function (ES6) Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Use this for importing only the connect function from MQTT.js in ES6 modules. This is useful for smaller bundles. ```javascript import { connect } from "mqtt"; // import connect from mqtt let client = connect("mqtt://test.mosquitto.org"); // create a client ``` -------------------------------- ### Subscribe to a Topic Source: https://github.com/mqttjs/mqtt.js/wiki/client Subscribe to a single topic or an array of topics. Specify QoS level in options. The callback receives an error or granted QoS levels for each topic. ```javascript client.subscribe('topic', { qos: 0 }, (err, granted) => { // called on subscription }); ``` ```javascript client.subscribe(['topic1', 'topic2'], { qos: [0, 1] }, (err, granted) => { // called on subscription }); ``` -------------------------------- ### Import MQTT.js with Bundlers Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Import the MQTT.js library for use with modern JavaScript bundlers like Webpack or Vite. This is the recommended approach for most projects. ```javascript import mqtt from 'mqtt' ``` -------------------------------- ### Publish a Message Source: https://github.com/mqttjs/mqtt.js/wiki/client Publish a message to a specified topic. Options for QoS and retain flags can be provided. A callback is fired upon completion of QoS handling. ```javascript client.publish('topic', 'message', { qos: 0, retain: false }, (err) => { // called when publish is complete }); ``` -------------------------------- ### Client Events Source: https://github.com/mqttjs/mqtt.js/wiki/connection Documentation for various events emitted by the MQTT client. ```APIDOC ### Event: 'connected' `function() {}` Emitted when the socket underlying the `MqttConnection` is connected. Note: only emitted by clients created using `mqtt.createConnection()`. ``` ```APIDOC ### Event: 'connect' `function(packet) {}` Emitted when an MQTT connect packet is received by the client. `packet` is an object that may have the following properties: * `version`: the protocol version string * `versionNum`: the protocol version number * `keepalive`: the client's keepalive period * `clientId`: the client's ID * `will`: an object with the following keys: * `topic`: the client's will topic * `payload`: the will message * `retain`: will retain flag * `qos`: will qos level * `clean`: clean start flag * `username`: v3.1 username * `password`: v3.1 password ``` ```APIDOC ### Event: 'connack' `function(packet) {}` Emitted when an MQTT connack packet is received by the client. `packet` is an object that may have the following properties: * `returnCode`: the return code of the connack packet ``` ```APIDOC ### Event: 'publish' `function(packet) {}` Emitted when an MQTT publish packet is received by the client. `packet` is an object that may have the following properties: * `topic`: the topic the message is published on * `payload`: the payload of the message * `messageId`: the ID of the packet * `qos`: the QoS level to publish at ``` ```APIDOC ### Events: <'puback', 'pubrec', 'pubrel', 'pubcomp', 'unsuback'> `function(packet) {}` Emitted when an MQTT `[puback, pubrec, pubrel, pubcomp, unsuback]` packet is received by the client. `packet` is an object that may contain the property: * `messageId`: the ID of the packet ``` ```APIDOC ### Event: 'subscribe' `function(packet) {}` Emitted when an MQTT subscribe packet is received. `packet` is an object that may contain the properties: * `messageId`: the ID of the packet * `subscriptions`: an array of objects representing the subscribed topics, containing the following keys * `topic`: the topic subscribed to * `qos`: the qos level of the subscription ``` ```APIDOC ### Event: 'suback' `function(packet) {}` Emitted when an MQTT suback packet is received. `packet` is an object that may contain the properties: * `messageId`: the ID of the packet * `granted`: a vector of granted QoS levels ``` ```APIDOC ### Event: 'unsubscribe' `function(packet) {}` Emitted when an MQTT unsubscribe packet is received. `packet` is an object that may contain the properties: * `messageId`: the ID of the packet * `unsubscriptions`: a list of topics the client is unsubscribing from, of the form `[topic1, topic2, ...]` ``` ```APIDOC ### Events: <'pingreq', 'pingresp', 'disconnect'> `function(packet){}` Emitted when an MQTT `[pingreq, pingresp, disconnect]` packet is received. `packet` only includes static header information and can be ignored. ``` -------------------------------- ### MqttConnection#publish([options]) Source: https://github.com/mqttjs/mqtt.js/wiki/connection Sends an MQTT publish packet to a specified topic with optional payload and QoS settings. ```APIDOC ### MqttConnection#publish([options]) Send an MQTT publish packet. `options` supports the following properties: * `topic`: the topic to publish to. `string` * `payload`: the payload to publish, defaults to an empty buffer. `string` or `buffer` * `qos`: the quality of service level to publish on. `number` * `messageId`: the message ID of the packet, required if qos > 0. `number` * `retain`: retain flag. `boolean` ``` -------------------------------- ### MqttSecureServer Creation Source: https://github.com/mqttjs/mqtt.js/wiki/server Instantiate a new TLS-secured MQTT server using the mqtt.createSecureServer factory method. This method returns an instance of MqttSecureServer. ```APIDOC ## MqttSecureServer Creation ### Description Instantiates a new TLS-secured MQTT server. It is recommended to use the factory method `mqtt.createSecureServer`. ### Method `mqtt.createSecureServer(keyPath, certPath, [listener])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript var mqtt = require('mqtt'); var server = mqtt.createSecureServer( __dirname + 'private-key.pem', __dirname + 'cert.pem', function(client) { client.on('connect', function(packet) { client.connack({returnCode: 0}); }); client.on('publish', function(packet) { // Handle publish }); client.on('subscribe', function(packet) { client.suback([0]); }); client.on('pingreq', function(packet) { client.pingresp(); }); client.on('disconnect', function(packet) { // Handle disconnect }); }); ``` ### Response #### Success Response (200) N/A (Server creation does not return a response in the traditional sense, but emits events). #### Response Example N/A ``` -------------------------------- ### Pipe MqttConnection with a Stream Source: https://github.com/mqttjs/mqtt.js/wiki/connection Shows how to pipe an existing stream (e.g., from a websocket or named pipe) into an MqttConnection. This allows the MqttConnection to process incoming MQTT data from the stream and publish messages to it. ```javascript // stream is from somewhere, it might be a named pipe, a websocket, or whatever other transport var mqtt = require("mqtt"); var conn = stream.pipe(new mqtt.MqttConnection()); conn.publish("hello", "world"); ``` -------------------------------- ### Subscribe: subscribe() Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Subscribes to one or more topics with optional QoS and MQTT 5.0 options. ```APIDOC ## mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback]) ### Description Subscribe to a topic or topics. ### Method `subscribe(topic, [options], [callback])` ### Parameters - **topic** (String | Array | Object) - A `String` topic, an `Array` of topics, or an object where keys are topic names and values are QoS levels (e.g., `{'test1': {qos: 0}, 'test2': {qos: 1}}`). MQTT wildcard characters (`+`, `#`) are supported. - **options** (Object) - Optional. Options to subscribe with: - **qos** (Number) - QoS subscription level, default `0`. - **nl** (Boolean) - No Local MQTT 5.0 flag. - **rap** (Boolean) - Retain as Published MQTT 5.0 flag. - **rh** (Number) - Retain Handling MQTT 5.0. - **properties** (Object) - MQTT 5.0 properties: - **subscriptionIdentifier** (number) - Identifier of the subscription. - **userProperties** (object) - Multiple name, value pairs. - **callback** (function) - Optional. Fired on suback. Receives `(err, granted)` where `granted` is an array of `{topic, qos}`. ### Response Example (Callback) ```javascript function (err, granted) { if (err) { console.error('Subscription error:', err); } else { console.log('Subscription granted:', granted); } } ``` ``` -------------------------------- ### MqttClient#unsubscribe Source: https://github.com/mqttjs/mqtt.js/wiki/client Explains how to unsubscribe from topics. ```APIDOC ## MqttClient#unsubscribe(topic, [callback]) ### Description Unsubscribe from a topic or topics. ### Parameters * `topic` (String | Array) - A topic string or an array of topics to unsubscribe from. * `callback` (Function) - Optional. Callback fired on unsuback. ``` -------------------------------- ### Browser Considerations Source: https://github.com/mqttjs/mqtt.js/blob/main/README.md Information specific to using mqtt.js in a browser environment, including protocol limitations and error handling differences. ```APIDOC ## Browser > [!IMPORTANT] > The only protocol supported in browsers is MQTT over WebSockets, so you must use `ws://` or `wss://` protocols. While the [ws](https://www.npmjs.com/package/ws) module is used in NodeJS, [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) is used in browsers. This is totally transparent to users except for the following: - The `wsOption` is not supported in browsers. - Browsers doesn't allow to catch many WebSocket errors for [security reasons](https://stackoverflow.com/a/31003057) as: > Access to this information could allow a malicious Web page to gain information about your network, so they require browsers report all connection-time errors in an indistinguishable way. So listening for `client.on('error')` may not catch all the errors you would get in NodeJS env. ``` -------------------------------- ### MqttConnection#suback(options) Source: https://github.com/mqttjs/mqtt.js/wiki/connection Sends an MQTT suback packet to acknowledge a subscription request. ```APIDOC ### client#suback(options) Send an MQTT suback packet. `options` supports the following properties: * `granted`: a vector of granted QoS levels, of the form `[0, 1, 2]` * `messageId`: the ID of the packet ``` -------------------------------- ### MqttClient#end Source: https://github.com/mqttjs/mqtt.js/wiki/client Describes how to close the client connection. ```APIDOC ## MqttClient#end() ### Description Close connection - send a disconnect packet and close the underlying stream. ``` -------------------------------- ### Run Specific Node.js Test Source: https://github.com/mqttjs/mqtt.js/blob/main/DEVELOPMENT.md Execute a single Node.js test file using esbuild-register for transpilation. ```sh node -r esbuild-register --test test/keepaliveManager.ts ``` -------------------------------- ### MqttSecureServer Events Source: https://github.com/mqttjs/mqtt.js/wiki/server Details the events emitted by an MqttSecureServer instance, which are similar to MqttServer. ```APIDOC ## MqttSecureServer Events ### Description MqttSecureServer is a subclass of `tls.Server` and inherits its events and methods. It also provides specific events. ### Event: 'client' #### Description Emitted when a new TLS connection is received. #### Parameters * `client` (MqttSecureServerClient) - An instance of `MqttSecureServerClient`, which wraps an `MqttConnection`. ### Method `MqttSecureServer(keyPath, certPath, [listener])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript server.on('client', function(client) { console.log('New secure client connected'); // Handle client connection events here }); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### MqttServer Events Source: https://github.com/mqttjs/mqtt.js/wiki/server Details the events emitted by an MqttServer instance, particularly the 'client' event. ```APIDOC ## MqttServer Events ### Description MqttServer is a subclass of `net.Server` and inherits its events and methods. It also provides specific events. ### Event: 'client' #### Description Emitted when a new TCP connection is received. #### Parameters * `client` (MqttServerClient) - An instance of `MqttServerClient`, which wraps an `MqttConnection`. ### Method `MqttServer([listener])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript server.on('client', function(client) { console.log('New client connected'); // Handle client connection events here }); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### MqttConnection Class Overview Source: https://github.com/mqttjs/mqtt.js/wiki/connection The MqttConnection class represents a raw MQTT connection. It is recommended to use MqttClient for client-side operations due to the boilerplate required by MqttConnection. MqttServerClient is a subclass of MqttConnection. ```APIDOC ## MqttConnection Invalid arguments to the methods below will cause MqttConnection to emit `error` events, which, if unhandled, will cause the program to terminate. Starting from v0.3.0, an MqttConnection is _just_ a [Writable](http://nodejs.org/api/stream.html#stream_class_stream_writable) stream, so it can be piped. `MqttConnection#stream` exposes the underlining `stream` object, so you can retrieve all the TCP-related options, as exposed by [Socket](http://nodejs.org/api/net.html#net_class_net_socket). For all events below `packet` will also contain all of the information contained in the MQTT static header. This includes `cmd`, `dup`, `qos` and `retain` even when they do not apply to the packet. It will also contain the `length` of the packet. ```