Connecting webapp to AWS IoT Core with MQTT.js

204 Views Asked by At
import { useEffect, useState } from 'react';
import mqtt from 'mqtt';

export default function Home() {
  const [mqttClient, setMqttClient] = useState(null);

  useEffect(() => {
    // Fetch the credentials from our Next.js API route
    fetch('./api/iot-credentials')
      .then(res => res.json())
      .then(credentials => {
        // Define the connection options for AWS IoT Core
        const options = {
          key: credentials.privateKey,
          cert: credentials.certificate,
          ca: credentials.rootCA,
          clientId: credentials.clientId,  
          protocol: 'wss',  
          host: credentials.endpoint,
          port: 443,
          path: '/mqtt',
          reconnectPeriod: 30*1000,
          keepalive: 60,
          clean: true,
          rejectUnauthorized: false,
        };

        // Connect to AWS IoT Core
        const brokerUrl = `${options.protocol}://${options.host}:${options.port}${options.path}`;
        const client = mqtt.connect(brokerUrl, options);


        client.on('connect', () => {
          console.log('Connected to AWS IoT Core');
        });
        client.on('error', (error) => {
          console.error('Error connecting to AWS IoT Core:', error);
        });
        
        client.on('offline', () => {
          console.log('MQTT client is offline');
        });
        
        client.on('reconnect', () => {
          console.log('MQTT client is trying to reconnect');
        });
        
        client.on('end', () => {
          console.log('MQTT client disconnected');
        });
        

        setMqttClient(client);
      });
  }, []);

  // Example function to publish a message
  const publishMessage = () => {
    if (mqttClient) {
      mqttClient.publish('my-topic', 'Hello from frontend');
    }
  };

  return (
    <div>
      <button onClick={publishMessage}>Publish Message</button>
    </div>
  );
}

I am trying to do a simple connection to AWS IoT Core to publish and subscribe to a topic using MQTT.js library. The pasted code is the connection settup i have build, but it is not working. Can someone please explain to me what i dont understand for this to work?
There are no error messages to work with.

0

There are 0 best solutions below