Azure IoT Device HTTP Transport
raw JSON →This package provides the HTTP 1.1 transport layer for the Azure IoT Device SDK for Node.js. It enables IoT devices to communicate with Azure IoT Hub by sending device-to-cloud messages and receiving cloud-to-device commands over the HTTP protocol. This transport is particularly useful in environments where persistent connections (like MQTT or AMQP) are impractical or undesirable, such as highly constrained networks or when devices infrequently send data. The current stable version is 1.14.4. It is part of the larger Azure IoT SDK for Node.js monorepo, with releases typically bundled across multiple related packages, occurring quarterly or as needed for bug fixes and security updates. It differentiates itself by offering the HTTP protocol option, contrasting with `azure-iot-device-mqtt` and `azure-iot-device-amqp` which provide alternative transports.
Common errors
error TypeError: Client.fromConnectionString is not a function ↓
Client from azure-iot-device as a named import: import { Client } from 'azure-iot-device';. Then, pass the Http transport when creating the client: const client = Client.fromConnectionString(connectionString, Http);. error Error: Could not connect: {"error":"Unauthorized"} ↓
HostName, DeviceId, and SharedAccessKey (or SharedAccessSignature), and that the device is enabled in IoT Hub. error (node:xyz) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. N Listener added to [Client]. Use emitter.setMaxListeners() to increase limit ↓
Client instance. If clients are frequently re-initialized, consider reusing an existing client or explicitly removing old listeners with client.removeListener(eventName, listenerFunction) before attaching new ones. For rare cases where many listeners are genuinely needed, client.setMaxListeners(N) can suppress the warning, but it's often a symptom of a bug. Warnings
breaking Node.js 12 reached end-of-life and is no longer supported. Azure IoT SDKs moved to Node.js 14 as the minimum requirement. ↓
gotcha The Azure IoT SDK for Node.js supports both CommonJS (`require`) and ES Modules (`import`). Using `require` in an ESM context or vice-versa can lead to runtime errors or incorrect symbol resolution. ↓
breaking The underlying `azure-iot-http-base` package changed its dependency from `@azure/core-http` to `@azure/core-auth` in a previous release. While `azure-iot-device-http` abstracts this, direct interactions with `azure-iot-http-base` or type conflicts could arise. ↓
gotcha The Azure IoT SDKs, including `azure-iot-device-http`, are regularly updated to address dependency vulnerabilities. Running older versions can expose your application to known security risks. ↓
Install
npm install azure-iot-device-http yarn add azure-iot-device-http pnpm add azure-iot-device-http Imports
- Client wrong
const Client = require('azure-iot-device').Client;correctimport { Client } from 'azure-iot-device'; - Message wrong
const Message = require('azure-iot-device').Message;correctimport { Message } from 'azure-iot-device'; - Http wrong
const Http = require('azure-iot-device-http').Http;correctimport { Http } from 'azure-iot-device-http'; - clientFromConnectionString wrong
const clientFromConnectionString = require('azure-iot-device-http').clientFromConnectionString;correctimport { clientFromConnectionString } from 'azure-iot-device-http';
Quickstart
import { Client, Message } from 'azure-iot-device';
import { Http } from 'azure-iot-device-http';
// Replace with your actual IoT Hub device connection string.
// You can find this in the Azure portal under your IoT Hub -> Devices -> [Your Device] -> Connection string (primary key).
const connectionString: string = process.env.IOTHUB_DEVICE_CONNECTION_STRING || 'HostName=YOUR_HUB.azure-devices.net;DeviceId=YOUR_DEVICE_ID;SharedAccessKey=YOUR_KEY';
if (connectionString.includes('YOUR_HUB')) {
console.warn('Please replace the placeholder connection string with your actual IoT Hub device connection string.');
process.exit(1);
}
const client = Client.fromConnectionString(connectionString, Http);
const connectCallback = (err?: Error): void => {
if (err) {
console.error(`Could not connect: ${err.message}`);
} else {
console.log('Client connected');
const message = new Message('some data from my device via HTTP');
console.log('Sending message:', message.getData());
client.sendEvent(message, (sendErr?: Error) => {
if (sendErr) {
console.error(`Error sending message: ${sendErr.toString()}`);
} else {
console.log('Message sent successfully');
}
});
client.on('message', (msg: Message) => {
console.log('Received message from IoT Hub:', msg.getData().toString());
client.complete(msg, (completeErr?: Error) => {
if (completeErr) {
console.error(`Error completing message: ${completeErr.toString()}`);
} else {
console.log('Message completed');
}
});
});
client.on('error', (error: Error) => {
console.error(`Client error: ${error.message}`);
});
client.on('disconnect', (transportError: Error) => {
console.warn(`Client disconnected: ${transportError?.message || 'Unknown reason'}`);
});
}
};
client.open(connectCallback);
// Keep the process alive for a bit to allow messages to be received
setInterval(() => {}, 1000 * 60 * 60); // Keep alive for 1 hour or until process is killed