Cannot subscribe with node.js

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!!

Hello @asyarif

It appears that your MQTT client code is experiencing authentication issues when connecting to the HiveMQ Cloud broker. This could be due to incorrect credentials. Please review the example provided in our GitHub repository below for guidance.

Kind regards,
Diego from HiveMQ Team

thanks for the reply! I have followed the guide, but it still gives an error like this

Error: Error: getaddrinfo ENOTFOUND 8883

*Edit: It works! there was a little mistake in my code, i accidentally removed the “tls://” before host