skip to Main Content

Node version: 18.17.1
Npm version: 9.8.1

I have installed mqtt using:

npm install mqtt

It’s working there without any problem. Code is as below:

import { useState } from 'react'
import './App.css'

import * as mqtt from 'mqtt'

function App() {

  let client = mqtt.connect("mqtt://test.mosquitto.org"); // create a client

  return (
    <>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  )
}

export default App

This is the error showing:
enter image description here

  1. Connecting to MQTT broker from Javascript -> Worked
  2. Connecting to MQTT broker from Vite (React) -> Not-Worked
  3. Connecting to MQTT broker from Next.js -> Not-Worked

2

Answers


  1. Chosen as BEST ANSWER

    Thank you so much :). The answer is very useful.


  2. You can not connect with native MQTT over TCP from a web app, the library will automatically convert the connection to MQTT over WebSockets (with the default HTTP port).

    But if the web app is loaded over HTTPS then the browser sandbox will not allow insecure WebSocket connections,it must be Secure WebSocket.

    Change the broker URL to start with wss:// instead of mqtt:// and ensure that the correct port is used.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search