An open API service indexing awesome lists of open source software.

https://github.com/immutal0/aws-mqtt-client-module

AWS Websocket pub/sub client javascript module
https://github.com/immutal0/aws-mqtt-client-module

aws client javascript module pub sub websocket

Last synced: 2 months ago
JSON representation

AWS Websocket pub/sub client javascript module

Awesome Lists containing this project

README

          

# AWS WebSocket Pub/Sub Client with MQTT.js

This guide demonstrates how to set up a WebSocket-based Pub/Sub system using AWS IoT and MQTT.js. AWS IoT now supports WebSockets, allowing easy integration for serverless web applications. You can publish messages from AWS Lambda via HTTP POST requests and subscribe to those messages on the client side using WebSockets.

## Prerequisites

1. **AWS IoT Setup**:
- Create an IAM role and assign the predefined `AWSIoTDataAccess` policy.
- Use [AWS Cognito](https://aws.amazon.com/cognito/) to provide temporary credentials for the front-end application.
- Optionally, customize the policy to allow access only to user-specific topics.

2. **Get IoT Endpoint URL**:
- Run the following AWS CLI command to get the IoT endpoint URL:
```
aws iot describe-endpoint
```

## Installation

To use the `aws-mqtt-client`, first install it using npm:

```bash
npm install aws-mqtt-client --save
```

## Basic Usage

### Step 1: Set Up AWS IoT MQTT Client

Import the client library and create a new MQTT client instance with your AWS credentials and IoT endpoint.

```js
import AWSMqtt from "aws-mqtt-client";

const mqttClient = new AWSMqtt({
accessKeyId: AWS_ACCESS_KEY, // AWS Access Key
secretAccessKey: AWS_SECRET_ACCESS_KEY, // AWS Secret Access Key
sessionToken: AWS_SESSION_TOKEN, // Optional: AWS Session Token
endpointAddress: AWS_IOT_ENDPOINT_HOST, // IoT Endpoint URL
region: "us-east-1" // AWS Region
});
```

### Step 2: Connect and Subscribe to a Topic

Use the `connect` event to establish a connection and the `subscribe` method to listen for messages from a specified topic.

```js
mqttClient.on("connect", () => {
mqttClient.subscribe("test-topic");
console.log("Connected to IoT MQTT WebSocket");
});

mqttClient.on("message", (topic, message) => {
console.log(message.toString());
});
```

### Step 3: Publish a Message

Publish messages to a specific MQTT topic using the `publish` method:

```js
mqttClient.publish("test-topic", "Your message here");
```

## Summary

This setup allows you to easily integrate WebSocket-based Pub/Sub messaging into your serverless web application with AWS IoT and MQTT.js. By leveraging AWS's IoT service with WebSockets, you can send real-time messages to the client and publish messages from Lambda functions via HTTP POST requests.