tencent cloud

Javascript/Node.JS/Mini Program
Last updated:2026-01-30 15:02:25
Javascript/Node.JS/Mini Program
Last updated: 2026-01-30 15:02:25

Feature Overview

MQTT.js is a module written in JavaScript that implements the MQTT protocol client feature, and can be used in both browser and Node.js environments.
Due to the single-threaded nature of JavaScript, MQTT.js is a fully asynchronous MQTT client. It supports both MQTT and MQTT over WebSocket, with varying levels of support across different runtime environments:
Browser environments: MQTT over WebSocket (including customized browser environments such as WeChat Mini Program, Alipay Mini Program, and so on).
Node.js environment: MQTT, MQTT over WebSocket.
In different environments, except for a few connection parameters, all other APIs are the same.

Preparing the Environment

Using npm Installation:
npm i mqtt
Using CDN Installation (for browsers):
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
// will initialize an mqtt variable globally.
console.log(mqtt)
</script>
In a Node.js environment, you can install MQTT.js globally via the command `npm i mqtt -g` to use it via the command line.
npm i mqtt -g

mqtt help

MQTT.js command line interface, available commands are:

* publish publish a message to the broker
* subscribe subscribe for updates from the broker
* version the current MQTT.js version
* help help about commands

Launch 'mqtt help [command]' to know more about the commands.

Example Code

MQTT5
MQTT5 TLS
MQTT3.1.1
MQTT3.1.1 TLS

const mqtt = require('mqtt');

/**
* MQTT 5.0 TCP Connection Example
*/

// ============ Connection Configuration ============
const serverUri = 'mqtt://mqtt-xxx.mqtt.tencenttdmq.com:1883';
const clientId = 'QuickStart';
const username = 'YOUR_USERNAME';
const password = 'YOUR_PASSWORD';
const pubTopic = 'home/test';
const topicFilters = ['home/test', 'home/#', 'home/+'];
const qos = [1, 1, 1];

// Configure connection options
const options = {
clientId: clientId,
username: username,
password: password,
protocolVersion: 5, // MQTT 5.0
clean: true,
reconnectPeriod: 0, // Disable automatic reconnection
};

// Create a client and connect
const client = mqtt.connect(serverUri, options);

// Connection successful
client.on('connect', async () => {
console.log('Connected');

try {
// 2. Subscribe
for (let i = 0; i < topicFilters.length; i++) {
await new Promise((resolve, reject) => {
client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {
if (err) reject(err);
else resolve();
});
});
}
console.log('Subscribed');

// 3. Publish
for (let i = 1; i <= 16; i++) {
await new Promise((resolve, reject) => {
client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {
if (err) reject(err);
else resolve();
});
});
await new Promise(resolve => setTimeout(resolve, 500));
}
console.log('Publish completed');

// 4. Wait to receive
await new Promise(resolve => setTimeout(resolve, 2000));

// 5. Disconnect
client.end();
console.log('Disconnected');
} catch (error) {
console.error('Error:', error.message);
client.end();
}
});

// Message receiving and processing
client.on('message', (topic, message) => {
console.log(`Received message: ${topic} -> ${message.toString()}`);
});

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


const mqtt = require('mqtt');
const fs = require('fs');
const tls = require('tls');

/**
* MQTT 5.0 TLS Encrypted Connection Example
*/

// ============ Connection Configuration ============
const serverUri = 'mqtts://mqtt-xxx.mqtt.tencenttdmq.com:8883';
const clientId = 'QuickStart';
const username = 'YOUR_USERNAME';
const password = 'YOUR_PASSWORD';
const pubTopic = 'home/test';
const topicFilters = ['home/test', 'home/#', 'home/+'];
const qos = [1, 1, 1];

// CA certificate path (optional, used to verify server certificate)
const caCertPath = null; // e.g., '/path/to/ca.crt'

