Connect with JavaScript (Node.js)
Use MQTT.js with the token authentication mode configured on a broker.
Below is an example using MQTT.js ↗ with the TOKEN authentication mode configured on a broker. The example assumes you have Node.js ↗ v16 or higher installed on your system.
Make sure to set the following environmental variables before running the example:
- BROKER_URI(e.g.- mqtts://YOUR-BROKER.YOUR-NAMESPACE.cloudflarepubsub.com)
- BROKER_TOKENwith a valid auth token
- BROKER_TOPICto publish to - for example,- hello/world
Before running the example, make sure to install the MQTT library:
npm i mqttyarn add mqttpnpm add mqttCopy the following example as example.js and run it with node example.js.
const mqtt = require("mqtt");
// Specify MQTT broker URI: mqtts://<broker name>.<namespace>.cloudflarepubsub.comconst uri = check_env(process.env.BROKER_URI);
// Any username and your token from the /brokers/YOUR_BROKER/credentials endpoint// The token should be the base64-encoded JWT issued by the Pub/Sub APIconst username = "anything";const password = check_env(process.env.BROKER_TOKEN);
// Specify a topic name to subscribe to and publish onlet topic = check_env(process.env.BROKER_TOPIC);
// Configure and create the MQTT clientconst client = mqtt.connect(uri, {  protocolVersion: 5,  port: 8883,  clean: true,  connectTimeout: 2000, // 2 seconds  clientId: "",  username,  password,});
// Emit errors and exitclient.on("error", function (err) {  console.log(`⚠️  error: ${err}`);  client.end();  process.exit();});
// Connect to your brokerclient.on("connect", function () {  console.log(`🌎 connected to ${process.env.BROKER_URI}!`);  // Subscribe to a topic  client.subscribe(topic, function (err) {    if (!err) {      console.log(`✅ subscribed to ${topic}`);      // Publish a message!      client.publish(topic, "My first MQTT message");    }  });});
// Start waiting for messagesclient.on("message", async function (topic, message) {  console.log(`received a message: ${message.toString()}`);
  // Goodbye!  client.end();  process.exit();});
// Return variable or throw errorfunction check_env(env) {  if (!env) {    throw "BROKER_URI, BROKER_TOKEN and BROKER_TOPIC must be set.";  }
  return env;}Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark