
Mosquitto is a popular open-source message broker that supports WebSockets, allowing for bidirectional, real-time communication between clients and servers.
To enable WebSocket support in Mosquitto, you need to add the `websockets` package to your Mosquitto configuration file.
Mosquitto's default configuration file is located at `/etc/mosquitto/mosquitto.conf`, and you can add the `websockets` package by including the following line: `allow_anonymous true; websockets true;`.
This will enable WebSocket support, allowing clients to connect using the WebSocket protocol.
Worth a look: What Are Websockets
Why Use Mosquitto WebSocket?
Mosquitto WebSocket is a powerful tool for web applications. It allows web browsers to connect to the Mosquitto MQTT broker using WebSockets, which provides several advantages.
One of the main benefits of using Mosquitto WebSocket is browser compatibility. Web browsers don't support native MQTT, but they do support WebSockets, making it possible to leverage the MQTT protocol in web applications.
Using Mosquitto WebSocket makes it easier to traverse network boundaries. WebSocket connections typically use standard web ports, which are usually open in firewalls, allowing for smoother communication.
The Mosquitto install packages for both Windows and Linux support WebSockets out of the box. This means you don't need to compile anything special to get started.
With Mosquitto WebSocket, you can receive MQTT data directly into a web browser, making it a great option for displaying MQTT data. This is especially useful if you're looking to create a user-friendly interface for your MQTT data.
Configuration
To configure Mosquitto for WebSockets, you'll need to edit the mosquitto.conf file, which is typically found in the /etc/mosquitto/mosquitto.conf directory on Linux systems, or C:\Program Files\mosquitto\mosquitto.conf on Windows.
You can open the mosquitto.conf file with your preferred text editor and add the necessary lines to enable WebSockets. For example, you can add the following lines to set the Mosquitto WebSocket port:
- listener 9001
- protocol websockets
- allow_anonymous true
Please note that setting allow_anonymous true is a highly insecure option, and you should always use proper authentication mechanisms in a real environment.
Configuring Broker for MacOS

To configure Mosquitto MQTT broker over WebSockets on MacOS, you'll need to create a mosquitto.conf file. This file is where you'll add the Mosquitto websocket config.
You can run the Mosquitto installer and follow the instructions to install Mosquitto in Docker. Alternatively, you can execute the following command to run the broker: `docker run -p 1883:1883 -p 8883:8883 -v /path/to/mosquitto.conf:/etc/mosquitto/mosquitto.conf -d mosquitto:latest`.
To test the setup, you can open `/etc/mosquitto/mosquitto.conf` with your preferred text editor and add the Mosquitto websocket config.
Configure for Windows
To configure Mosquitto MQTT broker over WebSockets for Windows, you'll need to locate the mosquitto.conf file, which can typically be found in C:\Program Files\mosquitto.
Open the mosquitto.conf file with your preferred text editor and add the following lines to set the Mosquitto WebSocket port to enable WebSockets.
The mosquitto.conf file can be found in C:\Program Files\mosquitto, so make sure to navigate to that directory first.
Configure on Your Broker
To configure Mosquitto to use WebSockets, you need to edit the mosquitto.conf file. This file is located at /etc/mosquitto/mosquitto.conf on both Linux (Debian-based) and Linux (RedHat-based) systems.

The mosquitto.conf file can also be found at C:\Program Files\mosquitto\mosquitto.conf on Windows systems.
To enable WebSockets, you need to add the following lines to the "Listeners" section: allow_anonymous true and listener websocket 9001.
Here's a summary of the necessary changes:
Save the file and restart the Mosquitto service.
Serving Web Pages
Serving web pages is an option when websockets are enabled on Mosquitto. You can use this feature to serve standard HTML web pages.
To get started, create a folder to store your web pages, for example, "web". Then, add the following entry into the Mosquitto configuration file without a trailing slash.
The port to use for connecting to the page is the same port you're using for websockets.
Here are some resources to learn more about serving web pages with Mosquitto:
- TCP/IP protocol suite explained
- Publishing MQTT Data to a Web Page
- MQTT protocol Overview
- Client Objects-Working with The Python MQTT Client
- MQTT-SN (MQTT for Sensor networks) Working Notes
Testing and Setup
To test Mosquitto WebSockets, you can use the MQTT Explorer tool. This visual interface allows you to test your setup and see if it's working correctly.
You'll need to install MQTT Explorer and start Mosquitto as described in the sections above. Then, fill in the MQTT connection details in the MQTT Explorer application, including the host name, port, and other settings. Click the CONNECT button to establish a connection.
In the terminal window, Mosquitto should show information about the new connection. You can then create topics, publish MQTT messages, and see the results in the MQTT Explorer application.
Consider reading: Websocket Create Connection
Configure Broker over Docker
To configure a Mosquitto MQTT broker over WebSockets for Docker, you'll need to follow a few simple steps. If you want to change Mosquitto configuration after starting the container, just edit the mosquitto.conf file.
You can restart the container using the `docker restart mos1` command. This will update the configuration changes you made to the mosquitto.conf file.
Test Linux
To test your Linux setup, start by opening the mosquitto.conf file and adding the necessary content to enable logging. Add the following to the "Logging" section.

