IoTHub Nodejs SDK Gotcha

If you want to connect using the fromConnectionString API, you first need to be aware that the connection string is not the connection string you’d copy from the Access Keys blade in the portal. This is a connection string which is documented as is required to be formatted like so:

HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>

The catch here is that this connection string will work, if you generate a SharedAccessKey specifically for the device you want to connect, as is defined by the DeviceId parameter.

If you want to use a single connection string for ALL devices to connect, you need to format your connection string like so:

HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKeyName=<policy_name>;SharedAccessKey=<policy_key>

Note the passing of the SharedAccessKeyName. This is the name of the policy you want to use to connect your devices, the default is “device”.

If you specify the policy to use, you can then just pass along the shared access key for that policy and use this connection string for any device.