JavaScript code in a scenario
How to compute, transform data, parse an external system response or build a text with a few lines of JavaScript and write the result into scenario variables.
The "JavaScript code" block helps where the regular blocks fall short: compute a discount by a formula, pick what you need from an external system response, bring a phone number to one format, build a phrase with the right word forms. The code receives the run data, returns a result, and the result lands in variables that then work in conditions, texts and other blocks like any {{vars.…}}.
Where to find the block
- Open the scenario in Automation and go to the editor.
- In the block library open the Operations group and drag the JavaScript code block onto the canvas.
- In the block panel fill in Code, add Result variables and, if you like, a Note: it is shown on the block card on the canvas.
- Press Check in the Check on a sample section, make sure the result is what you need, and connect the block exits.
The block has two exits: Next (the code ran, the variables are written) and Error (syntax, an exception in the code, time or memory exceeded, the code service unavailable).
How to write the code
Write the body of a function, not a whole program: the code runs as a function with a single input argument in strict mode ("use strict"). Return the result with return. There is no need to declare a function, export anything or load modules.
Placeholders {{…}} do not work in the code: it is passed as is. Take the data from the input object. The Insert variable button in the editor inserts exactly that path in input, such as input.vars.amount, not {{vars.amount}}.
What is in input
| Field | What it holds |
|---|---|
input.vars | Run variables, the same as {{vars.…}}: values from the blocks above, client replies, fields of an external system response. |
input.trigger | Data of the event that started the scenario, the same as {{trigger.…}}. For a webhook start the request body is in input.trigger.body. |
input.contact | The run contact: id, name, phone, email, tags (a list), custom (contact custom fields). |
input.conversation | custom: conversation custom fields. |
input.const | Company constants, the same as {{const.…}}. |
input.company | id and timezone (the company time zone). |
input.run | The run id and is_test: true in a test run and in a check on a sample. |
input holds only the data the scenario placeholders already reach, nothing beyond that. Empty sections come as an empty object {}, so input.vars.x is always safe to read without checking input.vars itself for undefined. Variables and constants are often stored as strings: convert them with Number(…) before arithmetic. If the input is larger than 512 KB, the webhook body is dropped first, then the constants; if that is still too much, the step takes the Error exit.
What to return and where it goes
In Result variables list the names of the variables the code may write to: from 1 to 20, a name starts with a Latin letter or _, then letters, digits and _, up to 64 characters. The code writes only to these variables and leaves the other run variables alone.
- You returned an object. Each declared variable takes the value of the key with the same name. A missing key or a
nullvalue clears the variable. Keys that are not in the list are skipped. - You returned a string, a number, `true`/`false` or a list, and there is one variable. The whole value goes into that variable.
- You returned something other than an object, and there are several variables. The step takes the Error exit with the reason "An object with variable keys is needed".
- You returned `null` or nothing at all. All declared variables are cleared. A forgotten
returnclears them too, and the check on a sample shows it.
Numbers and booleans keep their type; nested objects and lists are stored as a structure. A long string is cut to the size of one variable (8 KB). A run holds at most 50 variables: if there is no room left, the step takes the Error exit, and some variables may already be written by then. Further down the scenario the result is used as usual: {{vars.total}}.
You can await a value that is already available, but there are no timers or network in the block: a promise that never settles gives the "A promise never finished" error. Compute synchronously.
Examples
A discount by a formula
The order amount is in the amount variable, the discount percent in the company constant discount_percent. Result variables: discount and total. Further on, in a message: "Your total with the discount: {{vars.total}}".
const amount = Number(input.vars.amount) || 0;
const percent = Number(input.const.discount_percent) || 0;
const discount = Math.round(amount * percent / 100);
return { discount: discount, total: amount - discount };Parsing an external system response
The Send webhook block saved the list of goods from the response into the items variable. The code keeps only the goods in stock, counts them and takes the title of the first one. If nothing is in stock, first_title is cleared (null). Then an If / Else branch block splits the scenario on available_count.
let items = input.vars.items;
if (typeof items === 'string') {
items = JSON.parse(items || '[]');
}
if (!Array.isArray(items)) {
items = [];
}
const available = items.filter((item) => item && item.in_stock);
console.log('items:', items.length, 'in stock:', available.length);
return {
available_count: available.length,
first_title: available.length > 0 ? available[0].title : null,
};A phone number in one format
There is one result variable, phone_e164, so the code returns a string, not an object. If there are too few digits, the variable is cleared.
const digits = String(input.contact.phone || '').replace(/\D/g, '');
return digits.length >= 10 ? '+' + digits : null;A text with the right word form
Build a phrase such as "Anna, you have 3 bonuses" with the right word form (Russian has three plural forms) and insert it into a message as {{vars.greeting}}.
const name = String(input.contact.name || '').trim().split(' ')[0] || 'Здравствуйте';
const count = Number(input.vars.bonus) || 0;
const mod10 = count % 10;
const mod100 = count % 100;
let word = 'бонусов';
if (mod10 === 1 && mod100 !== 11) {
word = 'бонус';
} else if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) {
word = 'бонуса';
}
return name + ', у вас ' + count + ' ' + word;Check on a sample
The block panel has a Check on a sample section. The Sample input (JSON) field is prefilled with the variables of the blocks above and the webhook keys: change the values to try different cases, such as an empty list or a missing field. The sample sets vars, trigger and contact; the constants are the real ones, conversation custom fields are empty in a check, and input.run.is_test is true. The sample is up to 64 KB.
After you press Check, the code runs in the same environment and with the same limits as in a real run. The panel shows:
- Result: what the code returned (a long result is shown only in part);
- Log: the lines printed with
console.log; - What will be written: for each variable "will be written", "will be cleared" or "not declared" (the key is in the result but not in the variable list);
- on an error: its text and the highlighted code line. In a scenario such a step would take the Error exit.
A check writes nothing and does not start the scenario; the sample is not stored. There are at most 20 checks per minute per user (and 60 per minute per company). If the code service is busy or unavailable, repeat the check in a few seconds; it does not affect saving the block. The block also runs in a scenario test run: it writes only run variables, so it changes nothing outside the run.
Restrictions and limits
Standard JavaScript is available: objects and lists, strings, regular expressions, Math, JSON, Date. Each call of the block runs in a new clean environment: nothing from past runs or other blocks stays there, data is exchanged only through input and variables.
| What is not there | What to do instead |
|---|---|
Network: fetch, requests to sites and APIs | Make the request with the Send webhook block, save the response into a variable and parse it in code. |
Timers: setTimeout, setInterval | Use the scenario wait block for a pause. |
Modules and libraries: require, import | Write the functions you need right in the block code. |
| Files, environment and process | Pass the data you need through variables and constants. |
Intl and locale formatting | Format numbers and dates by hand. Time in the code is UTC; the company time zone is in input.company.timezone. |
| Limit | Value |
|---|---|
| Code size | 16,384 bytes (16 KB). A Cyrillic character takes 2 bytes. |
| Run time | About 1 second of CPU time per call, then the code is stopped. |
| Memory | Capped at a few dozen megabytes: enough for ordinary objects and lists, but not for huge arrays and strings built in a loop. |
| Input data | Up to 512 KB (see above for what is dropped beyond that). |
| Result | Up to 64 KB as JSON. |
| Log | Up to 20 lines of 200 characters, the rest is cut. |
| Result variables | 1 to 20 per block. |
| One scenario run | At most 50 code block calls and about 3 seconds of CPU time for all such blocks together. This guards against looping scenarios. |
The Error exit
The Error exit usually leads to a notification for the person in charge, an internal note or a safe default. If the code service is temporarily unavailable or overloaded, the step does not fail at once: it waits and retries automatically (after 5, 20 and 60 seconds; the run log shows the status "Waiting for the code service"), and takes the Error exit only after the last failed attempt. A test run has no retries: the step takes the Error exit at once.
Errors and what they mean
The error reason is shown in the scenario run log (and in a check on a sample). The reason code in brackets comes in the API in the step reason field.
| Error | What it means and what to do |
|---|---|
Syntax error in the code (syntax_error) | An unclosed bracket, quote or a typo. Press Check and fix the highlighted line. |
The code failed while running (script_error) | The code threw an exception, such as reading a field of an empty value. Add a check for empty values. |
The code ran out of time (timeout) | Usually an endless loop or going through a very large list. |
The code ran out of memory (memory_limit) | Do not build large arrays and strings in a loop. |
Recursion is too deep (stack_overflow) | Replace recursion with a loop or limit its depth. |
The result is too large (output_too_large) | The code returned more than 64 KB. Return only the fields you need. |
The result cannot be stored (result_not_serializable) | A function, a circular reference, a BigInt or a too deeply nested object was returned. Return a plain object, string or number. |
A promise never finished (unresolved_promise) | There are no timers or network, compute synchronously. |
An object with variable keys is needed (result_not_object) | There are several variables, but the code did not return an object. Return { name: value } or keep one variable. |
No room for the variables (variable_limit) | The run is out of variables. Some of them may already be written. |
Too much input data (input_too_large), the data could not be passed to the code (input_invalid) | Reduce the webhook and variable data or check their values. |
The block is set up wrong (code_invalid_config) | The code is empty or too long, or the variable list is wrong. Open the block and fix it. |
The code limit of the run is used up (budget_exhausted) | Code blocks were called too often or ran too long in one run. Check the scenario for a loop. |
The code service is unavailable or overloaded (sandbox_unavailable, sandbox_busy) | A failure or load on our side, the code needs no change. It appears after all retries. |
The code block is switched off (feature_disabled) | Code execution is switched off for the company or the platform. The block can be saved, but the step takes the Error exit. |
Internal error (internal_error) and other platform errors | A failure on our side. If it repeats, contact support. |
The console.log log
console.log, console.info, console.warn and console.error work inside the code. Objects are printed as JSON. The first 20 lines of 200 characters are kept. The log is shown in a check on a sample and in the scenario run log, next to the error reason and the line where it happened.
Who can use the block
- Adding the block, writing code and checking it on a sample needs the Automation → Edit right (
automation.update). There is no separate right for code: the block sees the same data as{{…}}placeholders. - The script log, the error text and the step details in the run log are visible only to roles with the Automation → Personal data in the log right: they may contain customer data. Without that right the step details are hidden entirely.
- The code is visible to everyone who can edit scenarios. Do not put passwords or keys in the code: it has no network access anyway.
Privacy
The code and the data it processes are not written to platform logs: the code service keeps only technical details (a code fingerprint, timings), not the code itself, the input or the result. The step entry in the run log keeps the names of the written and cleared variables, the number of skipped keys, the timings, the error reason and the console.log lines; the values of input and of the result are not stored there. The sample of a check is not stored anywhere. You write the log lines yourself, so do not print personal data with console.log unless you need to.
For developers
The check on a sample is available through the API: POST /v1/automations/code/check with a code, variables and sample body. Fields, response and limits are in the REST reference, the Automations group. Related articles: Automations: everyday scenarios without a developer, Variables, constants and buttons in scenarios, CRM blocks in scenarios.