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
- Connecting to MQTT broker from Javascript -> Worked
- Connecting to MQTT broker from Vite (React) -> Not-Worked
- Connecting to MQTT broker from Next.js -> Not-Worked
2
Answers
Thank you so much :). The answer is very useful.
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 ofmqtt://
and ensure that the correct port is used.