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
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| App | App | ❌ | — | Application associated with the node. |
| JavaScript Code | JavaScript | ✅ | — | 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:
- Add one or more credentials (Basic Auth, OAuth 2, API Key, private key, Custom).
- Give each a unique alias (e.g.
my_oauth,external_api). - Use the
libs.ecosystemCredentialsAPI 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();
| Method | Credential types | Description |
|---|---|---|
getToken() | OAuth 2, Basic Auth, Custom | Returns the resolved access token |
getHeaders() | API Key | Returns the configured headers |
getQueryParams() | API Key | Returns 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
contextobject - Return the result with
return - Use the standard JavaScript functions
Fullscreen mode
The code editor has a fullscreen mode:
- Click the fullscreen icon at the top of the code editor.
- The editor takes up the full height of the screen — ideal for developing long scripts.
- 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
| Library | Description |
|---|---|
adm-zip | Manipulation of ZIP files. |
ajv | JSON Schema validator. |
axios | HTTP client based on Promises. |
base64 | Base64 encoder/decoder. |
cheerio | Implementation of the core of jQuery for the server. |
convertUnits | Unit conversion and manipulation library. |
crypto | Native Node.js cryptographic module. |
dayjs | Date manipulation library. |
escapeHtml | Escapes HTML characters in a string. |
fastcsv | CSV file parsing module. |
file | Returns a FILE_TOKEN+key. |
google.authLibrary.JWT | JWT client for Google OAuth2. |
google.PubSub | Client for Google Cloud Pub/Sub. |
google.sheetsV4 | Google Sheets v4 API. |
js2xml | Converts JavaScript (JS) to XML. |
json2xml | Converts JSON to XML. |
JSONWebToken | Creates and verifies JSON Web Tokens (JWT). |
lodash | JavaScript utilities library. |
md5 | Computes the MD5 hash of a string. |
oauth1 | Request authorization with OAuth 1.0a. |
turndown | Converts HTML to Markdown. |
utf8 | UTF-8 encoder/decoder. |
uuid | Generates a random v4 UUID. |
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;