Skip to main content

Code node

The Code node allows executing custom JavaScript in your workflow: processing data with custom logic, transforming data, performing complex calculations and implementing specific business logic.

Parameters​

ParameterTypeRequiredDefaultDescription
AppApp❌—Application associated with the node.
JavaScript CodeJavaScript✅—Script executed by the node to transform or process the data.
Authentication (Auth tab)Authentication methods❌—Binding of Ecosystem credentials with an alias to use them in the code.

Authentication tab​

The Code node offers an Auth tab to declare authentication methods usable in your script:

  1. Add one or more credentials (Basic Auth, OAuth 2, API Key, private key, Custom).
  2. Give each a unique alias (e.g. my_oauth, external_api).
  3. Use the libs.ecosystemCredentials API in the code (see below).

The aliases declared in the Auth tab are the only ones accessible at execution.

libs.ecosystemCredentials API​

// OAuth 2, Basic Auth, Custom (token)
const credentials = libs.ecosystemCredentials.get('my_oauth');
const token = credentials.getToken();

// API Key (headers and/or query params)
const apiKey = libs.ecosystemCredentials.get('external_api');
const headers = apiKey.getHeaders();
const queryParams = apiKey.getQueryParams();
MethodCredential typesDescription
getToken()OAuth 2, Basic Auth, CustomReturns the resolved access token
getHeaders()API KeyReturns the configured headers
getQueryParams()API KeyReturns the configured query parameters

If the alias is not declared in the Auth tab, the node fails with an explicit message listing the available aliases.

See also: Authentication method types · Create an authentication method

JavaScript code​

Write your JavaScript code in the editor:

  • Access the context via the context object
  • Return the result with return
  • Use the standard JavaScript functions

Fullscreen mode​

The code editor has a fullscreen mode:

  1. Click the fullscreen icon at the top of the code editor.
  2. The editor takes up the full height of the screen — ideal for developing long scripts.
  3. Exit the fullscreen mode with the same icon or Esc.

Sticky scroll​

The editor applies a sticky scroll: the lines of the function currently being read remain visible at the top of the pane while scrolling, to keep the code context on screen.

Basic structure​

// Access the context data
const inputData = context.data;

// Processing
const processedData = {
// Your logic here
};

// Return the result
return processedData;

Available libraries​

JavaScript libraries are provided in the libs object.

Usage example:

// Generate a UUID
context.yId = libs.uuid();

// Manipulate dates
const now = libs.dayjs().format('YYYY-MM-DD');

// Compute an MD5 hash
const hash = libs.md5('my-string');

List of libraries​

LibraryDescription
adm-zipManipulation of ZIP files.
ajvJSON Schema validator.
axiosHTTP client based on Promises.
base64Base64 encoder/decoder.
cheerioImplementation of the core of jQuery for the server.
convertUnitsUnit conversion and manipulation library.
cryptoNative Node.js cryptographic module.
dayjsDate manipulation library.
escapeHtmlEscapes HTML characters in a string.
fastcsvCSV file parsing module.
fileReturns a FILE_TOKEN+key.
google.authLibrary.JWTJWT client for Google OAuth2.
google.PubSubClient for Google Cloud Pub/Sub.
google.sheetsV4Google Sheets v4 API.
js2xmlConverts JavaScript (JS) to XML.
json2xmlConverts JSON to XML.
JSONWebTokenCreates and verifies JSON Web Tokens (JWT).
lodashJavaScript utilities library.
md5Computes the MD5 hash of a string.
oauth1Request authorization with OAuth 1.0a.
turndownConverts HTML to Markdown.
utf8UTF-8 encoder/decoder.
uuidGenerates a random v4 UUID.
info

The examples above (libs.uuid(), libs.dayjs(), libs.md5()) illustrate some common uses; each library of the list is used the same way through the libs object.

:::

Available functions​

Standard JavaScript functions​

All JavaScript functions are available:

  • JSON.parse(), JSON.stringify()
  • Array.map(), Array.filter(), Array.reduce()
  • String.split(), String.replace()
  • Date, Math, etc.

Examples​

// Request body: object or JSON string depending on the case
const order = typeof context.data === 'string' ? JSON.parse(context.data) : context.data;

// Array manipulation
const activeItems = context.items.filter(item => item.active);

// Date formatting
const date = new Date(context.timestamp);
const formattedDate = date.toISOString();

// Calculations
const average = context.numbers.reduce((a, b) => a + b) / context.numbers.length;

Input​

The node receives the workflow context, which contains all the data of the previous nodes:

// Trigger data (see also [Trigger node](./trigger-node.md))
context.data
context.incomingRequest.headers
context.incomingRequest.query

// Results of the previous nodes
context.lastResponse.data
context.condition.result
context.forEach.item

// Global variables
context.variables.myVariable

Usage example​

// Retrieve the data
const order = context.data;
const user = context.lastResponse.data;

// Processing
const total = order.items.reduce((sum, item) => {
return sum + (item.price * item.quantity);
}, 0);

const discount = user.plan === 'premium' ? total * 0.1 : 0;
const finalTotal = total - discount;

// Return the result
return {
orderId: order.id,
total: finalTotal,
discount: discount,
items: order.items
};

Output​

The node returns the result of the script via the return statement. This result is injected into the context and remains accessible to the following nodes — the results of the previous nodes are notably read via context.lastResponse.data.

Simple return​

return {
success: true,
data: processedData
};

Conditional return​

if (condition) {
return { status: 'approved' };
} else {
return { status: 'rejected' };
}

You can also write directly in the context, for example context.yId = libs.uuid() (see Available libraries).

Errors​

  • Missing authentication alias — if the alias is not declared in the Auth tab, the node fails with an explicit message listing the available aliases.
  • JavaScript exception — an error thrown in the script (via throw) is passed to the On Error node.

Try/Catch​

Use try/catch to handle errors:

try {
const result = processData(context.data);
return result;
} catch (error) {
// The error will be handled by the On Error node
throw error;
}

Validation​

Validate the data before processing:

if (!context.data || !context.data.orderId) {
throw new Error('Order ID is required');
}

// Processing...

Limits​

  • Execution time: the code must run quickly.
  • Memory: avoid memory-consuming operations.
  • External APIs: use HTTP(S) Request nodes for API calls.
  • Files: use the FTP nodes for file operations.

Example​

Example 1: Data transformation​

const input = context.data;

const transformed = {
id: input.order_id,
customer: {
name: `${input.first_name} ${input.last_name}`,
email: input.email_address
},
items: input.products.map(product => ({
sku: product.product_sku,
quantity: product.qty,
price: product.price
}))
};

return transformed;

Example 2: Complex calculation​

const order = context.data;

// Total calculation
const subtotal = order.items.reduce((sum, item) => {
return sum + (item.price * item.quantity);
}, 0);

// Tax calculation
const taxRate = 0.20; // 20%
const tax = subtotal * taxRate;

// Shipping calculation
const shipping = order.shippingMethod === 'express' ? 15 : 5;

// Final total
const total = subtotal + tax + shipping;

return {
subtotal: subtotal,
tax: tax,
shipping: shipping,
total: total
};

Example 3: Validation and transformation​

const data = context.data;

// Validation
if (!data.email || !data.email.includes('@')) {
throw new Error('Invalid email address');
}

// Transformation
const normalized = {
email: data.email.toLowerCase().trim(),
name: data.name.trim(),
age: parseInt(data.age, 10)
};

// Age validation
if (isNaN(normalized.age) || normalized.age < 0) {
throw new Error('Invalid age');
}

return normalized;

See also​