Azure IoT Device HTTP Transport

raw JSON →
1.14.4 verified Wed Apr 22 auth: no javascript

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.

error TypeError: Client.fromConnectionString is not a function
cause This error typically occurs when `Client` is not correctly imported as a class with static methods, or when attempting to call `Client.fromConnectionString` directly on the `azure-iot-device-http` package (which is a re-export, but less common in modern usage).
fix
Ensure you are importing 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"}
cause The device connection string provided is invalid, expired, or does not correspond to an active device in your Azure IoT Hub, preventing successful authentication.
fix
Verify the device connection string in the Azure portal for your specific device. Ensure it's copied correctly, includes 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
cause This warning indicates that too many event listeners (e.g., for `message`, `error`, `disconnect` events) are being attached to a `Client` instance, often due to creating new client instances or re-attaching listeners in a loop without proper cleanup.
fix
Ensure event listeners are attached only once per 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.
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.
fix Upgrade your Node.js runtime environment to version 14.0.0 or higher. The `engines` field in `package.json` specifies `node: ">= 14.0.0"`.
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.
fix For modern Node.js projects using ES Modules (e.g., `"type": "module"` in `package.json`), use `import { Client, Message } from 'azure-iot-device';` and `import { Http } from 'azure-iot-device-http';`. For CommonJS projects, use `const { Client, Message } = require('azure-iot-device');` and `const { Http } = require('azure-iot-device-http');`.
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.
fix Ensure your project's dependency resolution correctly handles `@azure/core-auth`. If you are directly using functionalities from `azure-iot-http-base`, consult its documentation for updated API surfaces or type definitions.
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.
fix Regularly update all `azure-iot-*` packages to their latest stable versions. Utilize tools like `npm audit` or `yarn audit` to identify and resolve known vulnerabilities.
npm install azure-iot-device-http
yarn add azure-iot-device-http
pnpm add azure-iot-device-http

Demonstrates how to connect an Azure IoT device using an HTTP connection string, send a device-to-cloud message, and handle incoming cloud-to-device messages. It uses the modern `Client.fromConnectionString` pattern with the `Http` transport.

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