// Configure connection options (with TLS)
const options = {
clientId: clientId,
username: username,
password: password,
protocolVersion: 5, // MQTT 5.0
clean: true,
reconnectPeriod: 0, // Disable automatic reconnection
// TLS Configuration
rejectUnauthorized: true, // Production environment: verify server certificate
// If a CA certificate is provided, load it
ca: caCertPath ? [fs.readFileSync(caCertPath)] : undefined,
// Custom certificate verification
checkServerIdentity: (host, cert) => {
return validateServerCertificate(host, cert);
}
};

/**
* Verify server certificate
*/
function validateServerCertificate(host, cert) {
// 1. Check the certificate validity period
const now = new Date();
const validFrom = new Date(cert.valid_from);
const validTo = new Date(cert.valid_to);
if (now < validFrom || now > validTo) {
const error = new Error(`Certificate verification failed: the certificate has expired or is not yet valid (Validity period: ${validFrom} - ${validTo})`);
console.error(error.message);
return error;
}
// 2. Check the topic name (Optional, depending on actual requirements)
// const expectedSubject = 'CN=*.mqtt.tencenttdmq.com';
// if (!cert.subject.CN || !cert.subject.CN.includes('mqtt.tencenttdmq.com')) {
// const error = new Error(`Certificate verification failed: Subject mismatch (Actual: ${cert.subject.CN})`);
// console.error(error.message);
// return error;
// }
// 3. Use default certificate chain verification
const err = tls.checkServerIdentity(host, cert);
if (err) {
console.error('Certificate verification failed:', err.message);
return err;
}
console.log('Certificate verification passed');
return undefined;
}

// Create a client and connect
const client = mqtt.connect(serverUri, options);

// Connection successful
client.on('connect', async () => {
console.log('Connected (TLS encrypted)');

try {
// 2. Subscribe
for (let i = 0; i < topicFilters.length; i++) {
await new Promise((resolve, reject) => {
client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {
if (err) reject(err);
else resolve();
});
});
}
console.log('Subscribed');

// 3. Publish
for (let i = 1; i <= 16; i++) {
await new Promise((resolve, reject) => {
client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {
if (err) reject(err);
else resolve();
});
});
await new Promise(resolve => setTimeout(resolve, 500));
}
console.log('Publish completed');

// 4. Wait to receive
await new Promise(resolve => setTimeout(resolve, 2000));

// 5. Disconnect
client.end();
console.log('Disconnected');
} catch (error) {
console.error('Error:', error.message);
client.end();
}
});

// Message receiving and processing
client.on('message', (topic, message) => {
console.log(`Received message: ${topic} -> ${message.toString()}`);
});

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

const mqtt = require('mqtt');

/**
* MQTT 3.1.1 TCP Connection Example
*/

// ============ Connection Configuration ============
const serverUri = 'mqtt://mqtt-xxx.mqtt.tencenttdmq.com:1883';
const clientId = 'QuickStart';
const username = 'YOUR_USERNAME';
const password = 'YOUR_PASSWORD';
const pubTopic = 'home/test';
const topicFilters = ['home/test', 'home/#', 'home/+'];
const qos = [1, 1, 1];

// Configure connection options
const options = {
clientId: clientId,
username: username,
password: password,
protocolVersion: 4, // MQTT 3.1.1
clean: true,
reconnectPeriod: 0, // Disable automatic reconnection
};

// Create a client and connect
const client = mqtt.connect(serverUri, options);

// Connection successful
client.on('connect', async () => {
console.log('Connected');

try {
// 2. Subscribe
for (let i = 0; i < topicFilters.length; i++) {
await new Promise((resolve, reject) => {
client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {
if (err) reject(err);
else resolve();
});
});
}
console.log('Subscribed');

// 3. Publish
for (let i = 1; i <= 16; i++) {
await new Promise((resolve, reject) => {
client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {
if (err) reject(err);
else resolve();
});
});
await new Promise(resolve => setTimeout(resolve, 500));
}
console.log('Publish completed');

// 4. Wait to receive
await new Promise(resolve => setTimeout(resolve, 2000));

// 5. Disconnect
client.end();
console.log('Disconnected');
} catch (error) {
console.error('Error:', error.message);
client.end();
}
});

// Message receiving and processing
client.on('message', (topic, message) => {
console.log(`Received message: ${topic} -> ${message.toString()}`);
});

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

const mqtt = require('mqtt');
const fs = require('fs');
const tls = require('tls');

/**
* MQTT 3.1.1 TLS Encrypted Connection Example
*/

// ============ Connection Configuration ============
const serverUri = 'mqtts://mqtt-xxx.mqtt.tencenttdmq.com:8883';
const clientId = 'QuickStart';
const username = 'YOUR_USERNAME';
const password = 'YOUR_PASSWORD';
const pubTopic = 'home/test';
const topicFilters = ['home/test', 'home/#', 'home/+'];
const qos = [1, 1, 1];

// CA certificate path (optional, used to verify server certificate)
const caCertPath = null; // e.g., '/path/to/ca.crt'

// Configure connection options (with TLS)
const options = {
clientId: clientId,
username: username,
password: password,
protocolVersion: 4, // MQTT 3.1.1
clean: true,
reconnectPeriod: 0, // Disable automatic reconnection
// TLS Configuration
rejectUnauthorized: true, // Production environment: verify server certificate
// If a CA certificate is provided, load it
ca: caCertPath ? [fs.readFileSync(caCertPath)] : undefined,
// Custom certificate verification
checkServerIdentity: (host, cert) => {
return validateServerCertificate(host, cert);
}
};

/**
* Verify server certificate
*/
function validateServerCertificate(host, cert) {
// 1. Check the certificate validity period
const now = new Date();
const validFrom = new Date(cert.valid_from);
const validTo = new Date(cert.valid_to);
if (now < validFrom || now > validTo) {
const error = new Error(`Certificate verification failed: the certificate has expired or is not yet valid (Validity period: ${validFrom} - ${validTo})`);
console.error(error.message);
return error;
}
// 2. Check the topic name (Optional, depending on actual requirements)
// const expectedSubject = 'CN=*.mqtt.tencenttdmq.com';
// if (!cert.subject.CN || !cert.subject.CN.includes('mqtt.tencenttdmq.com')) {
// const error = new Error(`Certificate verification failed: Subject mismatch (Actual: ${cert.subject.CN})`);
// console.error(error.message);
// return error;
// }
// 3. Use default certificate chain verification
const err = tls.checkServerIdentity(host, cert);
if (err) {
console.error('Certificate verification failed:', err.message);
return err;
}
console.log('Certificate verification passed');
return undefined;
}

// Create a client and connect
const client = mqtt.connect(serverUri, options);

// Connection successful
client.on('connect', async () => {
console.log('Connected (TLS encrypted)');

try {
// 2. Subscribe
for (let i = 0; i < topicFilters.length; i++) {
await new Promise((resolve, reject) => {
client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {
if (err) reject(err);
else resolve();
});
});
}
console.log('Subscribed');

// 3. Publish
for (let i = 1; i <= 16; i++) {
await new Promise((resolve, reject) => {
client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {
if (err) reject(err);
else resolve();
});
});
await new Promise(resolve => setTimeout(resolve, 500));
}
console.log('Publish completed');

// 4. Wait to receive
await new Promise(resolve => setTimeout(resolve, 2000));

// 5. Disconnect
client.end();
console.log('Disconnected');
} catch (error) {
console.error('Error:', error.message);
client.end();
}
});

// Message receiving and processing
client.on('message', (topic, message) => {
console.log(`Received message: ${topic} -> ${message.toString()}`);
});

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



Parameter Description

Parameter
Description
topic
Copy the first-level MQTT Topic from the Topic Prefix page in the cluster details console.

connectUrl
broker connection address can be copied from the Basic Information > Access Information section of the target cluster in the console, as shown below. Format: mqtt-xxx-gz.mqtt.qcloud.tencenttdmq.com:1883.

clientId
Client ID is obtained from the Client Management page in the cluster details page on the console.

username
Connection username can be copied from the Authentication Management page on the cluster details console.

password
The password matching the Connection Username can be copied from the Authentication Management page on the cluster details console.

Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback