Get started with device twins (Node)

Device twins are JSON documents that store device state information (metadata, configurations, and conditions). IoT Hub persists a device twin for each device that connects to it.


The features described in this article are available only in the standard tier of IoT Hub. For more information about the basic and standard IoT Hub tiers, see Choose the right IoT Hub tier.

Use device twins to:

  • Store device metadata from your solution back end.

  • Report current state information such as available capabilities and conditions (for example, the connectivity method used) from your device app.

  • Synchronize the state of long-running workflows (such as firmware and configuration updates) between a device app and a back-end app.

  • Query your device metadata, configuration, or state.

Device twins are designed for synchronization and for querying device configurations and conditions. More information on when to use device twins can be found in Understand device twins.

Device twins are stored in an IoT hub and contain:

  • tags, device metadata accessible only by the solution back end;

  • desired properties, JSON objects modifiable by the solution back end and observable by the device app; and

  • reported properties, JSON objects modifiable by the device app and readable by the solution back end. Tags and properties cannot contain arrays, but objects can be nested.

Device twin image showing functionality

Additionally, the solution back end can query device twins based on all the above data. Refer to Understand device twins for more information about device twins, and to the IoT Hub query language reference for querying.

This tutorial shows you how to:

  • Create a back-end app that adds tags to a device twin, and a simulated device app that reports its connectivity channel as a reported property on the device twin.

  • Query devices from your back-end app using filters on the tags and properties previously created.

At the end of this tutorial, you will have two Node.js console apps:

  • AddTagsAndQuery.js, a Node.js back-end app, which adds tags and queries device twins.

  • TwinSimulatedDevice.js, a Node.js app, which simulates a device that connects to your IoT hub with the device identity created earlier, and reports its connectivity condition.


The article Azure IoT SDKs provides information about the Azure IoT SDKs that you can use to build both device and back-end apps.

To complete this tutorial you need the following:

  • Node.js version 10.0.x or later.

  • 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.

  1. Log in to the Azure portal.

  2. Choose +Create a resource, then Search the Marketplace for the IoT Hub.

  3. Select IoT Hub and click the Create button. You see the first screen for creating an IoT hub.

    Create a hub in the Azure portal

    Fill in the fields.

    Subscription: Select the subscription to use for your IoT hub.

    Resource Group: You can create a new resource group or use an existing one. To create a new one, click Create new and fill in the name you want to use. To use an existing resource group, click Use existing and select the resource group from the dropdown list. For more information, see Manage Azure Resource Manager resource groups.

    Region: This is the region in which you want your hub to be located. Select the location closest to you from the dropdown list.

    IoT Hub Name: Put in the name for your IoT Hub. This name must be globally unique. If the name you enter is available, a green check mark appears.


    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.

  4. Click Next: Size and scale to continue creating your IoT hub.

    Set the size and scale for a new IoT hub using the Azure portal

    On this screen, you can take the defaults and just click Review + create at the bottom.

    Pricing and scale 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 IoT hub and up to 8,000 messages per day. Each Azure subscription can create one IoT Hub in 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 IoT 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.

    Advanced / Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most IoT hubs only need four partitions.

  5. Click Review + create to review your choices. You see something similar to this screen.

    Review information for creating the new IoT hub

  6. Click Create to create your new IoT hub. Creating the hub takes a few minutes.

Retrieve connection string for IoT hub

After your hub has been created, retrieve the connection string for the hub. This is used to connect devices and applications to your hub.

  1. Click on your hub to see the IoT Hub pane with Settings, and so on. Click Shared access policies.

  2. In Shared access policies, select the iothubowner policy.

  3. Under Shared access keys, copy the Connection string -- primary key to be used later.

    Show how to retrieve the connection string

    For more information, see Access control in the "IoT Hub developer guide."

Create a device identity

