Connecting Nuxt.js to MQTT

2 minute read


In this blog post I’ll talk about how to connect Nuxt.js to MQTT.


MQTT has become the de facto of IoT. According to the statistics after HTTP it is the most used protocol for the connectivity layer of IoT devices. In this blog post you’ll learn how to combine this amazing protocol with Nuxt.js.

Getting Started


This tutorial assumes that you already know what is Vue.js. If don’t you can read about it here.

Installing Nuxt.js

First install Nuxt.js:

As stated in the docs installing is pretty simple.

$ vue init nuxt-community/starter-template <project-name>

Then simply install the dependencies.

$ cd <project-name>
$ npm install
$ npm run dev

Now you should be able to view the the site on http://localhost:3000.

Nuxt plugins

Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root vue.js application. This is especially helpful when using your own libraries or external modules.

For more information about Nuxt.js plugins you can read about here.

So lets use it!

Add required dependencies

$ npm i --save vue-mqttsocket

This is a vue plugin that registers mqtt on Vue instance globally we’ll see how to use it later.

Create a nuxt plugin

Create a new nuxt plugin by adding vue-mqttsocket plugin in plugins/mqtt.js .

In order to do so, put the following content in it.

import Vue from 'vue'

if (process.browser) {
  const mqtt = require('vue-mqttsocket').default
  Vue.use(mqtt, {uri: 'ws://localhost:8083/mqtt'})

Make sure to replace the uri with your MQTT broker address.

Also, add the section below in the end of nuxt.config.js.

 plugins: [

This will register the plugin in the nuxt.


Now you can register it in everypage that you need MQTT in a very simple way. All you have to do is to put the code below in the mounted section of your page:

async mounted() {
    this.$mqtt = await this.$mqtt

If you were successful you’ll be able to see a MQTT connected! message in the log of your browser.

Now publishing and subscribing is super simple.

To publish:

this.$mqtt.publish('mytopic', 'Hello MQTT from NUXT')

To subscribe:

this.$mqtt.on('message', (topic, message, packet) => {
    // Your code to deal with packets arrived