You'll need to run Mosquitto with the flag "-c" to point to the configuration file you just created. The command to do this is inserted into the terminal and clicked Enter.
This will start the MQTT broker with both a standard MQTT protocol listener on port 1883 and a WebSocket listener on port 8080. You should see these listeners running.
To test MQTT over WebSockets, you can use the tool MQTT X. Download the installer for your OS and install it.
Open MQTT X and click New Connection. In the Connection section, enter the Host Name, which is the IP Address where you installed the Mosquitto broker.
Testing Setup
Testing Setup can be a bit tricky, but don't worry, I've got you covered. To test MQTT over WebSockets, you can run Mosquitto and point it to the configuration file you've modified. This should start the MQTT broker with a standard MQTT protocol listener on port 1883 and a WebSocket listener on port 8080.

You can also use the MQTT Explorer to test your setup. First, install the MQTT Explorer and start Mosquitto as described in the sections above. Then, start the MQTT Explorer application and fill in the MQTT connection details, including the host name, port, and username.
To test MQTT over secure WebSockets, you can use the mosquitto_pub and mosquitto_sub command-line utilities provided by Mosquitto. This allows you to subscribe to a topic over secure WS and publish to a topic over secure WS.
Another tool you can use to test MQTT over WebSockets is MQTT X. Simply download the appropriate installer for your OS, install it, and open the tool to create a new connection. Enter the host name, port, and other details as required.
To ensure that you've successfully enabled WebSockets in Mosquitto, you can run Mosquitto with the flag "-c" and point it to the configuration file you've created. This should show you that the MQTT broker starts with a standard MQTT protocol listener and a WebSocket listener running on port 8080.
You can also use the MQTT box tool, a Google Chrome extension, to test your setup. This tool supports both websockets and secure websockets, although you may have difficulty with SSL if you use your own CA.
A fresh viewpoint: When to Use Websockets
Security and Encryption
Securing your Mosquitto WebSocket connection is crucial for protecting your data. Use TLS to ensure the confidentiality and integrity of your data.
To secure your WebSockets, revisit the certificates you generated with Let's Encrypt. This is because WebSockets can introduce vulnerabilities if left unsecured.
You can modify the mosquitto.conf file to include the necessary TLS configuration. After saving the changes, restart Mosquitto to apply the new settings.
Using WebSockets over TLS requires configuring the broker to use TLS. This involves modifying the mosquitto.conf file and adding a new listener for the secure connection.
To use webSockets over TLS, you need to add a new listener to the mosquitto.conf file. The extra listener should use websockets and the ssl configuration should apply to it.
You can use port 8081 for the secure connection. On the Python client, add the client.tls_set() command to tell it to use SSL.
Improving security by configuring WebSockets over TLS involves several steps. First, get SSL/TLS Certificates using Certificate Authority (CA) certificates or create your own self-signed certificates.
Curious to learn more? Check out: Client Websocket C#
Modify the Settings File by accessing the `mosquitto.conf` file and inserting the provided code snippet to set up WebSockets over SSL/TLS. This will enable the secure connection.
Restart Mosquitto for the new settings to be applied. This is a crucial step in configuring WebSockets over TLS.
Using a web-based MQTT client can help you test the secure WebSocket connection.
Client Examples and Tools
To use websockets with the Paho Python client, you need to specify the transport as 'websockets' and set the port to 9001. This is done by using the command client=paho.Client(“control1”,transport=’websockets’).
You can use the MQTT box tool in Google Chrome to test websockets, but be aware that you may have difficulty with SSL if you use your own CA.
MQTT explorer also supports websockets and SSL, giving you options for testing your websocket setup.
For your interest: Websocket Use Cases
Python Client Example
To use websockets with the Python client, you need to specify the transport as 'websockets' when creating a new client object. This is done by adding the transport parameter to the client creation command, like this: client=paho.Client("control1", transport='websockets').
Readers also liked: Websocket Client in Java

