Skip to main content

What It Does

The JavaScript Code node executes a JS snippet in an isolated environment with no access to the network or file system. Use it when data transformations become too complex for {{ }} expressions, or when you need conditional logic, iteration, or string manipulation that other nodes do not cover natively. Typical use cases:
  • Transform the structure of a JSON returned by an external API
  • Validate fields and throw descriptive errors when data is missing
  • Calculate derived values (discount, due date, hash)
  • Combine data from multiple upstream nodes into a single object
  • Format strings: masked IDs, localized dates, URL slugs

Input and Output

Variables available in the code scope:
VariableTypeDescription
inputanyOutput of the immediately preceding node ($json)
triggerobjectFull trigger payload (body, headers, query, method)
varsobjectWorkflow variables defined by Set Variable nodes
Output: the value returned via return is exposed as $json to downstream nodes. It can be an object, array, string, number, or boolean.

Configuration

1

Add the node to the flow

In the component palette, select Actions > JavaScript Code and drag it onto the canvas.
2

Write the code in the editor

The editor accepts modern JavaScript (ES2020+). Use return to define the node’s output.Auto-generated starter template:
// Access input data via 'input'
// Return the result with 'return'

const data = input;

const result = {
  processed: true,
  original:  data,
  timestamp: new Date().toISOString()
};

return result;
3

Reference flow variables

Do not use {{ }} expressions inside JS code — access data through the global variables:
// Correct
const nome = trigger.body.cliente.nome;
const plano = vars.plano_selecionado;

// Incorrect — {{ }} is not interpolated inside the JS editor
const nome = "{{ $trigger.body.cliente.nome }}";
4

Use console.log for debugging

console.log() is available and logs appear in the node’s execution panel during tests. In production, logs are discarded.
5

Test the node

Click Test in the node panel. The runtime executes the code with the pinned output data from upstream nodes and displays the result and execution duration.

Available APIs

The runtime is isolated — there is no access to the network, file system, or environment variables. The available JavaScript APIs are:
APIAvailable
JSON.parse() / JSON.stringify()yes
Math.*yes
Dateyes
RegExpyes
Array.* / Object.* / String.*yes
console.log()yes (debug only)
fetch() / XMLHttpRequestno
fs / path / Node.js modulesno
setTimeout / setIntervalno
require() / importno

Examples

Transform API response structure

The external API returns a format different from what downstream nodes expect.
{
  "status": 200,
  "body": {
    "data": {
      "customer_id":    "C-4821",
      "full_name":      "Ana Lima",
      "contact_email":  "ana@empresa.com",
      "is_premium":     true,
      "created_at":     "2025-01-15T10:30:00Z"
    }
  }
}

Format and validate a CPF

const cpfRaw = trigger.body.cpf || '';
const numeros = cpfRaw.replace(/\D/g, '');

if (numeros.length !== 11) {
  return { valido: false, cpf: null, erro: 'CPF deve ter 11 dígitos' };
}

const cpfFormatado = numeros.replace(
  /(\d{3})(\d{3})(\d{3})(\d{2})/,
  '$1.$2.$3-$4'
);

return { valido: true, cpf: cpfFormatado, erro: null };
The downstream Condition node checks {{ $json.valido }} and routes to the error path when false.

Calculate a due date

const diasParaVencer = vars.prazo_dias || 30;
const hoje = new Date();
hoje.setDate(hoje.getDate() + Number(diasParaVencer));

return {
  vencimento_iso: hoje.toISOString().split('T')[0],
  vencimento_br:  hoje.toLocaleDateString('pt-BR'),
  dias_restantes: Number(diasParaVencer)
};

Combine data from multiple nodes

When you need to assemble an object with fields coming from different nodes (HTTP, LLM, and trigger), use the JavaScript node as a consolidation point before sending.
// Data from the trigger
const cliente = trigger.body.cliente;

// Output of the HTTP node (saved to a variable via Set Variable node)
const pedido = vars.dados_pedido;

// Output of the LLM node (output of the preceding node)
const classificacao = input.result;

return {
  cliente_nome:   cliente.nome,
  cliente_email:  cliente.email,
  pedido_id:      pedido.id,
  pedido_valor:   pedido.valor,
  intencao:       classificacao.intencao,
  prioridade:     classificacao.confianca > 0.8 ? 'alta' : 'normal',
  gerado_em:      new Date().toISOString()
};

Filter and sort an array

const itens = input.body.itens || [];

const ativos = itens
  .filter(item => item.ativo === true)
  .sort((a, b) => b.valor - a.valor)
  .slice(0, 5);

return {
  total_recebidos: itens.length,
  total_ativos:    ativos.length,
  top5:            ativos
};

Error Handling

If the code throws an uncaught exception, the node marks the execution as failed and the error appears in the execution logs. To handle errors in a controlled way, use try/catch:
try {
  const dados = JSON.parse(trigger.body.payload_raw);
  return { sucesso: true, dados };
} catch (err) {
  return { sucesso: false, erro: err.message, dados: null };
}

Limits

ParameterValue
Execution timeout10 seconds
Network accessNot allowed
File system accessNot allowed
require() / external modulesNot supported
Maximum script sizeNo documented limit
Maximum output size10 MB
Infinite loops or very heavy synchronous operations cause a timeout after 10 seconds. Prefer array processing with Array.map() and Array.filter() instead of while loops without a clear exit condition.

Next Steps