Javascript in ioBroker – Script Engine Adapter

The ioBroker Script Engine adapter lets us create our own automations. We can use it to connect states from different adapters, respond to events, and schedule tasks. In this article, we will first explore the most important settings and the editor, then try a few simple JavaScript examples.

Created: June 2023

Reviewed: November 2026

Prerequisite: An installed ioBroker server

Installing the Script Engine adapter

To create our own scripts, we need to install the Script Engine adapter. On the ioBroker Adapters page, search for “Script Engine”. The adapter is named javascript on its card, and the first instance created after installation is usually called javascript.0.

Script Engine adapter card on the ioBroker Adapters page
The Script Engine adapter card. We can add an instance from here.

When we add an instance, its settings page opens. For our first experiments, we can leave most settings at their defaults. It is worth learning what the options do, however, because some of them change how scripts behave.

General settings

General settings of the JavaScript adapter
General settings of the JavaScript adapter.

In Additional npm modules, we can specify extra Node.js packages if a script genuinely needs them. Before adding an external package, always check its source and documentation.

Activate syntax help for these npm modules controls the editor assistance available for the specified modules. Mirror scripts to file path mirrors scripts to the file system. Beginners should leave this field empty. As the warning in the screenshot explains, it requires a separate, empty directory outside the ioBroker installation with the appropriate permissions. If a mirrored folder disappears, the corresponding scripts may also be deleted from the database.

Enable command “setObject” allows scripts to modify the structure, metadata, or settings of existing ioBroker objects. For example, a script could change an adapter’s configuration to stop or start it. The createState function can create new states without enabling “setObject”; this option is needed to overwrite existing objects.

Enable command “sendToHost” lets scripts send commands directly to the ioBroker host. Depending on the command, this can be used to request system information, restart the controller with restartController, or perform other host-level operations.

Enable command “exec” makes the exec() function available. With it, scripts can run operating-system commands and external programs.

The exec and sendToHost options give scripts powerful capabilities. In particular, exec() can run terminal commands with the permissions available to the ioBroker process.

Enable these options only when a script actually needs them, and run code only from sources you trust.

Do not subscribe all states on start can reduce the JavaScript instance’s resource usage, but it has an important consequence: when enabled, synchronous getState() does not work in the same way as with the default setting. On larger systems, it may be worth enabling this option and using targeted subscriptions together with asynchronous state reads.

The Maximum setState requests per minute per Script and Maximum triggers per Script limits help reveal scripts that write too frequently or trigger too many events. If a script reaches one of these limits, look for the cause first. A feedback loop, for example, can call the same code repeatedly.

Allow self-signed certificates for URL requests may be justified if a script connects to an HTTPS endpoint that uses a self-signed certificate. Relaxing certificate verification is a security compromise.

Astro settings

The Astro settings tab deals with times related to the Sun’s position, such as sunrise, sunset, and dusk. These can be useful for an automation that should not switch on the lights at the same clock time every day.

Astro settings of the JavaScript adapter
The Astro settings also let us define the start and end of the daytime period.

Use system settings uses the location settings configured in ioBroker. For accurate Astro times, the location and time zone must be correct. Under Day time settings, we can choose which events mark the beginning and end of daytime. Offset shifts an event by a number of minutes, while But not earlier and And not later set time boundaries. Create states for all astro times creates states for the calculated Astro times.

Here, “Astro” means astronomical events connected to the position of the Sun, not astrological predictions. The Sun/Moon icon in the editor shows the calculated events for the current day.

List of today's Astro events in the JavaScript editor
The editor can display the times of today’s astronomical events.

TypeScript, AI, and credentials

The TypeScript tab controls how TypeScript scripts are compiled and type-checked. For example, we can choose the compilation target and determine whether a script may start when compilation errors occur.

TypeScript includes valid JavaScript and gives developers additional tools for catching mistakes. It takes a little more preparation and learning, but type checking can be particularly helpful with larger scripts, custom function libraries, and complex data structures. We will not cover TypeScript programming in detail in this article.

Upper part of the JavaScript adapter's TypeScript compilation settings
Some of the main compilation options on the TypeScript tab.

On the AI settings tab, we can configure whether AI helpers appear in the editor and enter API keys for supported providers. With a valid API key configured, an AI assistant can be opened in a separate panel within the JavaScript editor.

If you use an AI assistant, always review generated code before running it, especially when it controls devices or communicates with external services.

AI helper and API key settings of the JavaScript adapter
The optional AI helper settings.

On the Credentials tab, we can allow scripts to read entries stored in ioBroker’s central credential store. Credentials are managed in the Admin basic settings rather than in the script itself. This means, for example, that we do not need to put an API key directly into the program code.

Allow access to centrally stored credentials only when your scripts actually need it.

