denoflare-mqtt demo

Broker: .cloudflarepubsub.com Topic: Password:

This is a demo of denoflare-mqtt, a tiny isomorphic MQTTv5 client running in the browser.

Subscribe and publish to a topic on your broker from standard JavaScript.

The library only implements MQTTv5, and only the features currently implemented by Cloudflare Pub/Sub.

Browser import (ESM) import { MqttClient } from 'https://cdn.jsdelivr.net/gh/skymethod/denoflare@denoflare-mqtt-v0.0.1/npm/denoflare-mqtt/esm/main.js'; // esm module from npm package source served from jsdelivr with the correct mime type for browsers
Deno import (also supports 'mqtts' over tcp!) import { MqttClient } from 'https://raw.githubusercontent.com/skymethod/denoflare/denoflare-mqtt-v0.0.1/common/mqtt/mod_deno.ts';
NPM See the denoflare-mqtt NPM package readme
Usage example
// connect, publish a message, then disconnect

const protocol = 'wss'; // also supports 'mqtts' in Deno
const hostname = 'my-broker.my-namespace.cloudflarepubsub.com';
const port = 8884; // 8883 for 'mqtts' in Deno
const maxMessagesPerSecond = 10; // current pub/sub beta limitation

const topic = 'my-topic';
const payload = 'hello world!';

const password = 'MY_JWT_TOKEN';

const client = new MqttClient({ 
   hostname, port, protocol, 
   maxMessagesPerSecond 
});

client.onMqttMessage = message => {
   if (message.type === DISCONNECT) {
      console.log('disconnect', message.reason);
   }
};

console.log('connecting');
await client.connect({ password });

const { clientId, keepAlive } = client;
console.log('connected', { clientId, keepAlive });

console.log(`publishing`);
await client.publish({ topic, payload });

console.log('disconnecting');
await client.disconnect();

console.log('disconnected');