In this section, you use the Azure CLI to create a device identity for this tutorial. The Azure CLI is preinstalled in the Azure Cloud Shell, or you can install the Azure CLI locally. Device IDs are case sensitive.

  1. Run the following command in the command-line environment where you are using the Azure CLI to install the IoT extension:

    az extension add --name azure-cli-iot-ext
  2. If you are running the Azure CLI locally, use the following command to sign in to your Azure account (if you are using the Cloud Shell, you are signed in automatically and you don't need to run this command):

    az login
  3. Finally, create a new device identity called myDeviceId and retrieve the device connection string with these commands:

    az iot hub device-identity create --device-id myDeviceId --hub-name {Your IoT Hub name}
    az iot hub device-identity show-connection-string --device-id myDeviceId --hub-name {Your IoT Hub name} -o table


    The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

Make a note of the device connection string from the result. This device connection string is used by the device app to connect to your IoT Hub as a device.

Create the service app

In this section, you create a Node.js console app that adds location metadata to the device twin associated with myDeviceId. It then queries the device twins stored in the IoT hub selecting the devices located in the US, and then the ones that are reporting a cellular connection.

  1. Create a new empty folder called addtagsandqueryapp. In the addtagsandqueryapp folder, create a new package.json file using the following command at your command prompt. Accept all the defaults:

    npm init
  2. At your command prompt in the addtagsandqueryapp folder, run the following command to install the azure-iothub package:

    npm install azure-iothub --save
  3. Using a text editor, create a new AddTagsAndQuery.js file in the addtagsandqueryapp folder.

  4. Add the following code to the AddTagsAndQuery.js file, and substitute the {iot hub connection string} placeholder with the IoT Hub connection string you copied when you created your hub:

         'use strict';
         var iothub = require('azure-iothub');
         var connectionString = '{iot hub connection string}';
         var registry = iothub.Registry.fromConnectionString(connectionString);
         registry.getTwin('myDeviceId', function(err, twin){
             if (err) {
                 console.error( + ': ' + err.message);
             } else {
                 var patch = {
                     tags: {
                         location: {
                             region: 'US',
                             plant: 'Redmond43'
                 twin.update(patch, function(err) {
                   if (err) {
                     console.error('Could not update twin: ' + + ': ' + err.message);
                   } else {
                     console.log(twin.deviceId + ' twin updated successfully');

    The Registry object exposes all the methods required to interact with device twins from the service. The previous code first initializes the Registry object, then retrieves the device twin for myDeviceId, and finally updates its tags with the desired location information.

    After updating the tags it calls the queryTwins function.

  5. Add the following code at the end of AddTagsAndQuery.js to implement the queryTwins function:

         var queryTwins = function() {
             var query = registry.createQuery("SELECT * FROM devices WHERE tags.location.plant = 'Redmond43'", 100);
             query.nextAsTwin(function(err, results) {
                 if (err) {
                     console.error('Failed to fetch the results: ' + err.message);
                 } else {
                     console.log("Devices in Redmond43: " + {return twin.deviceId}).join(','));
             query = registry.createQuery("SELECT * FROM devices WHERE tags.location.plant = 'Redmond43' AND properties.reported.connectivity.type = 'cellular'", 100);
             query.nextAsTwin(function(err, results) {
                 if (err) {
                     console.error('Failed to fetch the results: ' + err.message);
                 } else {
                     console.log("Devices in Redmond43 using cellular network: " + {return twin.deviceId}).join(','));

    The previous code executes two queries: the first selects only the device twins of devices located in the Redmond43 plant, and the second refines the query to select only the devices that are also connected through cellular network.

    The previous code, when it creates the query object, specifies a maximum number of returned documents. The query object contains a hasMoreResults boolean property that you can use to invoke the nextAsTwin methods multiple times to retrieve all results. A method called next is available for results that are not device twins, for example, results of aggregation queries.

  6. Run the application with:

        node AddTagsAndQuery.js

    You should see one device in the results for the query asking for all devices located in Redmond43 and none for the query that restricts the results to devices that use a cellular network.

    See the one device in the query results

In the next section, you create a device app that reports the connectivity information and changes the result of the query in the previous section.

Create the device app

In this section, you create a Node.js console app that connects to your hub as myDeviceId, and then updates its device twin's reported properties to contain the information that it is connected using a cellular network.

  1. Create a new empty folder called reportconnectivity. In the reportconnectivity folder, create a new package.json file using the following command at your command prompt. Accept all the defaults:

    npm init
  2. At your command prompt in the reportconnectivity folder, run the following command to install the azure-iot-device, and azure-iot-device-mqtt package:

    npm install azure-iot-device azure-iot-device-mqtt --save
  3. Using a text editor, create a new ReportConnectivity.js file in the reportconnectivity folder.

  4. Add the following code to the ReportConnectivity.js file, and substitute the {device connection string} placeholder with the device connection string you copied when you created the myDeviceId device identity:

        'use strict';
        var Client = require('azure-iot-device').Client;
        var Protocol = require('azure-iot-device-mqtt').Mqtt;
        var connectionString = '{device connection string}';
        var client = Client.fromConnectionString(connectionString, Protocol);
        if (err) {
            console.error('could not open IotHub client');
        }  else {
            console.log('client opened');
            client.getTwin(function(err, twin) {
            if (err) {
                console.error('could not get twin');
            } else {
                var patch = {
                    connectivity: {
                        type: 'cellular'
      , function(err) {
                    if (err) {
                        console.error('could not update twin');
                    } else {
                        console.log('twin state reported');

    The Client object exposes all the methods you require to interact with device twins from the device. The previous code, after it initializes the Client object, retrieves the device twin for myDeviceId and updates its reported property with the connectivity information.

  5. Run the device app

        node ReportConnectivity.js

    You should see the message twin state reported.

  6. Now that the device reported its connectivity information, it should appear in both queries. Go back in the addtagsandqueryapp folder and run the queries again:

        node AddTagsAndQuery.js

    This time myDeviceId should appear in both query results.

    Show myDeviceId in both query results

Next steps

In this tutorial, you configured a new IoT hub in the Azure portal, and then created a device identity in the IoT hub's identity registry. You added device metadata as tags from a back-end app, and wrote a simulated device app to report device connectivity information in the device twin. You also learned how to query this information using the SQL-like IoT Hub query language.

Use the following resources to learn how to: