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
As hashed out in the comments.
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 bewss://
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
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.
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.