Get started with IoT Hub module identity and module twin (Node.js)
Note
Module identities and module twins are similar to Azure IoT Hub device identity and device twin, but provide finer granularity. While Azure IoT Hub device identity and device twin enable the back-end application to configure a device and provides visibility on the device's conditions, a module identity and module twin provide these capabilities for individual components of a device. On capable devices with multiple components, such as operating system-based devices or firmware devices, it allows for isolated configuration and conditions for each component.
At the end of this tutorial, you have two Node.js apps:
CreateIdentities, which creates a device identity, a module identity, and associated security keys to connect your device and module clients.
UpdateModuleTwinReportedProperties, which sends updated module twin reported properties to your IoT Hub.
Note
For information about the Azure IoT SDKs that you can use to build both applications to run on devices, and your solution back end, see Azure IoT SDKs.
Prerequisites
Node.js version 10.0.x or later. Prepare your development environment describes how to install Node.js for this tutorial on either Windows or Linux.
An active Azure account. (If you don't have an account, you can create a free account in just a couple of minutes.)
Create an IoT hub
This section describes how to create an IoT hub using the Azure portal.
Sign in to the Azure portal.
From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.
Select IoT Hub from the search results, and then select Create.
On the Basics tab, complete the fields as follows:
Subscription: Select the subscription to use for your hub.
Resource Group: Select a resource group or create a new one. To create a new one, select Create new and fill in the name you want to use. To use an existing resource group, select that resource group. For more information, see Manage Azure Resource Manager resource groups.
Region: Select the region in which you want your hub to be located. Select the location closest to you. Some features, such as IoT Hub device streams, are only available in specific regions. For these limited features, you must select one of the supported regions.
IoT Hub Name: Enter a name for your hub. This name must be globally unique, with a length between 3 and 50 alphanumeric characters. The name can also include the dash (
'-') character.
Important
Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.
Select Next: Networking to continue creating your hub.
Choose the endpoints that devices can use to connect to your IoT Hub. You can select the default setting Public endpoint (all networks), or choose Public endpoint (selected IP ranges), or Private endpoint. Accept the default setting for this example.
Select Next: Management to continue creating your hub.
You can accept the default settings here. If desired, you can modify any of the following fields:
Pricing and scale tier: Your selected tier. You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the hub and up to 8,000 messages per day. Each Azure subscription can create one IoT hub in the free tier.
If you are working through a Quickstart for IoT Hub device streams, select the free tier.
IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. For details about the other tier options, see Choosing the right IoT Hub tier.
Microsoft Defender for IoT: Turn this on to add an extra layer of threat protection to IoT and your devices. This option is not available for hubs in the free tier. Learn more about security recommendations for IoT Hub in Defender for IoT.
Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most hubs need only four partitions.
Select Next: Tags to continue to the next screen.
Tags are name/value pairs. You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. In this document, you won't be adding any tags. For more information, see Use tags to organize your Azure resources.
Select Next: Review + create to review your choices. You see something similar to this screen, but with the values you selected when creating the hub.
Select Create to start the deployment of your new hub. Your deployment will be in progress a few minutes while the hub is being created. Once the deployment is complete, select Go to resource to open the new hub.
Get the IoT hub connection string
In this article, you create a back-end service that adds a device in the identity registry and then adds a module to that device. Your service requires the registry write permission. By default, every IoT hub is created with a shared access policy named registryReadWrite that grants this permission.
To get the IoT Hub connection string for the registryReadWrite policy, follow these steps:
In the Azure portal, select Resource groups. Select the resource group where your hub is located, and then select your hub from the list of resources.
On the left-side pane of your hub, select Shared access policies.
From the list of policies, select the registryReadWrite policy.
Under Shared access keys, select the copy icon for the Primary connection string and save the value.
For more information about IoT Hub shared access policies and permissions, see Access control and permissions.
Create a device identity and a module identity in IoT Hub
In this section, you create a Node.js app that creates a device identity and a module identity in the identity registry in your IoT hub. A device or module cannot connect to IoT hub unless it has an entry in the identity registry. For more information, see the "Identity registry" section of the IoT Hub developer guide. When you run this console app, it generates a unique ID and key for both device and module. Your device and module use these values to identify itself when it sends device-to-cloud messages to IoT Hub. The IDs are case-sensitive.
Create a directory to hold your code.
Inside of that directory, first run npm init -y to create an empty package.json with defaults. This is the project file for your code.
Run npm install -S azure-iothub@modules-preview to install the service SDK inside the node_modules subdirectory.
Note
The subdirectory name node_modules uses the word module to mean "a node library". The term here has nothing to do with IoT Hub modules.
Create the following .js file in your directory. Call it add.js. Copy and paste your hub connection string and hub name.
var Registry = require('azure-iothub').Registry; var uuid = require('uuid'); // Copy/paste your connection string and hub name here var serviceConnectionString = '<hub connection string from portal>'; var hubName = '<hub name>.azure-devices.net'; // Create an instance of the IoTHub registry var registry = Registry.fromConnectionString(serviceConnectionString); // Insert your device ID and moduleId here. var deviceId = 'myFirstDevice'; var moduleId = 'myFirstModule'; // Create your device as a SAS authentication device var primaryKey = new Buffer(uuid.v4()).toString('base64'); var secondaryKey = new Buffer(uuid.v4()).toString('base64'); var deviceDescription = { deviceId: deviceId, status: 'enabled', authentication: { type: 'sas', symmetricKey: { primaryKey: primaryKey, secondaryKey: secondaryKey } } }; // First, create a device identity registry.create(deviceDescription, function(err) { if (err) { console.log('Error creating device identity: ' + err); process.exit(1); } console.log('device connection string = "HostName=' + hubName + ';DeviceId=' + deviceId + ';SharedAccessKey=' + primaryKey + '"'); // Then add a module to that device registry.addModule({ deviceId: deviceId, moduleId: moduleId }, function(err) { if (err) { console.log('Error creating module identity: ' + err); process.exit(1); } // Finally, retrieve the module details from the hub so we can construct the connection string registry.getModule(deviceId, moduleId, function(err, foundModule) { if (err) { console.log('Error getting module back from hub: ' + err); process.exit(1); } console.log('module connection string = "HostName=' + hubName + ';DeviceId=' + foundModule.deviceId + ';ModuleId='+foundModule.moduleId+';SharedAccessKey=' + foundModule.authentication.symmetricKey.primaryKey + '"'); process.exit(0); }); }); });
This app creates a device identity with ID myFirstDevice and a module identity with ID myFirstModule under device myFirstDevice. (If that module ID already exists in the identity registry, the code simply retrieves the existing module information.) The app then displays the primary key for that identity. You use this key in the simulated module app to connect to your IoT hub.
Run this using node add.js. It will give you a connection string for your device identity and another one for your module identity.
Note
The IoT Hub identity registry only stores device and module identities to enable secure access to the IoT hub. The identity registry stores device IDs and keys to use as security credentials. The identity registry also stores an enabled/disabled flag for each device that you can use to disable access for that device. If your application needs to store other device-specific metadata, it should use an application-specific store. There is no enabled/disabled flag for module identities. For more information, see Understand the identity registry in your IoT Hub in the IoT Hub developer guide.
Update the module twin using Node.js device SDK
In this section, you create a Node.js app on your simulated device that updates the module twin reported properties.
Get your module connection string -- Sign in to the Azure portal. Navigate to your IoT Hub and click IoT Devices. Find myFirstDevice, open it and you see myFirstModule was successfully created. Copy the module connection string. It is needed in the next step.

Similar to what you did in the step above, create a directory for your device code and use NPM to initialize it and install the device SDK (npm install -S azure-iot-device-amqp@modules-preview).
Note
The npm install command may feel slow. Be patient -- it's pulling down lots of code from the package repository.
Note
If you see an error that says npm ERR! registry error parsing json, this is safe to ignore. If you see an error that says npm ERR! registry error parsing json, this is safe to ignore.
Create a file called twin.js. Copy and paste your module identity string.
var Client = require('azure-iot-device').Client; var Protocol = require('azure-iot-device-amqp').Amqp; // Copy/paste your module connection string here. var connectionString = '<insert module connection string here>'; // Create a client using the Amqp protocol. var client = Client.fromConnectionString(connectionString, Protocol); client.on('error', function (err) { console.error(err.message); }); // connect to the hub client.open(function(err) { if (err) { console.error('error connecting to hub: ' + err); process.exit(1); } console.log('client opened'); // Create device Twin client.getTwin(function(err, twin) { if (err) { console.error('error getting twin: ' + err); process.exit(1); } // Output the current properties console.log('twin contents:'); console.log(twin.properties); // Add a handler for desired property changes twin.on('properties.desired', function(delta) { console.log('new desired properties received:'); console.log(JSON.stringify(delta)); }); // create a patch to send to the hub var patch = { updateTime: new Date().toString(), firmwareVersion:'1.2.1', weather:{ temperature: 72, humidity: 17 } }; // send the patch twin.properties.reported.update(patch, function(err) { if (err) throw err; console.log('twin state reported'); }); }); });Now, run this using the command node twin.js.
F:\temp\module_twin>node twin.jsYou will then see:
client opened twin contents: { reported: { update: [Function: update], '$version': 1 }, desired: { '$version': 1 } } new desired properties received: {"$version":1} twin state reported
Next steps
To continue getting started with IoT Hub and to explore other IoT scenarios, see: