Hello! I am trying to make a school project that requires subscribing to MQTT from my backend (using node.js). this is the code i use to subscribe to a topic in my cluster,
const dotenv = require('dotenv');
dotenv.config();
const MQTT = require('mqtt');
const fs = require('fs');
const HOST = process.env.SERVERHOSTNAME;
const PORT = 8883;
const CLIENTID = `Traceability-test`;
const CONNECTURL = `mqtts://${HOST}:${PORT}`;
const TOPIC = 'Inkubasi/01A';
const CA_CERT_PATH = './isrgrootx1.pem'; // Path to your Let's Encrypt root CA file
//Encrypt root CA certificate
let caCert;
try {
caCert = fs.readFileSync(CA_CERT_PATH);
} catch (err) {
console.error('Error reading CA certificate:', err);
// Handle error
}
const client = MQTT.connect(CONNECTURL, {
clientId: CLIENTID,
clean: true,
connectTimeout: 7200,
username: process.env.USERNAME,
password: process.env.PASSWORD,
reconnectPeriod: 10000,
ca: caCert, // Provide the CA certificate to the MQTT client
});
client.on("error",function(error){ console.log("Can't connect"+error)})
client.on('connect', async () => {
console.log('Connected')
client.subscribe([TOPIC], () => {
console.log(`Subscribe to TOPIC '${TOPIC}'`)
})
})
client.on('message', (TOPIC, payload) => {
console.log('Received Message:', TOPIC, payload.toString())
})
I already added the root CA following instruction from the other discussions. But it keeps saying this error.
> Can't connectErrorWithReasonCode: Connection refused: Not authorized
Any help would be appreciated. Thanks in advance!!