Skip to content

mqtt

Since v8.0.74

The mqtt is the MQTT client module.

In JSH applications, you normally use:

const mqtt = require('mqtt');

This module is event-driven and auto-connects when a Client is created.

Client

MQTT client object.

Creation
new Client(options)
Options
OptionTypeDefaultDescription
serversString[]MQTT broker URLs (e.g. tcp://127.0.0.1:1883)
usernameStringUsername for broker authentication
passwordStringPassword for broker authentication
keepAliveNumber30Keep alive in seconds
connectRetryDelayNumber0Reconnect delay in milliseconds
cleanStartOnInitialConnectionBooleanfalseMQTT v5 clean start on first connection
connectTimeoutNumber0Connect timeout in milliseconds
Usage example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const mqtt = require('mqtt');

const client = new mqtt.Client({
    servers: ['tcp://127.0.0.1:1883'],
    username: 'user',
    password: 'pass',
    keepAlive: 60,
    connectRetryDelay: 2000,
    connectTimeout: 10 * 1000,
    cleanStartOnInitialConnection: true,
});

client.on('open', () => {
    console.println('Connected');
    client.subscribe('test/topic', {
        qos: 0,
        properties: {
            subscriptionIdentifier: 7,
        },
    });
});

client.on('subscribed', (topic, reason) => {
    console.println('Subscribed:', topic, 'reason:', reason);
    client.publish('test/topic', 'Hello, MQTT!');
});

client.on('message', (msg) => {
    console.println('Message:', msg.topic, msg.payloadText);
    client.unsubscribe(msg.topic, {
        properties: {
            user: {
                source: 'example',
            },
        },
    });
});

client.on('unsubscribed', (topic, reason) => {
    console.println('Unsubscribed:', topic, 'reason:', reason);
    client.close();
});

client.on('error', (err) => {
    console.println('Error:', err.message);
});

client.on('close', () => {
    console.println('Disconnected');
});

Methods

publish()

Publishes a message to a topic.

Syntax
publish(topic, message[, options])
Parameters
  • topic String
  • message String | Uint8Array | Object | Array
  • options Object (optional)
OptionTypeDefaultDescription
qosNumber0QoS level
retainBooleanfalseRetain flag
propertiesObjectMQTT v5 publish properties

options.properties fields:

PropertyTypeDescription
payloadFormatNumberPayload format indicator
messageExpiryNumberExpiry interval
contentTypeStringContent type
responseTopicStringResponse topic
correlationDataStringConverted to bytes
topicAliasNumberTopic alias
subscriptionIdentifierNumberSubscription identifier
userObjectUser properties (key: value)
Return value

None. Result is delivered by published or error events.

subscribe()

Subscribes to a topic.

Syntax
subscribe(topic[, options])
Parameters
  • topic String
  • options Object (optional)
OptionTypeDefaultDescription
qosNumber1QoS level
retainHandlingNumberMQTT v5 retain handling
noLocalBooleanfalseWhether to suppress messages published by the same client
retainAsPublishedBooleanfalseWhether to preserve the retain flag from the broker
propertiesObjectMQTT v5 subscribe properties

options.properties fields:

PropertyTypeDescription
subscriptionIdentifierNumberSubscription identifier
userObjectUser properties (key: value)
Return value

None. Result is delivered by subscribed or error events.

Usage example
client.subscribe('test/topic', {
    qos: 0,
    properties: {
        subscriptionIdentifier: 7,
        user: {
            source: 'example',
        },
    },
});

unsubscribe()

Unsubscribes from a topic.

Syntax
unsubscribe(topic[, options])
Parameters
  • topic String
  • options Object (optional)
OptionTypeDescription
propertiesObjectMQTT v5 unsubscribe properties

options.properties fields:

PropertyTypeDescription
userObjectUser properties (key: value)
Return value

None. Result is delivered by unsubscribed or error events.

Usage example
client.unsubscribe('test/topic', {
    properties: {
        user: {
            source: 'example',
        },
    },
});

close()

Closes the client connection.

Syntax
close()
Return value

None. Emits close event.

Events

open

Emitted after the client is connected.

client.on('open', () => { ... })

message

Emitted when a subscribed message is received.

client.on('message', (msg) => { ... })

msg fields:

PropertyTypeDescription
topicStringTopic name
payloadBufferBinary-safe message payload
payloadTextStringUTF-8 decoded text convenience field
propertiesObjectMQTT v5 publish properties

msg.properties fields:

PropertyTypeDescription
payloadFormatNumberPayload format indicator
messageExpiryNumberExpiry interval
contentTypeStringContent type
responseTopicStringResponse topic
correlationDataBufferBinary-safe correlation data
topicAliasNumberTopic alias
subscriptionIdentifierNumberSubscription identifier
userObjectUser properties

For text messages, use msg.payloadText or msg.payload.toString().

For binary messages, inspect msg.payload directly.

client.on('message', (msg) => {
    console.println('Payload is buffer:', Buffer.isBuffer(msg.payload));
    console.println('Payload bytes:', Array.from(msg.payload).join(','));
});

MQTT v5 publish properties are available as msg.properties.

client.on('message', (msg) => {
    console.println('Content type:', msg.properties.contentType);
    console.println('Response topic:', msg.properties.responseTopic);
    console.println('Correlation data:', msg.properties.correlationData.toString());
    console.println('User source:', msg.properties.user.source);
});

subscribed

Emitted when subscription ack is received.

client.on('subscribed', (topic, reason) => { ... })
  • topic String
  • reason Number (MQTT reason code)

published

Emitted when publish ack is received.

client.on('published', (topic, reason) => { ... })
  • topic String
  • reason Number (MQTT reason code)

unsubscribed

Emitted when unsubscribe ack is received.

client.on('unsubscribed', (topic, reason) => { ... })
  • topic String
  • reason Number (MQTT reason code)

error

Emitted when connection, subscribe, unsubscribe, or publish fails.

client.on('error', (err) => { ... })
  • err Error

If publish(), subscribe(), or unsubscribe() is called before the client is connected or after close(), the error is delivered through the error event.

close

Emitted when close() is called.

client.on('close', () => { ... })

MQTT v5 write properties example

This example writes to db/write/{table} and sets MQTT v5 user properties documented in MQTT v5 write API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const mqtt = require('mqtt');

const client = new mqtt.Client({
    servers: ['tcp://127.0.0.1:5653'],
});

const rows = [
    ['my-car', Date.now(), 32.1],
    ['my-car', Date.now() + 1000, 65.4],
];

client.on('open', () => {
    client.publish('db/write/EXAMPLE', rows, {
        qos: 1,
        properties: {
            user: {
                method: 'append',
                timeformat: 'ms',
            },
        },
    });
});

client.on('published', () => client.close());
client.on('error', (err) => console.println(err.message));
Last updated on