37.2 kBMarkdownView Raw
1# ![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
2
3![Github Test Status](https://github.com/mqttjs/MQTT.js/workflows/MQTT.js%20CI/badge.svg) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js)
4
5[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/mqttjs/MQTT.js/graphs/commit-activity)
6[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/mqttjs/MQTT.js/pulls)
7
8[![node](https://img.shields.io/node/v/mqtt.svg) ![npm](https://img.shields.io/npm/v/mqtt.svg?logo=npm) ![NPM Downloads](https://img.shields.io/npm/dm/mqtt.svg)](https://www.npmjs.com/package/mqtt)
9
10MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
11in JavaScript for node.js and the browser.
12
13## Table of Contents
14
15- [Upgrade notes](#notes)
16- [Installation](#install)
17- [Example](#example)
18- [React Native](#react-native)
19- [Import Styles](#example)
20- [Command Line Tools](#cli)
21- [API](#api)
22- [Browser](#browser)
23- [About QoS](#qos)
24- [TypeScript](#typescript)
25- [Weapp and Ali support](#weapp-alipay)
26- [Contributing](#contributing)
27- [Sponsor](#sponsor)
28- [License](#license)
29
30MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.
31
32[![JavaScript Style
33Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
34
35<a name="notes"></a>
36
37## Important notes for existing users
38
39**v5.0.0** (07/2023)
40
41- Removes support for all end of life node versions (v12 and v14), and now supports node v18 and v20.
42- Completely rewritten in Typescript 🚀.
43- When creating `MqttClient` instance `new` is now required.
44
45**v4.0.0** (Released 04/2020) removes support for all end of life node versions, and now supports node v12 and v14. It also adds improvements to
46debug logging, along with some feature additions.
47
48As a **breaking change**, by default a error handler is built into the MQTT.js client, so if any
49errors are emitted and the user has not created an event handler on the client for errors, the client will
50not break as a result of unhandled errors. Additionally, typical TLS errors like `ECONNREFUSED`, `ECONNRESET` have been
51added to a list of TLS errors that will be emitted from the MQTT.js client, and so can be handled as connection errors.
52
53**v3.0.0** adds support for MQTT 5, support for node v10.x, and many fixes to improve reliability.
54
55**Note:** MQTT v5 support is experimental as it has not been implemented by brokers yet.
56
57**v2.0.0** removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
58packets. It also removes all the deprecated functionality in v1.0.0,
59mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0,
60subscriptions are restored upon reconnection if `clean: true`.
61v1.x.x is now in _LTS_, and it will keep being supported as long as
62there are v0.8, v0.10 and v0.12 users.
63
64As a **breaking change**, the `encoding` option in the old client is
65removed, and now everything is UTF-8 with the exception of the
66`password` in the CONNECT message and `payload` in the PUBLISH message,
67which are `Buffer`.
68
69Another **breaking change** is that MQTT.js now defaults to MQTT v3.1.1,
70so to support old brokers, please read the [client options doc](#client).
71
72**v1.0.0** improves the overall architecture of the project, which is now
73split into three components: MQTT.js keeps the Client,
74[mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
75Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
76includes the protocol parser and generator. The new Client improves
77performance by a 30% factor, embeds Websocket support
78([MOWS](http://npm.im/mows) is now deprecated), and it has a better
79support for QoS 1 and 2. The previous API is still supported but
80deprecated, as such, it is not documented in this README.
81
82<a name="install"></a>
83
84## Installation
85
86```sh
87npm install mqtt --save
88```
89
90<a name="example"></a>
91
92## Example
93
94For the sake of simplicity, let's put the subscriber and the publisher in the same file:
95
96```js
97const mqtt = require("mqtt");
98const client = mqtt.connect("mqtt://test.mosquitto.org");
99
100client.on("connect", () => {
101 client.subscribe("presence", (err) => {
102 if (!err) {
103 client.publish("presence", "Hello mqtt");
104 }
105 });
106});
107
108client.on("message", (topic, message) => {
109 // message is Buffer
110 console.log(message.toString());
111 client.end();
112});
113```
114
115output:
116
117```sh
118Hello mqtt
119```
120
121<a name="example-react-native"></a>
122
123### React Native
124
125MQTT.js can be used in React Native applications. To use it, see the [React Native example](https://github.com/MaximoLiberata/react-native-mqtt.js-example)
126
127If you want to run your own MQTT broker, you can use
128[Mosquitto](http://mosquitto.org) or
129[Aedes-cli](https://github.com/moscajs/aedes-cli), and launch it.
130
131You can also use a test instance: test.mosquitto.org.
132
133If you do not want to install a separate broker, you can try using the
134[Aedes](https://github.com/moscajs/aedes).
135
136<a name="import_styles"></a>
137
138## Import styles
139
140### CommonJS (Require)
141
142```js
143const mqtt = require("mqtt") // require mqtt
144const client = mqtt.connect("mqtt://test.mosquitto.org") // create a client
145```
146
147### ES6 Modules (Import)
148
149#### Default import
150
151```js
152import mqtt from "mqtt"; // import namespace "mqtt"
153let client = mqtt.connect("mqtt://test.mosquitto.org"); // create a client
154```
155
156#### Importing individual components
157
158```js
159import { connect } from "mqtt"; // import connect from mqtt
160let client = connect("mqtt://test.mosquitto.org"); // create a client
161```
162
163<a name="cli"></a>
164
165## Command Line Tools
166
167MQTT.js bundles a command to interact with a broker.
168In order to have it available on your path, you should install MQTT.js
169globally:
170
171```sh
172npm install mqtt -g
173```
174
175Then, on one terminal
176
177```sh
178mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
179```
180
181On another
182
183```sh
184mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
185```
186
187See `mqtt help <command>` for the command help.
188
189<a name="debug"></a>
190
191## Debug Logs
192
193MQTT.js uses the [debug](https://www.npmjs.com/package/debug#cmd) package for debugging purposes. To enable debug logs, add the following environment variable on runtime :
194
195```ps
196# (example using PowerShell, the VS Code default)
197$env:DEBUG='mqttjs*'
198```
199
200<a name="reconnecting"></a>
201
202## About Reconnection
203
204An important part of any websocket connection is what to do when a connection
205drops off and the client needs to reconnect. MQTT has built-in reconnection
206support that can be configured to behave in ways that suit the application.
207
208#### Refresh Authentication Options / Signed Urls with `transformWsUrl` (Websocket Only)
209
210When an mqtt connection drops and needs to reconnect, it's common to require
211that any authentication associated with the connection is kept current with
212the underlying auth mechanism. For instance some applications may pass an auth
213token with connection options on the initial connection, while other cloud
214services may require a url be signed with each connection.
215
216By the time the reconnect happens in the application lifecycle, the original
217auth data may have expired.
218
219To address this we can use a hook called `transformWsUrl` to manipulate
220either of the connection url or the client options at the time of a reconnect.
221
222Example (update clientId & username on each reconnect):
223
224```js
225 const transformWsUrl = (url, options, client) => {
226 client.options.username = `token=${this.get_current_auth_token()}`;
227 client.options.clientId = `${this.get_updated_clientId()}`;
228
229 return `${this.get_signed_cloud_url(url)}`;
230 }
231
232 const connection = await mqtt.connectAsync(<wss url>, {
233 ...,
234 transformWsUrl: transformUrl,
235 });
236
237```
238
239Now every time a new WebSocket connection is opened (hopefully not too often),
240we will get a fresh signed url or fresh auth token data.
241
242Note: Currently this hook does _not_ support promises, meaning that in order to
243use the latest auth token, you must have some outside mechanism running that
244handles application-level authentication refreshing so that the websocket
245connection can simply grab the latest valid token or signed url.
246
247#### Customize Websockets with `createWebsocket` (Websocket Only)
248
249When you need to add a custom websocket subprotocol or header to open a connection
250through a proxy with custom authentication this callback allows you to create your own
251instance of a websocket which will be used in the mqtt client.
252
253```js
254 const createWebsocket = (url, websocketSubProtocols, options) => {
255 const subProtocols = [
256 websocketSubProtocols[0],
257 'myCustomSubprotocolOrOAuthToken',
258 ]
259 return new WebSocket(url, subProtocols)
260 }
261
262 const client = await mqtt.connectAsync(<wss url>, {
263 ...,
264 createWebsocket: createWebsocket,
265 });
266```
267
268#### Enabling Reconnection with `reconnectPeriod` option
269
270To ensure that the mqtt client automatically tries to reconnect when the
271connection is dropped, you must set the client option `reconnectPeriod` to a
272value greater than 0. A value of 0 will disable reconnection and then terminate
273the final connection when it drops.
274
275The default value is 1000 ms which means it will try to reconnect 1 second
276after losing the connection.
277
278Note that this will only enable reconnects after either a connection timeout, or
279after a successful connection. It will _not_ (by default) enable retrying
280connections that are actively denied with a CONNACK error by the server.
281
282To also enable automatic reconnects for CONNACK errors, set
283`reconnectOnConnackError: true`.
284
285<a name="topicalias"></a>
286
287## About Topic Alias Management
288
289### Enabling automatic Topic Alias using
290
291If the client sets the option `autoUseTopicAlias:true` then MQTT.js uses existing topic alias automatically.
292
293example scenario:
294
295```bash
2961. PUBLISH topic:'t1', ta:1 (register)
2972. PUBLISH topic:'t1' -> topic:'', ta:1 (auto use existing map entry)
2983. PUBLISH topic:'t2', ta:1 (register overwrite)
2994. PUBLISH topic:'t2' -> topic:'', ta:1 (auto use existing map entry based on the receent map)
3005. PUBLISH topic:'t1' (t1 is no longer mapped to ta:1)
301```
302
303User doesn't need to manage which topic is mapped to which topic alias.
304If the user want to register topic alias, then publish topic with topic alias.
305If the user want to use topic alias, then publish topic without topic alias. If there is a mapped topic alias then added it as a property and update the topic to empty string.
306
307### Enabling automatic Topic Alias assign
308
309If the client sets the option `autoAssignTopicAlias:true` then MQTT.js uses existing topic alias automatically.
310If no topic alias exists, then assign a new vacant topic alias automatically. If topic alias is fully used, then LRU(Least Recently Used) topic-alias entry is overwritten.
311
312example scenario:
313
314```bash
315The broker returns CONNACK (TopicAliasMaximum:3)
3161. PUBLISH topic:'t1' -> 't1', ta:1 (auto assign t1:1 and register)
3172. PUBLISH topic:'t1' -> '' , ta:1 (auto use existing map entry)
3183. PUBLISH topic:'t2' -> 't2', ta:2 (auto assign t1:2 and register. 2 was vacant)
3194. PUBLISH topic:'t3' -> 't3', ta:3 (auto assign t1:3 and register. 3 was vacant)
3205. PUBLISH topic:'t4' -> 't4', ta:1 (LRU entry is overwritten)
321```
322
323Also user can manually register topic-alias pair using PUBLISH topic:'some', ta:X. It works well with automatic topic alias assign.
324
325<a name="api"></a>
326
327## API
328
329- [`mqtt.connect()`](#connect)
330- [`mqtt.connectAsync()`](#connect-async)
331- [`mqtt.Client()`](#client)
332- [`mqtt.Client#connect()`](#client-connect)
333- [`mqtt.Client#publish()`](#publish)
334- [`mqtt.Client#publishAsync()`](#publish-async)
335- [`mqtt.Client#subscribe()`](#subscribe)
336- [`mqtt.Client#subscribeAsync()`](#subscribe-async)
337- [`mqtt.Client#unsubscribe()`](#unsubscribe)
338- [`mqtt.Client#unsubscribeAsync()`](#unsubscribe-async)
339- [`mqtt.Client#end()`](#end)
340- [`mqtt.Client#endAsync()`](#end-async)
341- [`mqtt.Client#removeOutgoingMessage()`](#removeOutgoingMessage)
342- [`mqtt.Client#reconnect()`](#reconnect)
343- [`mqtt.Client#handleMessage()`](#handleMessage)
344- [`mqtt.Client#connected`](#connected)
345- [`mqtt.Client#reconnecting`](#reconnecting)
346- [`mqtt.Client#getLastMessageId()`](#getLastMessageId)
347- [`mqtt.Store()`](#store)
348- [`mqtt.Store#put()`](#put)
349- [`mqtt.Store#del()`](#del)
350- [`mqtt.Store#createStream()`](#createStream)
351- [`mqtt.Store#close()`](#close)
352
353---
354
355<a name="connect"></a>
356
357### mqtt.connect([url], options)
358
359Connects to the broker specified by the given url and options and
360returns a [Client](#client).
361
362The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
363'tls', 'ws', 'wss', 'wxs', 'alis'. If you are trying to connect to a unix socket just append the `+unix` suffix to the protocol (ex: `mqtt+unix`). This will set the `unixSocket` property automatically.
364
365The URL can also be an object as returned by
366[`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
367in that case the two objects are merged, i.e. you can pass a single
368object with both the URL and the connect options.
369
370You can also specify a `servers` options with content: `[{ host:
371'localhost', port: 1883 }, ... ]`, in that case that array is iterated
372at every connect.
373
374For all MQTT-related options, see the [Client](#client)
375constructor.
376
377<a name="connect-async"></a>
378
379### connectAsync([url], options)
380
381Asynchronous wrapper around the [`connect`](#connect) function.
382
383Returns a `Promise` that resolves to a `mqtt.Client` instance when the client
384fires a `'connect'` or `'end'` event, or rejects with an error if the `'error'`
385is fired.
386
387Note that the `manualConnect` option will cause the promise returned by this
388function to never resolve or reject as the underlying client never fires any
389events.
390
391---
392
393<a name="client"></a>
394
395### mqtt.Client(streamBuilder, options)
396
397The `Client` class wraps a client connection to an
398MQTT broker over an arbitrary transport method (TCP, TLS,
399WebSocket, ecc).
400`Client` is an [EventEmitter](https://nodejs.org/en/learn/asynchronous-work/the-nodejs-event-emitter) that has it's own [events](#events)
401
402`Client` automatically handles the following:
403
404- Regular server pings
405- QoS flow
406- Automatic reconnections
407- Start publishing before being connected
408
409The arguments are:
410
411- `streamBuilder` is a function that returns a subclass of the `Stream` class that supports
412 the `connect` event. Typically a `net.Socket`.
413- `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults:
414 - `wsOptions`: is the WebSocket connection options. Default is `{}`.
415 It's specific for WebSockets. For possible options have a look at: <https://github.com/websockets/ws/blob/master/doc/ws.md>.
416 - `keepalive`: `60` seconds, set to `0` to disable
417 - `reschedulePings`: reschedule ping messages after sending packets (default `true`)
418 - `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
419 - `protocolId`: `'MQTT'`
420 - `protocolVersion`: `4`
421 - `clean`: `true`, set to false to receive QoS 1 and 2 messages while
422 offline
423 - `reconnectPeriod`: `1000` milliseconds, interval between two
424 reconnections. Disable auto reconnect by setting to `0`.
425 - `reconnectOnConnackError`: `false`, whether to also reconnect if a CONNACK
426 is received with an error.
427 - `connectTimeout`: `30 * 1000` milliseconds, time to wait before a
428 CONNACK is received
429 - `username`: the username required by your broker, if any
430 - `password`: the password required by your broker, if any
431 - `incomingStore`: a [Store](#store) for the incoming packets
432 - `outgoingStore`: a [Store](#store) for the outgoing packets
433 - `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`)
434 - `customHandleAcks`: MQTT 5 feature of custom handling puback and pubrec packets. Its callback:
435
436 ```js
437 customHandleAcks: function(topic, message, packet, done) {/*some logic with calling done(error, reasonCode)*/}
438 ```
439
440 - `autoUseTopicAlias`: enabling automatic Topic Alias using functionality
441 - `autoAssignTopicAlias`: enabling automatic Topic Alias assign functionality
442 - `properties`: properties MQTT 5.0.
443 `object` that supports the following properties:
444 - `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
445 - `receiveMaximum`: representing the Receive Maximum value `number`,
446 - `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`,
447 - `topicAliasMaximum`: representing the Topic Alias Maximum value indicates the highest value that the Client will accept as a Topic Alias sent by the Server `number`,
448 - `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`,
449 - `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`,
450 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
451 - `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
452 - `authenticationData`: Binary Data containing authentication data `binary`
453 - `authPacket`: settings for auth packet `object`
454 - `will`: a message that will sent by the broker automatically when
455 the client disconnect badly. The format is:
456 - `topic`: the topic to publish
457 - `payload`: the message to publish
458 - `qos`: the QoS
459 - `retain`: the retain flag
460 - `properties`: properties of will by MQTT 5.0:
461 - `willDelayInterval`: representing the Will Delay Interval in seconds `number`,
462 - `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`,
463 - `messageExpiryInterval`: value is the lifetime of the Will Message in seconds and is sent as the Publication Expiry Interval when the Server publishes the Will Message `number`,
464 - `contentType`: describing the content of the Will Message `string`,
465 - `responseTopic`: String which is used as the Topic Name for a response message `string`,
466 - `correlationData`: The Correlation Data is used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
467 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
468 - `transformWsUrl` : optional `(url, options, client) => url` function
469 For ws/wss protocols only. Can be used to implement signing
470 urls which upon reconnect can have become expired.
471 - `createWebsocket` : optional `url, websocketSubProtocols, options) => Websocket` function
472 For ws/wss protocols only. Can be used to implement a custom websocket subprotocol or implementation.
473 - `resubscribe` : if connection is broken and reconnects,
474 subscribed topics are automatically subscribed again (default `true`)
475 - `messageIdProvider`: custom messageId provider. when `new UniqueMessageIdProvider()` is set, then non conflict messageId is provided.
476 - `log`: custom log function. Default uses [debug](https://www.npmjs.com/package/debug) package.
477 - `manualConnect`: prevents the constructor to call `connect`. In this case after the `mqtt.connect` is called you should call `client.connect` manually.
478 - `timerVariant`: defaults to `auto`, which tries to determine which timer is most appropriate for you 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:
479 ```js
480 timerVariant: {
481 set: (func, timer) => setInterval(func, timer),
482 clear: (id) => clearInterval(id)
483 }
484 ```
485 - `forceNativeWebSocket`: 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. It is important to note that if set to true for the first client created, then all the clients will use native WebSocket. And conversely, if not set or set to false, all will use the detection result.
486 - `unixSocket`: if you want to connect to a unix socket, set this to true
487
488In 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). If using a **self-signed certificate**, set `rejectUnauthorized: false`. However, be cautious as this exposes you to potential man in the middle attacks and isn't recommended for production.
489
490For those supporting multiple TLS protocols on a single port, like MQTTS and MQTT over WSS, utilize the `ALPNProtocols` option. This 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.
491
492If you are connecting to a broker that supports only MQTT 3.1 (not
4933.1.1 compliant), you should pass these additional options:
494
495```js
496{
497 protocolId: 'MQIsdp',
498 protocolVersion: 3
499}
500```
501
502This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
503version 1.3 and 1.4 works fine without those.
504
505<a name="events"></a>
506
507#### Event `'connect'`
508
509`function (connack) {}`
510
511Emitted on successful (re)connection (i.e. connack rc=0).
512
513- `connack` received connack packet. When `clean` connection option is `false` and server has a previous session
514 for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case,
515 you may rely on stored session and prefer not to send subscribe commands for the client.
516
517#### Event `'reconnect'`
518
519`function () {}`
520
521Emitted when a reconnect starts.
522
523#### Event `'close'`
524
525`function () {}`
526
527Emitted after a disconnection.
528
529#### Event `'disconnect'`
530
531`function (packet) {}`
532
533Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
534
535#### Event `'offline'`
536
537`function () {}`
538
539Emitted when the client goes offline.
540
541#### Event `'error'`
542
543`function (error) {}`
544
545Emitted when the client cannot connect (i.e. connack rc != 0) or when a
546parsing error occurs.
547
548The following TLS errors will be emitted as an `error` event:
549
550- `ECONNREFUSED`
551- `ECONNRESET`
552- `EADDRINUSE`
553- `ENOTFOUND`
554
555#### Event `'end'`
556
557`function () {}`
558
559Emitted when [`mqtt.Client#end()`](#end) is called.
560If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
561callback returns.
562
563#### Event `'message'`
564
565`function (topic, message, packet) {}`
566
567Emitted when the client receives a publish packet
568
569- `topic` topic of the received packet
570- `message` payload of the received packet
571- `packet` received packet, as defined in
572 [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)
573
574#### Event `'packetsend'`
575
576`function (packet) {}`
577
578Emitted when the client sends any packet. This includes .published() packets
579as well as packets used by MQTT for managing subscriptions and connections
580
581- `packet` received packet, as defined in
582 [mqtt-packet](https://github.com/mcollina/mqtt-packet)
583
584#### Event `'packetreceive'`
585
586`function (packet) {}`
587
588Emitted when the client receives any packet. This includes packets from
589subscribed topics as well as packets used by MQTT for managing subscriptions
590and connections
591
592- `packet` received packet, as defined in
593 [mqtt-packet](https://github.com/mcollina/mqtt-packet)
594
595---
596
597<a name="client-connect"></a>
598
599### mqtt.Client#connect()
600
601By default client connects when constructor is called. To prevent this you can set `manualConnect` option to `true` and call `client.connect()` manually.
602
603<a name="publish"></a>
604
605### mqtt.Client#publish(topic, message, [options], [callback])
606
607Publish a message to a topic
608
609- `topic` is the topic to publish to, `String`
610- `message` is the message to publish, `Buffer` or `String`
611- `options` is the options to publish with, including:
612 - `qos` QoS level, `Number`, default `0`
613 - `retain` retain flag, `Boolean`, default `false`
614 - `dup` mark as duplicate flag, `Boolean`, default `false`
615 - `properties`: MQTT 5.0 properties `object`
616 - `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`,
617 - `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`,
618 - `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`,
619 - `responseTopic`: String which is used as the Topic Name for a response message `string`,
620 - `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
621 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
622 - `subscriptionIdentifier`: representing the identifier of the subscription `number`,
623 - `contentType`: String describing the content of the Application Message `string`
624 - `cbStorePut` - `function ()`, fired when message is put into `outgoingStore` if QoS is `1` or `2`.
625- `callback` - `function (err, packet)`, fired when the QoS handling completes,
626 or at the next tick if QoS 0. An error occurs if client is disconnecting.
627
628<a name="publish-async"></a>
629
630### mqtt.Client#publishAsync(topic, message, [options])
631
632Async [`publish`](#publish). Returns a `Promise<Packet | undefined>`.
633
634A packet is anything that has a `messageId` property.
635---
636
637<a name="subscribe"></a>
638
639### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])
640
641Subscribe to a topic or topics
642
643- `topic` is a `String` topic to subscribe to or an `Array` of
644 topics to subscribe to. It can also be an object, it has as object
645 keys the topic name and as value the QoS, like `{'test1': {qos: 0}, 'test2': {qos: 1}}`.
646 MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level)
647- `options` is the options to subscribe with, including:
648 - `qos` QoS subscription level, default 0
649 - `nl` No Local MQTT 5.0 flag (If the value is true, Application Messages MUST NOT be forwarded to a connection with a ClientID equal to the ClientID of the publishing connection)
650 - `rap` Retain as Published MQTT 5.0 flag (If true, Application Messages forwarded using this subscription keep the RETAIN flag they were published with. If false, Application Messages forwarded using this subscription have the RETAIN flag set to 0.)
651 - `rh` Retain Handling MQTT 5.0 (This option specifies whether retained messages are sent when the subscription is established.)
652 - `properties`: `object`
653 - `subscriptionIdentifier`: representing the identifier of the subscription `number`,
654 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
655- `callback` - `function (err, granted)`
656 callback fired on suback where:
657 - `err` a subscription error or an error that occurs when client is disconnecting
658 - `granted` is an array of `{topic, qos}` where:
659 - `topic` is a subscribed to topic
660 - `qos` is the granted QoS level on it
661
662<a name="subscribe-async"></a>
663
664### mqtt.Client#subscribeAsync(topic/topic array/topic object, [options])
665
666Async [`subscribe`](#subscribe). Returns a `Promise<ISubscriptionGrant[]>`.
667
668---
669
670<a name="unsubscribe"></a>
671
672### mqtt.Client#unsubscribe(topic/topic array, [options], [callback])
673
674Unsubscribe from a topic or topics
675
676- `topic` is a `String` topic or an array of topics to unsubscribe from
677- `options`: options of unsubscribe.
678 - `properties`: `object`
679 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
680- `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.
681
682<a name="unsubscribe-async"></a>
683
684### mqtt.Client#unsubscribeAsync(topic/topic array, [options])
685
686Async [`unsubscribe`](#unsubscribe). Returns a `Promise<void>`.
687
688---
689
690<a name="end"></a>
691
692### mqtt.Client#end([force], [options], [callback])
693
694Close the client, accepts the following options:
695
696- `force`: passing it to true will close the client right away, without
697 waiting for the in-flight messages to be acked. This parameter is
698 optional.
699- `options`: options of disconnect.
700 - `reasonCode`: Disconnect Reason Code `number`
701 - `properties`: `object`
702 - `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
703 - `reasonString`: representing the reason for the disconnect `string`,
704 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
705 - `serverReference`: String which can be used by the Client to identify another Server to use `string`
706- `callback`: will be called when the client is closed. This parameter is
707 optional.
708
709<a name="end-async"></a>
710
711### mqtt.Client#endAsync([force], [options])
712
713Async [`end`](#end). Returns a `Promise<void>`.
714
715---
716
717<a name="removeOutgoingMessage"></a>
718
719### mqtt.Client#removeOutgoingMessage(mId)
720
721Remove a message from the outgoingStore.
722The outgoing callback will be called with Error('Message removed') if the message is removed.
723
724After this function is called, the messageId is released and becomes reusable.
725
726- `mId`: The messageId of the message in the outgoingStore.
727
728---
729
730<a name="reconnect"></a>
731
732### mqtt.Client#reconnect()
733
734Connect again using the same options as connect()
735
736---
737
738<a name="handleMessage"></a>
739
740### mqtt.Client#handleMessage(packet, callback)
741
742Handle messages with backpressure support, one at a time.
743Override at will, but **always call `callback`**, or the client
744will hang.
745
746---
747
748<a name="connected"></a>
749
750### mqtt.Client#connected
751
752Boolean : set to `true` if the client is connected. `false` otherwise.
753
754---
755
756<a name="getLastMessageId"></a>
757
758### mqtt.Client#getLastMessageId()
759
760Number : get last message id. This is for sent messages only.
761
762---
763
764<a name="reconnecting"></a>
765
766### mqtt.Client#reconnecting
767
768Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.
769
770---
771
772<a name="store"></a>
773
774### mqtt.Store(options)
775
776In-memory implementation of the message store.
777
778- `options` is the store options:
779 - `clean`: `true`, clean inflight messages when close is called (default `true`)
780
781Other implementations of `mqtt.Store`:
782
783- [mqtt-jsonl-store](https://github.com/robertsLando/mqtt-jsonl-store) which uses
784 [jsonl-db](https://github.com/AlCalzone/jsonl-db) to store inflight data, it works only on Node.
785- [mqtt-level-store](http://npm.im/mqtt-level-store) which uses
786 [Level-browserify](http://npm.im/level-browserify) to store the inflight
787 data, making it usable both in Node and the Browser.
788- [mqtt-nedb-store](https://github.com/behrad/mqtt-nedb-store) which
789 uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight
790 data.
791- [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses
792 [localForage](http://npm.im/localforage) to store the inflight
793 data, making it usable in the Browser without browserify.
794
795---
796
797<a name="put"></a>
798
799### mqtt.Store#put(packet, callback)
800
801Adds a packet to the store, a packet is
802anything that has a `messageId` property.
803The callback is called when the packet has been stored.
804
805---
806
807<a name="createStream"></a>
808
809### mqtt.Store#createStream()
810
811Creates a stream with all the packets in the store.
812
813---
814
815<a name="del"></a>
816
817### mqtt.Store#del(packet, cb)
818
819Removes a packet from the store, a packet is
820anything that has a `messageId` property.
821The callback is called when the packet has been removed.
822
823---
824
825<a name="close"></a>
826
827### mqtt.Store#close(cb)
828
829Closes the Store.
830
831<a name="browser"></a>
832<a name="webpack"></a>
833<a name="vite"></a>
834
835## Browser
836
837> [!IMPORTANT]
838> The only protocol supported in browsers is MQTT over WebSockets, so you must use `ws://` or `wss://` protocols.
839
840While 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:
841
842- The `wsOption` is not supported in browsers.
843- Browsers doesn't allow to catch many WebSocket errors for [security reasons](https://stackoverflow.com/a/31003057) as:
844
845 > 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.
846
847 So listening for `client.on('error')` may not catch all the errors you would get in NodeJS env.
848
849### Bundle
850
851MQTT.js is bundled using [esbuild](https://esbuild.github.io/). It is tested working with all bundlers like Webpack, Vite and React.
852
853You can find all mqtt bundles versions in `dist` folder:
854
855- `mqtt.js` - iife format, not minified
856- `mqtt.min.js` - iife format, minified
857- `mqtt.esm.js` - esm format minified
858
859Starting from MQTT.js > 5.2.0 you can import mqtt in your code like this:
860
861```js
862import mqtt from 'mqtt'
863```
864
865This will be automatically handled by your bundler.
866
867Otherwise you can choose to use a specific bundle like:
868
869```js
870import * as mqtt from 'mqtt/dist/mqtt'
871import * as mqtt from 'mqtt/dist/mqtt.min'
872import mqtt from 'mqtt/dist/mqtt.esm'
873```
874
875<a name="cdn"></a>
876
877### Via CDN
878
879The MQTT.js bundle is available through <http://unpkg.com>, specifically
880at <https://unpkg.com/mqtt/dist/mqtt.min.js>.
881See <http://unpkg.com> for the full documentation on version ranges.
882
883<a name="qos"></a>
884
885## About QoS
886
887Here is how QoS works:
888
889- QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received.
890- QoS 1 : received **at least once** : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it _will_ be received, but there can be duplicates.
891- QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates.
892
893About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
894
895<a name="typescript"></a>
896
897## Usage with TypeScript
898
899Starting from v5 this project is written in TypeScript and the type definitions are included in the package.
900
901Example:
902
903```ts
904import { connect } from "mqtt"
905const client = connect('mqtt://test.mosquitto.org')
906```
907
908<a name="weapp-alipay"></a>
909
910## WeChat and Ali Mini Program support
911
912### WeChat Mini Program
913
914Supports [WeChat Mini Program](https://mp.weixin.qq.com/). Use the `wxs` protocol. See [the WeChat docs](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html).
915
916```js
917import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only' // import before mqtt.
918import 'esbuild-plugin-polyfill-node/polyfills/navigator'
919const mqtt = require("mqtt");
920const client = mqtt.connect("wxs://test.mosquitto.org", {
921 timerVariant: 'native' // more info ref issue: #1797
922});
923```
924
925### Ali Mini Program
926
927Supports [Ali Mini Program](https://open.alipay.com/channel/miniIndex.htm). Use the `alis` protocol. See [the Alipay docs](https://docs.alipay.com/mini/developer/getting-started).
928<a name="example"></a>
929
930```js
931const mqtt = require("mqtt");
932const client = mqtt.connect("alis://test.mosquitto.org");
933```
934
935<a name="contributing"></a>
936
937## Contributing
938
939MQTT.js is an **OPEN Open Source Project**. This means that:
940
941> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
942
943See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.
944
945### Contributors
946
947MQTT.js is only possible due to the excellent work of the following contributors:
948
949| Name | GitHub | Twitter |
950| ------------------ | -------------------------------------------------- | ---------------------------------------------------------- |
951| Adam Rudd | [GitHub/adamvr](https://github.com/adamvr) | [Twitter/@adam_vr](http://twitter.com/adam_vr) |
952| Matteo Collina | [GitHub/mcollina](https://github.com/mcollina) | [Twitter/@matteocollina](http://twitter.com/matteocollina) |
953| Maxime Agor | [GitHub/4rzael](https://github.com/4rzael) | [Twitter/@4rzael](http://twitter.com/4rzael) |
954| Siarhei Buntsevich | [GitHub/scarry1992](https://github.com/scarry1992) | |
955| Daniel Lando | [GitHub/robertsLando](https://github.com/robertsLando) | |
956
957<a name="sponsor"></a>
958
959## Sponsor
960
961If you would like to support MQTT.js, please consider sponsoring the author and active maintainers:
962
963- [Matteo Collina](https://github.com/sponsors/mcollina): author of MQTT.js
964- [Daniel Lando](https://github.com/sponsors/robertsLando): active maintainer
965
966<a name="license"></a>
967
968## License
969
970MIT