AWS IoT MQTT client
This module implements a client to connect to AWS IoT MQTT broker using WebSockets. It can be used in a browser as well as in Node.js environment.
The main class exported from this package is a subclass of MqttClient and exposes the same API. What this package adds is the following:
- AWS IoT broker url signing logic
- Refreshing of credentials and re-signing url on re-connects
- Custom WebSocket stream implementation that is more efficient then out of the box mqtt.js/websocket-stream combo (this package handles corking/uncorking of the stream, whereas websocket-stream sends a separate frame per each byte written)
- Validated connection options that work with AWS MQTT broker
- Pins versions of
aws-signature-v4to a known tested combo, in the past lax version constraints broke this package
NodeClientthat works in node (need to install ws separately)
Up until now an implementation of a realtime in-browser application required the use of either an external service (e.g Pusher, PubNub) or roll your own servers (e.g. using socket.io) that maintain connections with browsers and need scaling to respond to the changes in number of active users. Using AWS IoT MQTT broker as the realtime backend provides a low cost scalable service for your application.
AWS documentation does not explicitly promote the use of IoT MQTT broker as a general purpose pub/sub broker. Only the use case of IoT devices communication is explicitly described. While technically there is nothing preventing general purpose browsers and servers connecting to the broker (such as implemented by this library), AWS may change its terms of service or implement some broker constraints to prevent such use case. Use at your own risk.
npm install aws-sdk aws-mqtt --save
when using in a node environment (not browser), install WebSocket implementation, e.g.
npm install ws --save
The example below assumes the use of Babel/Webpack.
aws-sdk now officially supports bundling with webpack, with a few things to know.
AWSconfigregion = 'us-east-1' // your regionAWSconfigcredentials = ... // See AWS Setup and Security belowconst client =region: AWSconfigregioncredentials: AWSconfigcredentialsendpoint: '...iot.us-east-1.amazonaws.com' // NOTE: get this value with `aws iot describe-endpoint`expires: 600 // Sign url with expiration of 600 secondsclientId: 'mqtt-client-' + Math // clientId to register with MQTT broker. Need to be unique per clientwill:topic: 'WillMsg'payload: 'Connection Closed abnormally..!'qos: 0retain: falseclientclientclientclient
client object in the above example is a subclass of MqttClient class from MQTT.js.
For events and API see the docs.
The same usage as in browser, but require a different module -
require('aws-mqtt/lib/NodeClient') instead of
ws also needs to be installed.
Install ws if you don't have it installed yet
npm install ws@^6.0.0
// in node v6.xconst AWS =const AWSMqttClient =AWSconfigregion = 'us-east-1'AWSconfigcredentials = ...const client =region: AWSconfigregioncredentials: AWSconfigcredentialsendpoint: '...iot.us-east-1.amazonaws.com' // NOTE: get this value with `aws iot describe-endpoint`clientId: 'mqtt-client-' + Math // clientId to register with MQTT broker. Need to be unique per clientwill:topic: 'WillMsg'payload: 'Connection Closed abnormally..!'qos: 0retain: false
In AWS Lambda functions
NodeClient instance will set up internal timers and the node.js process will not exit until you call
This is fine if you are developing a long running server app that subscribes and/or publishes messages.
For ephemeral functions, such as AWS Lambda, this approach will cause the function invocation to timeout.
To publish a single message to a topic and disconnect - require
publishMessage and use it like this:
const AWS =const publishMessage =AWSconfigregion = 'us-east-1'AWSconfigcredentials = ...const config =region: AWSconfigregioncredentials: AWSconfigcredentialsendpoint: '...iot.us-east-1.amazonaws.com'// publish returns a Promise
AWS Setup and Security
An example of policy statement for an un-authenticated user (tweak as you see fit, note the use of
iot:ClientId to dynamically limit the topics):
Quick example using Cognito Identity un-authenticated users approach
Create a Cognito Identity Pool in AWS (under Cognito Federated Identities)
Accept default create IAM roles for authenticated and un-authenticated identities
Go to IAM Roles and find the role for the un-authenticated role created for the identity pool
Edit the inline policy to allow access to connect, subscribe and publish to IoT message broker. Note: the policy shown below is very open for an un-authenticated user, you can start with that to make sure things work, and then tighten it up.
Get the Identity Pool ID you just created:
aws cognito-identity list-identity-pools --max-results=5
Use the Identity Pool ID in you app credentials:
AWSconfigregion = '...' // e.g us-west-2AWSconfigcredentials =IdentityPoolId: '...'
AWS.config.credentials to AWSMqtt connect methods.
./examples folder there are two example projects:
- chat - The minimalistic example of using AWSMqtt in browser with Webpack
- node-publisher - contains two examples
- timePublisher.js - how to connect to AWS IoT MQTT broker, subscribe and publish messages
- publish.js - how to publish one message and disconnect, e.g.
node publish.js "/chat" Hello
Before running any of the examples, copy
examples/config.js and fill in your values.
Frequently asked questions
If your browser is reporting a memory leak, this could be caused by your cleanup strategy of event listeners. By default, most browsers allow 10 event listeners to listen to a single emitting event from a singular source. So, if you have more than 10 listeners for an event (ie
message is the event), then you will get this error. If your client is disconnecting, or reconnecting, we recommend that you cleanup the old event listeners with
client.removeAllListeners('EVENT') (where EVENT could be
message, or other), or
There are a few reasons why your client may be disconnecting unexpectedly. Here are a few cases:
connectconfiguration MUST be unique across each client. If clients A and B use the same clientId, then when B tries to connect, client A will get disconnected (by the broker). Because this package attempts to reconnect you when disconnected, client A will reconnect, which will cause client B to disconnect. And an infinite cycle ensues. Note that
clientId, if not passed in the config, will use
'mqtt-client-' + (Math.floor((Math.random() * 100000) + 1))to generate a "unique" clientId. If you are passing in clientId to override the default, make sure it is unique.
- Permissions with AWS IAM could be set up incorrectly.