Search code examples
javascripthtmlmqttmqtt.js

MQTT.js - Uncaught TypeError: n.createConnection is not a function


I try to connect my webapp with my MQTT-Broker. I decide to use MQTT.js, but there is an error in my code:

Uncaught TypeError: n.createConnection is not a function
    at t.exports (mqtt.min.js:1:29576)
    at T.streamBuilder (mqtt.min.js:1:39683)
    at T._setupStream (mqtt.min.js:1:6556)
    at new T (mqtt.min.js:1:5968)
    at Function.u [as connect] (mqtt.min.js:1:39286)
    at (index):23:29

The exception will be thrown in line const client = mqtt.connect(broker); . I don't know, how to solve this issue, I hope you can help me.

Here is a minimal example of my code:

<!DOCTYPE html>
<html>
<head>
    <title>MQTT Data Display</title>
    <script src="mqtt.min.js"></script>
</head>
<body>
    <h1>MQTT Data Display</h1>
    
    <h2>Receiving Data:</h2>
    <textarea id="dataField" rows="5" cols="50" readonly></textarea>
    
    <h2>Input text:</h2>
    <input type="text" id="inputField" />
    <button onclick="publishMessage()">Send</button>
    
    <script>
        // MQTT Broker config
        const broker = 'mqtt:<BrokerURL>';
        const topic = 'your-mqtt-topic';

        // create MQTT Client
        const client = mqtt.connect(broker);

        // connect MQTT Client
        client.on('connect', function () {
            console.log('MQTT connected');
            client.subscribe(topic);
        });

        // Receive new message
        client.on('message', function (topic, message) {
            const data = message.toString();
            const dataField = document.getElementById('dataField');
            dataField.value = data;
        });

        // publish messsage
        function publishMessage() {
            const inputField = document.getElementById('inputField');
            const message = inputField.value;
            client.publish(topic, message);
        }
    </script>
</body>
</html>


Solution

  • When running from inside a web browser you MUST use MQTT over Websockets, you can not use native MQTT because the browser sandbox will not allow you to connect to arbitrary TCP ports.

    So you must first have a broker that is configured to accept connections via MQTT over Websockets.

    Second you need to change the broker variable to be the a URL starting with ws:// not mqtt://

    Next, is the browser running on the same machine as the MQTT broker? localhost is only going to access the machine the browser is running on which is not normally the case for web pages.