No credentials have been created yet in the screenshot.

Configuring access to centrally stored credentials
The Credentials tab controls access to the central credential store.

Script history

On the Script history tab, we can choose how many saved versions the system retains for each script. In the editor, these versions can be viewed, compared, and restored. The value shown in the screenshot is 30. Setting it to 0 disables history, although the adapter description says that the very first version is still kept. History can help us recover from an accidental editing mistake, but it does not replace regular backups.

Setting the number of saved script versions
Here we can set how many script versions are retained.

Getting to know the Scripts editor

After saving the JavaScript instance settings, open the Scripts page. The screenshot shows three main areas. On the left is the script folder tree, in the middle is the editor, and at the bottom is the log output. We can resize the areas by dragging their borders and hide the log when we need more room.

Folder tree, code editor, and log panel on the Scripts page
The three main parts of the Scripts editor: folder tree, code editor, and log.

Folders and new scripts

We can organise our scripts in the folder tree on the left. It is worth using descriptive names and separate folders from the start, for example for lighting or notifications. At the top of the folder view, the folder-plus icon creates a new folder, while the plus icon creates a new script. The pencil icon helps with renaming, and the search icon helps us find scripts.

The three-dot menu includes Expert mode, exporting all scripts, importing scripts, changing the theme, and copying. Exporting can help us keep a copy of our scripts. Importing may change existing content, so check what you are about to load first.

Options in the three-dot menu on the Scripts page
The three-dot menu provides import, export, and Expert mode options.

When creating a script, we can choose from several editor modes. Rules is built around simple conditions, while Blockly uses graphical blocks. Function block diagram provides a visual way to build more complex logic that runs continuously. JavaScript and TypeScript let us write code directly. We will choose JavaScript for this article.

Choosing between Rules, Blockly, Function block diagram, JavaScript, and TypeScript scripts
We can choose from several editor modes when creating a new script.

Give the script a descriptive name and select its folder. The creation dialog also shows its ID. This ID reflects the folder and script name. Later, it helps us identify which script ran when reading logs and error messages.

Name, folder, and ID of a new JavaScript script
Give the new script a name and check the selected folder.

Editor tools

We write our code in the central area. We can have several scripts open at once and switch between them using the tabs at the top. The folder tree can be hidden when we need more space. Above the code are icons for actions such as starting, restarting, viewing history, and undoing changes. Their order may vary between versions, so check the tooltip that appears when you hover over an unfamiliar icon.

Upper toolbar of the JavaScript editor
The editor toolbar contains controls for running scripts and opening helper panels.

The clock icon opens a scheduling dialog. We can use its wizard to select a time or repeating interval, or edit the scheduling expression directly in the CRON view. A scheduled task runs only while its script is running. Before accepting a schedule, check that its repetition matches what you intended.

Setting a schedule in the JavaScript editor wizard
The scheduling dialog includes both a wizard and a CRON view.

The state selector lets us insert IDs from the ioBroker Objects page into our script. This is more reliable than typing a long ID by hand. In the screenshot, the mqtt.0.mySwitch state is selected. Its name and instance number may be different in your installation.

Selecting the mqtt.0.mySwitch state from the Objects list
The state selector helps us insert the exact ID.

The question-mark icon opens a documentation panel. It includes descriptions of the JavaScript adapter’s built-in functions. If we are unsure about a function’s parameters, this is a good place to start.

Built-in documentation panel of the JavaScript adapter
The documentation panel helps us use the built-in functions.

The lower part of the page displays the script’s log output. It is especially useful during our first tests and when troubleshooting. The full system log is also available on the ioBroker Logs page.

A few simple JavaScript examples

Try the following examples in separate scripts. The first one needs no additional device. For the later examples, always check the state IDs on the Objects page and replace them with the IDs used in your own system where necessary.

1. Writing a message to the log

Our first script simply writes a message to the log. Create a JavaScript script, paste in the line, save it, and start it. The text will appear in the log panel below when the script runs.

console.log('Hello ioBroker! Hello JavaScript!');
The first JavaScript script and its message in the log
Our first script has written its message to the log.

console.log() writes the value inside its parentheses to the log. Later, we can use messages like this to check whether code has actually run in response to an event.

2. Reading a state value

In the example system shown in the screenshots, the lamp state is mqtt.0.lamp. The getState() function returns the state object; its val property contains the value. The next script reads the state once, when the script starts.

const LIGHT_ID = 'mqtt.0.lamp';
const lightState = getState(LIGHT_ID);

if (lightState && !lightState.notExist) {
  console.log('Lamp state value: ' + lightState.val);
} 
else {
  console.warn('State not found: ' + LIGHT_ID);
}

If your MQTT adapter is not instance mqtt.0, or your lamp has a different name, change the value of LIGHT_ID. This example only reads the state; it does not switch the lamp. The synchronous getState() used in this article assumes the default setting discussed earlier: Do not subscribe all states on start is not enabled.

3. Responding to a switch state

With on(), we can subscribe to changes in a state. The script below watches mqtt.0.mySwitch, which is visible in the screenshot, and writes a log entry whenever its value actually changes. This is a safe first way to check which events arrive from the switch.

const SWITCH_ID = 'mqtt.0.mySwitch';

on({ id: SWITCH_ID, change: 'ne' }, (event) => {
  console.log('New switch value: ' + event.state.val);
});

change: 'ne' means that the function runs when the new value differs from the previous one. event.state.val is the new value. If nothing appears in the log, first check on the Objects page whether the selected state really changes.

4. Switching a lamp in response to an event

Now let us extend the previous idea with a switching command. This example responds when the switch state changes to true. It reverses the lamp’s current Boolean value. A change to false does not switch the lamp again, so releasing a button does not cause a second toggle.

const SWITCH_ID = 'mqtt.0.mySwitch';
const LIGHT_ID = 'mqtt.0.lamp';

on({ id: SWITCH_ID, change: 'ne', val: true }, () => {
  const lightState = getState(LIGHT_ID);

  if (!lightState || lightState.notExist ||
      typeof lightState.val !== 'boolean') {
    console.warn('The lamp state is missing or is not a Boolean value.');
    return;
  }

  setState(LIGHT_ID, !lightState.val);
  console.log('New switching command: ' + !lightState.val);
});

Here, setState() writes a new value to the state. It switches a real lamp only if the selected writable state is connected to a properly configured adapter and device. Not every status state can be used for control. Check the state’s type and purpose in your own system before using this example with a real device. If the MQTT adapter stores the value as text, such as "true", you must adapt this Boolean example to that state first.

For a manual test, first set mySwitch to false, then to true. Another toggle requires a new transition to true. With a physical pushbutton, releasing and pressing it again will usually create that transition, but it is worth checking with the logging example first.

5. Scheduled temperature check

Our final example combines scheduling, reading a state, and a notification adapter. It checks the temperature every two minutes. If the measured value falls below 15 °C, it sends one warning through the Pushsafer adapter. It can send another warning only after the temperature has risen to at least 15 °C and then fallen below the limit again.

This requires an installed and configured Pushsafer adapter and an existing temperature state. Replace TEMPERATURE_ID and, if necessary, PUSHSAFER_INSTANCE with the IDs used in your own system. Start the script only after setting up the notification service.

const TEMPERATURE_ID = 'mqtt.0.temperature';
const PUSHSAFER_INSTANCE = 'pushsafer.0';
const LIMIT_C = 15;

let warningSent = false;

schedule('*/2 * * * *', () => {
  const state = getState(TEMPERATURE_ID);

  if (!state || state.notExist ||
      state.val === null || state.val === undefined ||
      state.val === '') {
    console.warn('No valid temperature reading is available.');
    return;
  }

  const temperature = Number(state.val);

  if (!Number.isFinite(temperature)) {
    console.warn('The temperature cannot be converted to a number.');
    return;
  }

  if (temperature >= LIMIT_C) {
    warningSent = false;
    return;
  }

  if (warningSent) {
    return;
  }

  sendTo(PUSHSAFER_INSTANCE, {
    message: 'Room temperature: ' + temperature + ' °C',
    title: 'Low temperature'
  });

  warningSent = true;
  console.warn('Low temperature: ' + temperature + ' °C');
});

The CRON expression */2 * * * * starts the check every two minutes. The script skips missing values or values that cannot be interpreted as numbers, so an empty value will not accidentally become a 0 °C warning. The warningSent variable exists only in the running script’s memory. If the script or adapter restarts, its value becomes false again, so another notification may be sent if the temperature is still low. For a real alarm application, persistent state storage and error handling need to be designed separately.

Troubleshooting your first scripts

  • The script does not start. Check that the JavaScript adapter instance is running, the script has been saved, and the log does not report a syntax error.
  • No log message appears. Check the log panel below the editor and the ioBroker Logs page. For an event-driven script, the state must actually change.
  • A state cannot be found. The mqtt.0 instance number in the examples belongs to the example system. Copy the exact state ID from the Objects page in your own installation.
  • The state changes, but the lamp does not switch. Check that you selected a writable state intended for control and that the adapter forwards the command to the device.
  • No Pushsafer notification arrives. Check the Pushsafer adapter instance name, its settings, and its log. Also inspect the temperature state’s value separately on the Objects page.

If you are unsure how to use a built-in function, consult the editor’s documentation panel or the official JavaScript adapter function reference.

For more notification examples, see the Pushsafer adapter documentation.


← More ioBroker articles