Cloud Code Sandbox

Quick introduction of how to use Cloud Code

Sometimes you need to execute a part of your business logic in a server. You can execute JavaScript code at thethings.iO cloud using the Cloud Code API.

There are three types of Cloud Code: triggers, jobs and parsers or decoders.

  • Triggers are executed when an event occurs like a thingWrite.
  • Cloud Code Jobs are tasks executed once every hour or day.
  • Cloud Code Decoders are snippets of code executed with a REST API call or when we recieve data to any of the data ingestion services.

You can use triggers to send alarms when the temperature is higher than a threshold or generate events to aggregate later in a job.

Device group Trigger Example

This is a description of how you can set and manage a trigger for a device group.

First, go to the cloud code view clicking on the 'cloud code' link at the left sidebar.

Next, click on 'Start Coding'.


As you can see, this view is empty because you haven't created any triggers, jobs or decoders yet. Later, you will manage these (list, delete and edit) from this view.

Now, just click the 'Add Trigger' button and you will see the next form.


This form is very straight-forward. You only have to name the trigger, choose the device group on which you want to apply the trigger, and put the code and save.

Once added, the trigger will subscribe to all the devices of a device group. That means that every time an event on your devices occurs, we execute the trigger code.

For example (see the next code example), if a device writes a temperature value of 25, the trigger is triggered and will get this value via the params argument. If our trigger is configured to send an email every time a value is higher than 50. The code will compare 25 and 50 and will do nothing. But if the device writes a 60, then the trigger will send an email alerting us.

function trigger(params, callback){
  console.log('trigger triggered!!')

  var values = params.values
  var thingToken = params.thingToken

  //iterate over the values of the write
  for(var i=0; i<values.length; ++i){
    if(values[i].key === 'temperature' && values[i].value >= 50){
      console.log('omg too hot')
          service : 'SendGrid',
          auth: {
            api_user: 'YOUR API USER',
            api_key: 'YOUR API KEY'
          from: '[email protected]',
          to: '[email protected]',
          subject : 'The temperature is too high',
          text : 'Master, it’s too hot here! \n\n Always yours,\n '+ thingToken
  //end the trigger