Search code examples
reactjsnext.jswebsocketmqttmqtt.js

Connecting to MQTT with secure websocket in Nextjs


I use this code to connect to my own mqtt broker with socket from Nextjs and it works fine

import mqtt, { MqttClient } from "mqtt";
//...
mqtt.connect("ws://IPADDRESS:1884");
//....

Now, I want to change it to secure websocket (wss) and I have CRT file, but don't know how to add it.

import mqtt, { MqttClient } from "mqtt";
//...
mqtt.connect("wss://IPADDRESS:1884");
//....

Solution

  • You can use the same certificate that you used for the website, using it for the web socket too. For example, if the website URL is https://test.com you should connect to test.com with wss (wss://test.com:1884) and use the same SSL certificate in your brocker. For the Mosquitto the config file should be like below.

    listener 1883
    
    allow_anonymous true
    
    
    listener 1884
    protocol websockets
    socket_domain ipv4
    
    cafile C:\Program Files\mosquitto\cert\ca.crt
    keyfile C:\Program Files\mosquitto\cert\server.key
    certfile C:\Program Files\mosquitto\cert\server.crt
    tls_version tlsv1.2
    

    The port 1883 use for Mqtt connection without TLS, for web socket use port 1884 and it needs SSL certificate.

    The certificate files should be on the server, they are:

    ca.crt is the CA file of your SSL certificate

    server.key is the private key

    server.crt is the CRT file of your SSL certificate

    When you connect to the web socket from your website because it is HTTPS and you connect to the same URL for the web socket, it uses the same SSL certificate and doesn't need to import it to the browser.