Search code examples
javascriptnext.jsmqttvite

MQTT.js not working inside the Vite (React with TypeScript) and inside the Next.js app


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

Solution

  • 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.