Release Notes
npm i mqtt
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script><script>// Initialize a global mqtt variable.console.log(mqtt)</script>
npm i mqtt -gmqtt helpMQTT.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 commandsLaunch 'mqtt help [command]' to know more about the commands.
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.0clean: true,reconnectPeriod: 0, // Disable automatic reconnection.};// Create a client and connect.const client = mqtt.connect(serverUri, options);// Connection successfulclient.on('connect', async () => {console.log('Connected');try {// 2. Subscribefor (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. Publishfor (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 receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error handlingclient.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.0clean: true,reconnectPeriod: 0, // Disable automatic reconnection.// TLS configurationrejectUnauthorized: true, // Production environment: Verify the server certificate// If a CA certificate is provided, load it.ca: caCertPath ? [fs.readFileSync(caCertPath)] : undefined,// Custom certificate verificationcheckServerIdentity: (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 successfulclient.on('connect', async () => {console.log('Connected (TLS encrypted)');try {// 2. Subscribefor (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. Publishfor (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 receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error handlingclient.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.1clean: true,reconnectPeriod: 0, // Disable automatic reconnection.};// Create a client and connect.const client = mqtt.connect(serverUri, options);// Connection successfulclient.on('connect', async () => {console.log('Connected');try {// 2. Subscribefor (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. Publishfor (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 receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error handlingclient.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.1clean: true,reconnectPeriod: 0, // Disable automatic reconnection.// TLS ConfigurationrejectUnauthorized: true, // Production environment: Verify the server certificate// If a CA certificate is provided, load it.ca: caCertPath ? [fs.readFileSync(caCertPath)] : undefined,// Custom certificate verificationcheckServerIdentity: (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 successfulclient.on('connect', async () => {console.log('Connected (TLS encrypted)');try {// 2. Subscribefor (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. Publishfor (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 receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error handlingclient.on('error', (error) => {console.error('Error:', error.message);});
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. |
Was this page helpful?
You can also Contact sales or Submit a Ticket for help.
Help us improve! Rate your documentation experience in 5 mins.
Feedback