tencent cloud

TDMQ for MQTT

Related Agreement
プライバシーポリシー
データプライバシーとセキュリティ契約
ドキュメントTDMQ for MQTT

Javascript/Node.JS/Mini Program

フォーカスモード
フォントサイズ
最終更新日: 2026-04-01 16:37:51

Feature Overview

MQTT.js is a JavaScript module that implements MQTT protocol client functionality and can be used in browser and Node.js environments.
Since JavaScript is single-threaded, MQTT.js is a fully asynchronous MQTT client. It supports MQTT and MQTT over WebSocket, with different levels of support in execution environments as follows:
Browser environment: MQTT over WebSocket (including WeChat mini program, Alipay mini program, and other custom browser environments).
Node.js environment: MQTT and MQTT over WebSocket.
In different environments, except for a few connection parameters, all other APIs are the same.

Environment Preparation

Install using npm:
npm i mqtt
Install using CDN (browser):
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
// Initialize a global mqtt variable.
console.log(mqtt)
</script>
In a Node.js environment, you can use the command `npm i mqtt -g` to globally install MQTT.js for command line usage.
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.

Sample 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('Published');

// 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 the server certificate)
const caCertPath = null; // e.g., '/path/to/ca.crt'

// Configure connection options (including 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 the 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 the 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 subject name (optional, based 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 the default certificate chain for 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('Published');

// 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('Published');

// 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 the server certificate)
const caCertPath = null; // e.g., '/path/to/ca.crt'

// Configure connection options (including 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 the 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 the 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, based 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 the default certificate chain for 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('Published');

// 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
First-level MQTT topic, which can be copied from the Topic page on the cluster details page in the console.

connectUrl
Broker connection address, which 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, which can be obtained from the Client Management page on the cluster details page in the console.

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

password
Password matching the connection username, which can be copied from the Authentication Management page on the cluster details page in the console.


ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック