skip to Main Content

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");
//....

2

Answers


  1. As hashed out in the comments.

    1. You can not load unsecure content from a page loaded over HTTPS. This means if the page loads over https://, then the WebSocket Connection must be wss://

    2. The browser will not ask you to approve a self signed or untrusted certificate when making WebSocket connections like it does when trying to navigate to HTTPS site with a certificate not signed by a trusted CA.

    You have 2 choices

    1. You manually import your self signed certificate into the browsers trust store. This is only a valid option for dev/test as it would need be done to ALL browsers that ever access the site.
    2. You get a certificate from a trusted CA (e.g. LetsEncrypt) and use for both the HTTP server and the Broker (or you get get something like Nginx to proxy for the broker and to TLS termination for both)
    Login or Signup to reply.
  2. 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 Filesmosquittocertca.crt
    keyfile C:Program Filesmosquittocertserver.key
    certfile C:Program Filesmosquittocertserver.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.

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