node.js mqtt client using TLS

guagay_wk picture guagay_wk · Oct 13, 2016 · Viewed 12.9k times · Source

I am trying to implement a node.js mqtt client with TLS using the package below;

https://www.npmjs.com/package/mqtt#client

The code for running mqtt client without TLS is as follows;

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', function () {
  client.subscribe('presence')
  client.publish('presence', 'Hello mqtt')
})

client.on('message', function (topic, message) {
  // message is Buffer 
  console.log(message.toString())
  client.end()
})

How should the above code be modified to use TLS on the mqtt client?

The mosca MQTT broker was run as a stand-alone using the command below;

mosca --key ./tls-key.pem --cert ./tls-cert.pem --http-port 3000 --http-bundle --http-static ./ | pino

Answer

notion picture notion · Oct 13, 2016

Should be enough to change the protocol part of the URL to mqtts://

mqtts://test.mosquitto.org.

Self-signed certificates

You can pass the following option to the connect function when using self-signed certificates (for testing purposes only):

mqtt.connect('mqtts://test.mosquitto.org', {
    rejectUnauthorized: false
});