You should also set the port to the WebSocket port, which is 9001. This is a crucial step to ensure that the client is communicating over websockets.
The Python demo script provided shows how to publish and subscribe using websockets. Running this script will demonstrate the use of websockets, but it's worth noting that there is no clear indication that the client is using websockets as opposed to standard MQTT.
JavaScript Client
To run a JavaScript client for MQTT, you need to create a web page and add your JavaScript code.
The client is meant to be run in a browser, making it an ideal choice for web-based applications.
For detailed usage examples, scripts, and download links, check out the tutorial on Understanding and using The JavaScript MQTT Client With Websockets.
You can use any MQTT client that supports WebSockets to connect to ws://yourhost URI, as long as Mosquitto is setup correctly.
Mosquitto can be configured to enable WebSockets and regular HTTP connections by modifying the mosquitto.conf file.
Take a look at this: Javascript Websocket
Apache with Websocket support

Apache with Websocket support can be achieved by using the mod_websocket_mosquitto module, which can be downloaded from https://github.com/willem4ever/mod_websocket_mosquitto.
The instructions to compile and install this module are pretty straightforward, and you'll end up with something like the following in your Apache configuration.
You can use this module to authenticate users with MQTT/Mosquitto, which allows for different access rights based on different certificates for different topics.
Troubleshooting and Best Practices
Always use secure connections (wss://) on public or untrusted networks to keep your data safe. This is a no-brainer, especially when dealing with sensitive information.
Don't use generic Client IDs - go for something unique that identifies your device or client. This will make it easier to spot and manage connected clients.
Limit retained messages to avoid bombarding newly connected clients with old news. This will help keep your system running smoothly and prevent unnecessary congestion.
Use rate limiting to prevent clients from flooding your broker with too many messages. This is like having a bouncer at a club, ensuring everything runs smoothly and preventing chaos.
Regularly audit connected clients to catch any suspicious activity or issues. This is a good habit to get into, especially if you're running a large-scale system.
Use MQTT's Last Will and Testament (LWT) feature to alert other clients if a device goes offline. This is a great way to keep track of your devices and ensure everything is working as expected.
Reported Issues
I've experienced issues with Javascript websocket connections to Mosquitto broker, where the ESP8266 would disconnect every time I connected using Javascript over websockets.
The problem was specifically with the Windows Mosquitto broker version 2.03.
A new version, v2.0.4, was released on December 22, 2020, which included a bug fix that addressed this issue.
The bug fix specifically mentioned "Fix websockets connections blocking non-websockets connections on Windows."
Additional reading: Webrtc Websocket Connections
Best Practices in a Nutshell
Always use secure connections (wss://) when hopping onto public or untrusted networks. This will help keep your data safe from prying eyes.
Keep your TLS certificates fresh and updated to avoid any security issues. Trust me, it's a hassle to deal with expired certificates.
Use unique Client IDs to identify your connected clients. This will make it easier to spot and manage them, especially when you have a large number of devices connected.
Limit retained messages to avoid bombarding newly connected clients with old news. You don't want to overwhelm them with unnecessary information.
Use prefixes to categorize different devices or locations in your topics. This will keep your topics clear and logical, making it easier to navigate.
Rate limiting is your friend - it's like the bouncer at a club, ensuring no client gets too rowdy and floods your broker with a barrage of messages.
Audit your connected clients regularly to ensure everything is running smoothly. If something seems off, don't hesitate to disconnect and investigate.
Wrap Up
It's essential to prioritize security in our IoT ecosystem, where every connection and data packet deserves respect and caution.
The technical steps of setting up WebSockets and wrapping them in TLS are crucial, but they're just one facet of the story.
Fostering a culture of security is about guaranteeing the sanctity of IoT conversations, preventing eavesdropping, and ensuring the foundation of our ecosystem is built on trust and reliability.
In our quest for seamless communication through MQTT, let's ensure that this act of communication remains both secure and sacred.
By following the roadmap to navigate MQTT over WebSockets, you'll be well-prepared to tackle any challenges that come your way.
Now that you've successfully configured your Mosquitto broker, you can start exploring your own IoT MQTT projects and create something truly awesome.
Remember, with great power comes great responsibility, so be sure to keep your IoT setup secure and up-to-date.
Featured Images: pexels.com


