The vue-paho-mqtt
plugin provides a convenient way to use the Eclipse Paho MQTT JavaScript client with Vue 3.
This plugin allows you to connect to a MQTT broker and subscribe to topics in your Vue app. It uses paho-mqtt to connect to the broker and provides several useful features such as auto-reconnect, message handlers, and error notifications.
- Installation
- Setup
- Options
- Notification Alerts
- Global MQTT client instance: $mqtt
- Usage Example
- Contributing
- License
- Credits
- Changelog
- Security
Install the package using npm:
npm install vue-paho-mqtt
To use the plugin, you need to create an instance of it and pass it to the use
function:
// src/main.ts
import App from './App.vue';
import { createApp } from 'vue';
import { createPahoMqttPlugin } from 'vue-paho-mqtt';
createApp(App)
.use(
createPahoMqttPlugin({
PluginOptions: {
autoConnect: true,
showNotifications: true,
},
MqttOptions: {
host: 'localhost',
port: 9001,
clientId: `MyID-${Math.random() * 9999}`,
mainTopic: 'MAIN',
},
}),
)
.mount('#app');
Quasar Framework (quasar boot)
import { boot } from 'quasar/wrappers';
import { createPahoMqttPlugin } from 'vue-paho-mqtt';
export default boot(({ app }) => {
app.use(
createPahoMqttPlugin({
PluginOptions: {
autoConnect: true,
showNotifications: true,
},
MqttOptions: {
host: 'localhost',
port: 9001,
clientId: `MyID-${Math.random() * 9999}`,
mainTopic: 'MAIN',
},
}),
);
});
Nuxt3 (nuxt plugins)
import { createPahoMqttPlugin } from 'vue-paho-mqtt';
export default defineNuxtPlugin({
name: 'vue-paho-mqtt',
enforce: 'pre',
async setup(nuxtApp) {
nuxtApp.vueApp.use(
createPahoMqttPlugin({
PluginOptions: {
autoConnect: true,
showNotifications: true,
},
MqttOptions: {
host: 'localhost',
port: 9001,
clientId: `MyID-${Math.random() * 9999}`,
mainTopic: 'MAIN',
},
}),
);
},
hooks: {
'app:created'() {
const nuxtApp = useNuxtApp();
},
},
});
You can configure the plugin by passing an object with the following options to createPahoMqttPlugin
:
-
showNotifications
(boolean
, default:true
) - Whether to show error and success notifications. -
autoConnect
(boolean
, default:true
) - Whether to automatically connect to the broker when the plugin is initialized.
You can configure the MQTT client by passing an object with the following options to createPahoMqttPlugin
:
-
host
(string
, default:"localhost"
) - The hostname or IP address of the MQTT broker. -
port
(number
, default:9001
) - The port number of the MQTT broker. -
useSSL
(boolean
, default:false
) - Whether to use SSL when connecting to the broker. -
clientId
(string
, default:"ClientID-${Math.random() * 9999}}"
) - The client identifier to use when connecting to the broker. -
username
(string
, default:""
) - The username to use when connecting to the broker. -
password
(string
, default:""
) - The password to use when connecting to the broker. -
mainTopic
(string
, default:"MAIN"
) - If enaled, the topic that will be prepended to the topic specified during the $mqtt.publish and $mqtt.subscribe (can be manually disabled in $mqtt.publish and $mqtt.subscribe). -
enableMainTopic
(boolean
, default:true
) - Enables usage of the main topic. -
watchdogTimeout
(number
, default:30000
) - The time in milliseconds to wait for a connection to the broker before timing out. -
reconnectTimeout
(number
, default:5000
) - The time in milliseconds to wait before attempting to reconnect to the broker after a disconnection. -
keepAliveInterval
(number
, default:60000
) - The server disconnects this client if there is no activity for this number of milliseconds. -
cleanSession
(boolean
, default:true
) - Whether to delete the server persistent state on a new connection.
The MQTT protocol provides Quality of Service (QoS) levels to control the reliability of message delivery between a publisher and a subscriber. Additionally, it provides the ability to retain messages, allowing subscribers to receive messages even if they connect after the message has been published.
The following are the MQTT QoS and retention options available for publishing messages:
type | Option | QoS Level | Retain |
---|---|---|---|
string | B | 0 | false |
string | Br | 0 | true |
string | Q | 1 | false |
string | Qr | 1 | true |
string | F | 2 | true |
string | Fnr | 2 | false |
-
B: QoS 0, non-retained message. The message is delivered at most once, and the broker does not store the message for future subscribers.
-
Br: QoS 0, retained message. The message is delivered at most once, and the broker stores the message for future subscribers.
-
Q: QoS 1, non-retained message. The message is delivered at least once, and the broker stores it until the publisher receives an acknowledgment from the subscriber.
-
Qr: QoS 1, retained message. The message is delivered at least once, and the broker stores it until the publisher receives an acknowledgment from the subscriber. The broker also stores the message for future subscribers.
-
F: QoS 2, retained message. The message is delivered exactly once, and the broker stores it for future subscribers.
-
Fnr: QoS 2, non-retained message. The message is delivered exactly once, and the broker does not store it for future subscribers.
type MqttMode = 'B' | 'F' | 'Q' | 'Qr' | 'Br' | 'Fnr';
$mqtt.publish('test/topic', 'Hello, world!', 'Fnr');
The Vue Paho MQTT plugin comes with built-in notifications using SweetAlert2 library to display the notification alerts. This library is already installed with the plugin.
PluginOptions.showNotifications
(boolean
, default:true
) - Whether to show error and success alert notifications.
createPahoMqttPlugin({
PluginOptions: {
showNotifications: true,
...
}
...
On | Icon | Title | Content | Timer |
---|---|---|---|---|
Connection Success | success | "Connected" | "MQTT Connected" | 1500 |
Connection Failure | error | "Mqtt Error" | "MQTT failed to connect" | - |
Connection Timeout | error | "Mqtt Error" | "Broker connection timed out" | - |
Connection Lost | error | "Mqtt Error" | "MQTT connection lost" | - |
Disconnect Error | error | "Error" | catch(error) =>Â error.message | - |
Connect Error | error | "Error" | catch(error) =>Â error.message | - |
Connect to the MQTT broker. Shows a dialog notification in case of error if the plugin is configured to do so.
Custom callbacks can be passed to the connect function. Such as onConnect
, onFailure
, onConnectionLost
, onMessageArrived
.
onConnect()
: resolves the promise totrue
if the connection was successful.onFailure()
: rejects the promise tofalse
if the connection was unsuccessful.onConnectionLost()
: returns an response object with the following properties:errorCode
: the error code.
onMessageArrived()
: returns a message object with the following properties:payloadString
: the message payload as a string.destinationName
: the name of the topic that the message was published to.
Note: Inside the 'subscribe' function a function is passed to the 'onMessageArrived' callback. This function is used to parse the message payload and return the parsed message inside the subscribe function where it is called. You don't really need to handle arriving messages in the 'onMessageArrived' callback.
const connect: ({
onConnect?: ((...args: unknown[]) => unknown) | undefined;
onFailure?: ((...args: unknown[]) => unknown) | undefined;
onConnectionLost?:
| ((
responseObject: {
errorCode: number;
},
...args: unknown[]
) => unknown)
| undefined;
onMessageArrived?:
| ((
message: {
payloadString: string;
destinationName: string;
},
...args: unknown[]
) => unknown)
| undefined;
}) => Promise<boolean>;
// Composition API
import { $mqtt } from 'vue-paho-mqtt';
$mqtt.connect();
// Options API
this.$mqtt.connect();
// or use it with async/await
const result = await $mqtt.connect();
// result will return "true" if the connection was successful
Callback | When | Return |
---|---|---|
onConnect |
successfully connected to the mqtt broker | - |
onFailure |
failed to connect to the mqtt broker | - |
onConnectionLost |
disconnected or connection lost connection | responseObject: {errorCode: number} |
onMessageArrived |
message arrived from one of the subscribed topics | message: {payloadString: string;destinationName: string;} |
$mqtt.connect({
onConnect: () => {
console.log('Mqtt connected');
},
onFailure: () => {
console.log('Mqtt connection failed');
},
onConnectionLost: (error: any) => {
console.log('Error:', error.message);
},
onMessageArrived: (message: {
payloadString: string;
destinationName: string;
}) => {
console.log(
'Message Arrived:',
message.payloadString,
message.destinationName,
);
},
});
Disconnect from the mqtt broker. Shows a dialog notification in case of error if the plugin is configured to do so.
const disconnect: () => Promise<boolean>;
// Composition API
import { $mqtt } from 'vue-paho-mqtt';
$mqtt.disconnect();
// Options API
this.$mqtt.disconnect();
// or use it with async/await
const result = await $mqtt.disconnect();
// result will return "true" if the disconnection was successful
It is used to subscribe to the topic specified, and to define the function to call when the specified topic recieves a message.
param | type | explanation | default |
---|---|---|---|
topic |
string |
MQTT topic to subscribe (ie: 'my/test/topic') | - |
onMessage |
function |
Arrow function with a parameter to be fired when a message arrives to the specified topic | - |
useMainTopic |
boolean |
main topic defined in the MQTT Options will be prepended to the topic specified | true |
const subscribe: (
topic: string,
onMessage: (data: string, ...args: unknown[]) => unknown,
useMainTopic?: boolean,
) => void;
// if the enableMainTopic is true, subscribe to 'MAIN/my/topic'
this.$mqtt.subscribe('my/topic', (data: string) => {
console.log(data, 'recieved');
});
// even if the enableMainTopic is true, subscribe to 'my/topic'
this.$mqtt.subscribe(
'my/topic',
(data: string) => {
console.log(data, 'recieved');
},
false,
);
import { $mqtt } from 'vue-paho-mqtt';
$mqtt.subscribe('my/topic', (data: string) => {
console.log(data, 'recieved');
});
Used to publish string data to the topic specified.
const publish: (
topic: string,
payload: string,
mode: MqttMode,
useMainTopic?: boolean,
) => void;
param | type | explanation | default |
---|---|---|---|
topic |
string |
MQTT topic to publish (ie: 'my/test/topic') | - |
payload |
string |
string payload to send | - |
mode |
MqttMode |
See MQTT Quality of Service (QoS) and Retention Options for Publish for detailed explanation for mqtt mode options. ["B" | "F" | "Q" | "Qr" | "Br" | "Fnr" ] |
- |
useMainTopic |
boolean |
main topic defined in the MQTT Options will be prepended to the topic specified | true |
// if the enableMainTopic is true, publish to 'MAIN/my/topic'
// 'Fnr' => Qos: 2 , retained: false
this.$mqtt.publish('test/topic', 'Hello, world!', 'Fnr');
// even if the enableMainTopic is true, publish to 'my/topic'
// 'B' => Qos: 0 , retained: false
this.$mqtt.publish('test/topic', 'Hello, world!', 'B', false);
// if the enableMainTopic is true, publish to 'MAIN/my/topic'
// 'Qr' => Qos: 1 , retained: true
this.$mqtt.publish('test/topic', 'Hello, world!', 'Qr');
// payload: "Hello, world!"
import { $mqtt } from 'vue-paho-mqtt';
$mqtt.publish('test/topic', 'Hello, world!', 'Qr');
Get or set the host parameter from the MQTT Options.
const host: (e?: string) => string;
$mqtt.host(); // ie: "localhost"
$mqtt.host('192.168.0.1');
<template>
<label>MQTT host: {{ $mqtt.host() }}</label>
</template>
onMounted(() => {
console.log(this.$mqtt.host());
});
import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
console.log($mqtt.host());
});
Get or set the port parameter from the MQTT Options.
const port: (e?: number) => number;
$mqtt.port(); // ie: 9001
$mqtt.port(1234);
<template>
<label>MQTT port: {{ $mqtt.port() }}</label>
</template>
onMounted(() => {
console.log(this.$mqtt.port());
});
import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
console.log($mqtt.port());
});
Get or set the path parameter from the MQTT Options.
const path: (e?: string) => string;
$mqtt.path(); // ie: "/mqtt"
$mqtt.path('/ws/mqtt');
<template>
<label>MQTT path: {{ $mqtt.path() }}</label>
</template>
onMounted(() => {
console.log(this.$mqtt.path());
});
import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
console.log($mqtt.path());
});
Get or set the username parameter from the MQTT Options.
const username: (e?: string) => string;
$mqtt.username(); // ie: ""
$mqtt.username('testUsername');
<template>
<label>MQTT username: {{ $mqtt.username() }}</label>
</template>
onMounted(() => {
console.log(this.$mqtt.username());
});
import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
console.log($mqtt.username());
});
Caution
Exposing the password to the client can cause security issues if not used properly.
Get or set the password parameter from the MQTT Options.
const password: (e?: string) => string;
$mqtt.password(); // ie: ""
$mqtt.password('secret');
<template>
<label>MQTT password: {{ $mqtt.password() }}</label>
</template>
onMounted(() => {
console.log(this.$mqtt.password());
});
import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
console.log($mqtt.password());
});
Get or set the clientId parameter from the MQTT Options.
const clientId: (e?: string) => string;
$mqtt.clientId(); // ie: "MyID-234"
$mqtt.clientId('MyNewClientId');
<template>
<label>MQTT client id: {{ $mqtt.clientId() }}</label>
</template>
onMounted(() => {
console.log(this.$mqtt.clientId());
});
import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
console.log($mqtt.clientId());
});
Get or set the mainTopic parameter from the MQTT Options.
const mainTopic: (e?: string) => string | undefined;
$mqtt.mainTopic(); // ie: "MyID-234"
$mqtt.mainTopic('MyNewClientId');
<template>
<label>MQTT mainTopic: {{ $mqtt.mainTopic() }}</label>
</template>
onMounted(() => {
console.log(this.$mqtt.mainTopic());
});
import { onMounted } from 'vue';
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
console.log($mqtt.mainTopic());
});
Used to unsubscribe from the topic specified
const unsubscribe: (topic: string, useMainTopic?: boolean) => void;
param | type | explanation | default |
---|---|---|---|
topic |
string |
MQTT topic to unsubscribe (ie: 'my/test/topic') | - |
useMainTopic |
boolean |
main topic defined in the MQTT Options will be prepended to the topic specified | true |
// if the enableMainTopic is true, unsubscribe from 'MAIN/my/topic'
$mqtt.unsubscribe('test/topic');
// even if the enableMainTopic is true, unsubscribe from 'my/topic'
$mqtt.unsubscribe('test/topic', false);
Used to unsubscribe from all the topics subscribed previously.
const unsubscribeAll: () => void;
$mqtt.unsubscribeAll();
Used to get the status of the mqtt connection.
type MqttStatus =
| 'connected'
| 'disconnected'
| 'connecting'
| 'error'
| 'lost'
| null;
const status: () => MqttStatus;
$mqtt.status(); // ie: "connected"
<template>
<label>MQTT Status: {{ $mqtt.status() }}</label>
</template>
onMounted(() => {
console.log($mqtt.status());
});
mounted() {
// Connect to the mqtt broker
this.$mqtt.connect();
// Subscribe to a topic
this.$mqtt.subscribe("test/topic", (message: string) => {
console.log("Received message:", message);
});
// Publish a message
this.$mqtt.publish("test/topic", "Hello, world!", "F");
// Disconnect from the broker
this.$mqtt.disconnect();
}
<script setup lang="ts">
import { onMounted } from "vue";
import { $mqtt } from 'vue-paho-mqtt';
onMounted(() => {
// Connect to the mqtt broker
$mqtt.connect();
// Subscribe to a topic
$mqtt.subscribe("test/topic", (message: string) => {
console.log("Received message:", message);
});
// Publish a message
$mqtt.publish("test/topic", "Hello, world!", "F");
// Disconnect from the broker
$mqtt.disconnect();
});
</script>
Contributions to the project is highly appreciated. If you have any suggestions/questions/requests please consider opening an issue. If you want to contribute to the project, fixing an open issue is greatly recommended and appreciated. To see the all contribution rules please check the contribution rules.
This project is licensed under MIT License
if you want to see more, please check LICENSE for more information.
This project is created and actively maintained by kaandesu and EgeOnder
Maintainer | ||
---|---|---|
kaandesu | [email protected] | - |
EgeOnder | 40398628 [email protected] | @EgeOnder23 |
Please see CHANGELOG for more information on what has changed recently.
The security policy of the project can be found in SECURITY.md. If you find any security issues, please refer to the policy. Thank you.