UNPKG

35.9 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
278<a name="topicalias"></a>
279
280## About Topic Alias Management
281
282### Enabling automatic Topic Alias using
283
284If the client sets the option `autoUseTopicAlias:true` then MQTT.js uses existing topic alias automatically.
285
286example scenario:
287
288```bash
2891. PUBLISH topic:'t1', ta:1 (register)
2902. PUBLISH topic:'t1' -> topic:'', ta:1 (auto use existing map entry)
2913. PUBLISH topic:'t2', ta:1 (register overwrite)
2924. PUBLISH topic:'t2' -> topic:'', ta:1 (auto use existing map entry based on the receent map)
2935. PUBLISH topic:'t1' (t1 is no longer mapped to ta:1)
294```
295
296User doesn't need to manage which topic is mapped to which topic alias.
297If the user want to register topic alias, then publish topic with topic alias.
298If 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.
299
300### Enabling automatic Topic Alias assign
301
302If the client sets the option `autoAssignTopicAlias:true` then MQTT.js uses existing topic alias automatically.
303If 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.
304
305example scenario:
306
307```bash
308The broker returns CONNACK (TopicAliasMaximum:3)
3091. PUBLISH topic:'t1' -> 't1', ta:1 (auto assign t1:1 and register)
3102. PUBLISH topic:'t1' -> '' , ta:1 (auto use existing map entry)
3113. PUBLISH topic:'t2' -> 't2', ta:2 (auto assign t1:2 and register. 2 was vacant)
3124. PUBLISH topic:'t3' -> 't3', ta:3 (auto assign t1:3 and register. 3 was vacant)
3135. PUBLISH topic:'t4' -> 't4', ta:1 (LRU entry is overwritten)
314```
315
316Also user can manually register topic-alias pair using PUBLISH topic:'some', ta:X. It works well with automatic topic alias assign.
317
318<a name="api"></a>
319
320## API
321
322- [`mqtt.connect()`](#connect)
323- [`mqtt.connectAsync()`](#connect-async)
324- [`mqtt.Client()`](#client)
325- [`mqtt.Client#connect()`](#client-connect)
326- [`mqtt.Client#publish()`](#publish)
327- [`mqtt.Client#publishAsync()`](#publish-async)
328- [`mqtt.Client#subscribe()`](#subscribe)
329- [`mqtt.Client#subscribeAsync()`](#subscribe-async)
330- [`mqtt.Client#unsubscribe()`](#unsubscribe)
331- [`mqtt.Client#unsubscribeAsync()`](#unsubscribe-async)
332- [`mqtt.Client#end()`](#end)
333- [`mqtt.Client#endAsync()`](#end-async)
334- [`mqtt.Client#removeOutgoingMessage()`](#removeOutgoingMessage)
335- [`mqtt.Client#reconnect()`](#reconnect)
336- [`mqtt.Client#handleMessage()`](#handleMessage)
337- [`mqtt.Client#connected`](#connected)
338- [`mqtt.Client#reconnecting`](#reconnecting)
339- [`mqtt.Client#getLastMessageId()`](#getLastMessageId)
340- [`mqtt.Store()`](#store)
341- [`mqtt.Store#put()`](#put)
342- [`mqtt.Store#del()`](#del)
343- [`mqtt.Store#createStream()`](#createStream)
344- [`mqtt.Store#close()`](#close)
345
346---
347
348<a name="connect"></a>
349
350### mqtt.connect([url], options)
351
352Connects to the broker specified by the given url and options and
353returns a [Client](#client).
354
355The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
356'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.
357
358The URL can also be an object as returned by
359[`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
360in that case the two objects are merged, i.e. you can pass a single
361object with both the URL and the connect options.
362
363You can also specify a `servers` options with content: `[{ host:
364'localhost', port: 1883 }, ... ]`, in that case that array is iterated
365at every connect.
366
367For all MQTT-related options, see the [Client](#client)
368constructor.
369
370<a name="connect-async"></a>
371
372### connectAsync([url], options)
373
374Asynchronous wrapper around the [`connect`](#connect) function.
375
376Returns a `Promise` that resolves to a `mqtt.Client` instance when the client
377fires a `'connect'` or `'end'` event, or rejects with an error if the `'error'`
378is fired.
379
380Note that the `manualConnect` option will cause the promise returned by this
381function to never resolve or reject as the underlying client never fires any
382events.
383
384---
385
386<a name="client"></a>
387
388### mqtt.Client(streamBuilder, options)
389
390The `Client` class wraps a client connection to an
391MQTT broker over an arbitrary transport method (TCP, TLS,
392WebSocket, ecc).
393`Client` is an [EventEmitter](https://nodejs.dev/en/learn/the-nodejs-event-emitter/) that has it's own [events](#events)
394
395`Client` automatically handles the following:
396
397- Regular server pings
398- QoS flow
399- Automatic reconnections
400- Start publishing before being connected
401
402The arguments are:
403
404- `streamBuilder` is a function that returns a subclass of the `Stream` class that supports
405 the `connect` event. Typically a `net.Socket`.
406- `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults:
407 - `wsOptions`: is the WebSocket connection options. Default is `{}`.
408 It's specific for WebSockets. For possible options have a look at: <https://github.com/websockets/ws/blob/master/doc/ws.md>.
409 - `keepalive`: `60` seconds, set to `0` to disable
410 - `reschedulePings`: reschedule ping messages after sending packets (default `true`)
411 - `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
412 - `protocolId`: `'MQTT'`
413 - `protocolVersion`: `4`
414 - `clean`: `true`, set to false to receive QoS 1 and 2 messages while
415 offline
416 - `reconnectPeriod`: `1000` milliseconds, interval between two
417 reconnections. Disable auto reconnect by setting to `0`.
418 - `connectTimeout`: `30 * 1000` milliseconds, time to wait before a
419 CONNACK is received
420 - `username`: the username required by your broker, if any
421 - `password`: the password required by your broker, if any
422 - `incomingStore`: a [Store](#store) for the incoming packets
423 - `outgoingStore`: a [Store](#store) for the outgoing packets
424 - `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`)
425 - `customHandleAcks`: MQTT 5 feature of custom handling puback and pubrec packets. Its callback:
426
427 ```js
428 customHandleAcks: function(topic, message, packet, done) {/*some logic with calling done(error, reasonCode)*/}
429 ```
430
431 - `autoUseTopicAlias`: enabling automatic Topic Alias using functionality
432 - `autoAssignTopicAlias`: enabling automatic Topic Alias assign functionality
433 - `properties`: properties MQTT 5.0.
434 `object` that supports the following properties:
435 - `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
436 - `receiveMaximum`: representing the Receive Maximum value `number`,
437 - `maximumPacketSize`: representing the Maximum Packet Size the Client is willing to accept `number`,
438 - `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`,
439 - `requestResponseInformation`: The Client uses this value to request the Server to return Response Information in the CONNACK `boolean`,
440 - `requestProblemInformation`: The Client uses this value to indicate whether the Reason String or User Properties are sent in the case of failures `boolean`,
441 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
442 - `authenticationMethod`: the name of the authentication method used for extended authentication `string`,
443 - `authenticationData`: Binary Data containing authentication data `binary`
444 - `authPacket`: settings for auth packet `object`
445 - `will`: a message that will sent by the broker automatically when
446 the client disconnect badly. The format is:
447 - `topic`: the topic to publish
448 - `payload`: the message to publish
449 - `qos`: the QoS
450 - `retain`: the retain flag
451 - `properties`: properties of will by MQTT 5.0:
452 - `willDelayInterval`: representing the Will Delay Interval in seconds `number`,
453 - `payloadFormatIndicator`: Will Message is UTF-8 Encoded Character Data or not `boolean`,
454 - `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`,
455 - `contentType`: describing the content of the Will Message `string`,
456 - `responseTopic`: String which is used as the Topic Name for a response message `string`,
457 - `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`,
458 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
459 - `transformWsUrl` : optional `(url, options, client) => url` function
460 For ws/wss protocols only. Can be used to implement signing
461 urls which upon reconnect can have become expired.
462 - `createWebsocket` : optional `url, websocketSubProtocols, options) => Websocket` function
463 For ws/wss protocols only. Can be used to implement a custom websocket subprotocol or implementation.
464 - `resubscribe` : if connection is broken and reconnects,
465 subscribed topics are automatically subscribed again (default `true`)
466 - `messageIdProvider`: custom messageId provider. when `new UniqueMessageIdProvider()` is set, then non conflict messageId is provided.
467 - `log`: custom log function. Default uses [debug](https://www.npmjs.com/package/debug) package.
468 - `manualConnect`: prevents the constructor to call `connect`. In this case after the `mqtt.connect` is called you should call `client.connect` manually.
469 - `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`
470 - `unixSocket`: if you want to connect to a unix socket, set this to true
471
472In 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.
473
474For 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.
475
476If you are connecting to a broker that supports only MQTT 3.1 (not
4773.1.1 compliant), you should pass these additional options:
478
479```js
480{
481 protocolId: 'MQIsdp',
482 protocolVersion: 3
483}
484```
485
486This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
487version 1.3 and 1.4 works fine without those.
488
489<a name="events"></a>
490
491#### Event `'connect'`
492
493`function (connack) {}`
494
495Emitted on successful (re)connection (i.e. connack rc=0).
496
497- `connack` received connack packet. When `clean` connection option is `false` and server has a previous session
498 for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case,
499 you may rely on stored session and prefer not to send subscribe commands for the client.
500
501#### Event `'reconnect'`
502
503`function () {}`
504
505Emitted when a reconnect starts.
506
507#### Event `'close'`
508
509`function () {}`
510
511Emitted after a disconnection.
512
513#### Event `'disconnect'`
514
515`function (packet) {}`
516
517Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
518
519#### Event `'offline'`
520
521`function () {}`
522
523Emitted when the client goes offline.
524
525#### Event `'error'`
526
527`function (error) {}`
528
529Emitted when the client cannot connect (i.e. connack rc != 0) or when a
530parsing error occurs.
531
532The following TLS errors will be emitted as an `error` event:
533
534- `ECONNREFUSED`
535- `ECONNRESET`
536- `EADDRINUSE`
537- `ENOTFOUND`
538
539#### Event `'end'`
540
541`function () {}`
542
543Emitted when [`mqtt.Client#end()`](#end) is called.
544If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
545callback returns.
546
547#### Event `'message'`
548
549`function (topic, message, packet) {}`
550
551Emitted when the client receives a publish packet
552
553- `topic` topic of the received packet
554- `message` payload of the received packet
555- `packet` received packet, as defined in
556 [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)
557
558#### Event `'packetsend'`
559
560`function (packet) {}`
561
562Emitted when the client sends any packet. This includes .published() packets
563as well as packets used by MQTT for managing subscriptions and connections
564
565- `packet` received packet, as defined in
566 [mqtt-packet](https://github.com/mcollina/mqtt-packet)
567
568#### Event `'packetreceive'`
569
570`function (packet) {}`
571
572Emitted when the client receives any packet. This includes packets from
573subscribed topics as well as packets used by MQTT for managing subscriptions
574and connections
575
576- `packet` received packet, as defined in
577 [mqtt-packet](https://github.com/mcollina/mqtt-packet)
578
579---
580
581<a name="client-connect"></a>
582
583### mqtt.Client#connect()
584
585By default client connects when constructor is called. To prevent this you can set `manualConnect` option to `true` and call `client.connect()` manually.
586
587<a name="publish"></a>
588
589### mqtt.Client#publish(topic, message, [options], [callback])
590
591Publish a message to a topic
592
593- `topic` is the topic to publish to, `String`
594- `message` is the message to publish, `Buffer` or `String`
595- `options` is the options to publish with, including:
596 - `qos` QoS level, `Number`, default `0`
597 - `retain` retain flag, `Boolean`, default `false`
598 - `dup` mark as duplicate flag, `Boolean`, default `false`
599 - `properties`: MQTT 5.0 properties `object`
600 - `payloadFormatIndicator`: Payload is UTF-8 Encoded Character Data or not `boolean`,
601 - `messageExpiryInterval`: the lifetime of the Application Message in seconds `number`,
602 - `topicAlias`: value that is used to identify the Topic instead of using the Topic Name `number`,
603 - `responseTopic`: String which is used as the Topic Name for a response message `string`,
604 - `correlationData`: used by the sender of the Request Message to identify which request the Response Message is for when it is received `binary`,
605 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
606 - `subscriptionIdentifier`: representing the identifier of the subscription `number`,
607 - `contentType`: String describing the content of the Application Message `string`
608 - `cbStorePut` - `function ()`, fired when message is put into `outgoingStore` if QoS is `1` or `2`.
609- `callback` - `function (err)`, fired when the QoS handling completes,
610 or at the next tick if QoS 0. An error occurs if client is disconnecting.
611
612<a name="publish-async"></a>
613
614### mqtt.Client#publishAsync(topic, message, [options])
615
616Async [`publish`](#publish). Returns a `Promise<void>`.
617
618---
619
620<a name="subscribe"></a>
621
622### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])
623
624Subscribe to a topic or topics
625
626- `topic` is a `String` topic to subscribe to or an `Array` of
627 topics to subscribe to. It can also be an object, it has as object
628 keys the topic name and as value the QoS, like `{'test1': {qos: 0}, 'test2': {qos: 1}}`.
629 MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level)
630- `options` is the options to subscribe with, including:
631 - `qos` QoS subscription level, default 0
632 - `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)
633 - `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.)
634 - `rh` Retain Handling MQTT 5.0 (This option specifies whether retained messages are sent when the subscription is established.)
635 - `properties`: `object`
636 - `subscriptionIdentifier`: representing the identifier of the subscription `number`,
637 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
638- `callback` - `function (err, granted)`
639 callback fired on suback where:
640 - `err` a subscription error or an error that occurs when client is disconnecting
641 - `granted` is an array of `{topic, qos}` where:
642 - `topic` is a subscribed to topic
643 - `qos` is the granted QoS level on it
644
645<a name="subscribe-async"></a>
646
647### mqtt.Client#subscribeAsync(topic/topic array/topic object, [options])
648
649Async [`subscribe`](#subscribe). Returns a `Promise<granted[]>`.
650
651---
652
653<a name="unsubscribe"></a>
654
655### mqtt.Client#unsubscribe(topic/topic array, [options], [callback])
656
657Unsubscribe from a topic or topics
658
659- `topic` is a `String` topic or an array of topics to unsubscribe from
660- `options`: options of unsubscribe.
661 - `properties`: `object`
662 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`
663- `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.
664
665<a name="unsubscribe-async"></a>
666
667### mqtt.Client#unsubscribeAsync(topic/topic array, [options])
668
669Async [`unsubscribe`](#unsubscribe). Returns a `Promise<void>`.
670
671---
672
673<a name="end"></a>
674
675### mqtt.Client#end([force], [options], [callback])
676
677Close the client, accepts the following options:
678
679- `force`: passing it to true will close the client right away, without
680 waiting for the in-flight messages to be acked. This parameter is
681 optional.
682- `options`: options of disconnect.
683 - `reasonCode`: Disconnect Reason Code `number`
684 - `properties`: `object`
685 - `sessionExpiryInterval`: representing the Session Expiry Interval in seconds `number`,
686 - `reasonString`: representing the reason for the disconnect `string`,
687 - `userProperties`: The User Property is allowed to appear multiple times to represent multiple name, value pairs `object`,
688 - `serverReference`: String which can be used by the Client to identify another Server to use `string`
689- `callback`: will be called when the client is closed. This parameter is
690 optional.
691
692<a name="end-async"></a>
693
694### mqtt.Client#endAsync([force], [options])
695
696Async [`end`](#end). Returns a `Promise<void>`.
697
698---
699
700<a name="removeOutgoingMessage"></a>
701
702### mqtt.Client#removeOutgoingMessage(mId)
703
704Remove a message from the outgoingStore.
705The outgoing callback will be called with Error('Message removed') if the message is removed.
706
707After this function is called, the messageId is released and becomes reusable.
708
709- `mId`: The messageId of the message in the outgoingStore.
710
711---
712
713<a name="reconnect"></a>
714
715### mqtt.Client#reconnect()
716
717Connect again using the same options as connect()
718
719---
720
721<a name="handleMessage"></a>
722
723### mqtt.Client#handleMessage(packet, callback)
724
725Handle messages with backpressure support, one at a time.
726Override at will, but **always call `callback`**, or the client
727will hang.
728
729---
730
731<a name="connected"></a>
732
733### mqtt.Client#connected
734
735Boolean : set to `true` if the client is connected. `false` otherwise.
736
737---
738
739<a name="getLastMessageId"></a>
740
741### mqtt.Client#getLastMessageId()
742
743Number : get last message id. This is for sent messages only.
744
745---
746
747<a name="reconnecting"></a>
748
749### mqtt.Client#reconnecting
750
751Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.
752
753---
754
755<a name="store"></a>
756
757### mqtt.Store(options)
758
759In-memory implementation of the message store.
760
761- `options` is the store options:
762 - `clean`: `true`, clean inflight messages when close is called (default `true`)
763
764Other implementations of `mqtt.Store`:
765
766- [mqtt-jsonl-store](https://github.com/robertsLando/mqtt-jsonl-store) which uses
767 [jsonl-db](https://github.com/AlCalzone/jsonl-db) to store inflight data, it works only on Node.
768- [mqtt-level-store](http://npm.im/mqtt-level-store) which uses
769 [Level-browserify](http://npm.im/level-browserify) to store the inflight
770 data, making it usable both in Node and the Browser.
771- [mqtt-nedb-store](https://github.com/behrad/mqtt-nedb-store) which
772 uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight
773 data.
774- [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses
775 [localForage](http://npm.im/localforage) to store the inflight
776 data, making it usable in the Browser without browserify.
777
778---
779
780<a name="put"></a>
781
782### mqtt.Store#put(packet, callback)
783
784Adds a packet to the store, a packet is
785anything that has a `messageId` property.
786The callback is called when the packet has been stored.
787
788---
789
790<a name="createStream"></a>
791
792### mqtt.Store#createStream()
793
794Creates a stream with all the packets in the store.
795
796---
797
798<a name="del"></a>
799
800### mqtt.Store#del(packet, cb)
801
802Removes a packet from the store, a packet is
803anything that has a `messageId` property.
804The callback is called when the packet has been removed.
805
806---
807
808<a name="close"></a>
809
810### mqtt.Store#close(cb)
811
812Closes the Store.
813
814<a name="browser"></a>
815<a name="webpack"></a>
816<a name="vite"></a>
817
818## Browser
819
820> [!IMPORTANT]
821> The only protocol supported in browsers is MQTT over WebSockets, so you must use `ws://` or `wss://` protocols.
822
823While 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:
824
825- The `wsOption` is not supported in browsers.
826- Browsers doesn't allow to catch many WebSocket errors for [security reasons](https://stackoverflow.com/a/31003057) as:
827
828 > 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.
829
830 So listening for `client.on('error')` may not catch all the errors you would get in NodeJS env.
831
832### Bundle
833
834MQTT.js is bundled using [esbuild](https://esbuild.github.io/). It is tested working with all bundlers like Webpack, Vite and React.
835
836You can find all mqtt bundles versions in `dist` folder:
837
838- `mqtt.js` - iife format, not minified
839- `mqtt.min.js` - iife format, minified
840- `mqtt.esm.js` - esm format minified
841
842Starting from MQTT.js > 5.2.0 you can import mqtt in your code like this:
843
844```js
845import mqtt from 'mqtt'
846```
847
848This will be automatically handled by your bundler.
849
850Otherwise you can choose to use a specific bundle like:
851
852```js
853import * as mqtt from 'mqtt/dist/mqtt'
854import * as mqtt from 'mqtt/dist/mqtt.min'
855import mqtt from 'mqtt/dist/mqtt.esm'
856```
857
858<a name="cdn"></a>
859
860### Via CDN
861
862The MQTT.js bundle is available through <http://unpkg.com>, specifically
863at <https://unpkg.com/mqtt/dist/mqtt.min.js>.
864See <http://unpkg.com> for the full documentation on version ranges.
865
866<a name="qos"></a>
867
868## About QoS
869
870Here is how QoS works:
871
872- QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received.
873- 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.
874- QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates.
875
876About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
877
878<a name="typescript"></a>
879
880## Usage with TypeScript
881
882Starting from v5 this project is written in TypeScript and the type definitions are included in the package.
883
884Example:
885
886```ts
887import { connect } from "mqtt"
888const client = connect('mqtt://test.mosquitto.org')
889```
890
891<a name="weapp-alipay"></a>
892
893## WeChat and Ali Mini Program support
894
895### WeChat Mini Program
896
897Supports [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).
898
899```js
900const mqtt = require("mqtt");
901const client = mqtt.connect("wxs://test.mosquitto.org");
902```
903
904### Ali Mini Program
905
906Supports [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).
907<a name="example"></a>
908
909```js
910const mqtt = require("mqtt");
911const client = mqtt.connect("alis://test.mosquitto.org");
912```
913
914<a name="contributing"></a>
915
916## Contributing
917
918MQTT.js is an **OPEN Open Source Project**. This means that:
919
920> 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.
921
922See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.
923
924### Contributors
925
926MQTT.js is only possible due to the excellent work of the following contributors:
927
928| Name | GitHub | Twitter |
929| ------------------ | -------------------------------------------------- | ---------------------------------------------------------- |
930| Adam Rudd | [GitHub/adamvr](https://github.com/adamvr) | [Twitter/@adam_vr](http://twitter.com/adam_vr) |
931| Matteo Collina | [GitHub/mcollina](https://github.com/mcollina) | [Twitter/@matteocollina](http://twitter.com/matteocollina) |
932| Maxime Agor | [GitHub/4rzael](https://github.com/4rzael) | [Twitter/@4rzael](http://twitter.com/4rzael) |
933| Siarhei Buntsevich | [GitHub/scarry1992](https://github.com/scarry1992) | |
934| Daniel Lando | [GitHub/robertsLando](https://github.com/robertsLando) | |
935
936<a name="sponsor"></a>
937
938## Sponsor
939
940If you would like to support MQTT.js, please consider sponsoring the author and active maintainers:
941
942- [Matteo Collina](https://github.com/sponsors/mcollina): author of MQTT.js
943- [Daniel Lando](https://github.com/sponsors/robertsLando): active maintainer
944
945<a name="license"></a>
946
947## License
948
949MIT