Search code examples
node.jsaws-lambdamqttmosquitto

Connect non-AWS MQTT broker in Lambda with NodeJS 14+


I was using AWS Lambda function to publish MQTT messages to a Mosquitto Broker hosted outside of AWS.

I was using Node mqqt plug-in. Everything was working well in Node JS 12. Now migrating to Node JS 14 and the the function

on(“connect”) does no longer seem to be working. The Broker URL and credentials have not changed, but the I am not getting a connection to the broker. Also the on(“error”) does not return anything.

After AWS Lambda stopped supporting Node 12, need to migrate.

Any suggestions?

Same behavior btw with Node JS 18.

Below is a fragment from my code. Sensitive info replaced with xxx.

client.on("connect",function(connack) is no longer working when deploying this function with NodeJs 14+.

Another detail that might be important. When I run this function locally out of VSCode with the AWS Plugin and Docker in the background, client.on("connect",function(connack) seems to be working.

'use strict';
 
const AWS = require('aws-sdk');

const mqtt = require('mqtt');

const client  = mqtt.connect('mqtt://xxx:1883',{
    username: 'xxx'
})

const MqttTargetTopic = 'xxx';
const MqttCheckTopic  = 'xxx';

exports.handler = function(event, context, callback) {
    context.callbackWaitsForEmptyEventLoop = false;
    
    // Check that the messages only from the whitelisted devices are re-routed
    if (event.devi != "xxx" && event.devi != "xxx" && event.devi != "xxx") {
        
        var res = {};
        res.processed = "OK - device " + event.devi + " is not whitelisted!";
        callback(null, res);        
    }
    else {
    
        // Try to connect to Target MQTT Broker
        client.on("connect",function(connack){ 
            
            console.log("MQTT Client connected " + JSON.stringify(connack)); 
            
            // If connection successful, try to publish
            client.publish(MqttTargetTopic, JSON.stringify(event), { qos: 0, retain: false }, (error) => {

Solution

  • I was not able to figure out why the previous implementation stopped working on NodeJs 14+, but I found another working solution for my lambda function. Instead of using mqtt plugin I moved to async-mqtt.

    Below code works for me in Node Js 16 and 18.

    import * as mqtt_async from "async-mqtt";
    
    ...
    
    const client = await mqtt_async.connect(...)
    
    await client.publish(topic, data);
    await client.end();
    
    ...