logo_smallAxellero.io

JavaScript Node

Execute ECMAScript 5.1 compatible JavaScript code in Axellero workflows.

JavaScript Node

Execute JavaScript code in a secure JavaScript sandbox with access to built-in utilities for data processing, API calls, and workflow automation.

JavaScript Sandbox Limitations

Critical Limitation

The JavaScript sandbox only supports ECMAScript 5.1. Modern ES6+ features are NOT supported and will cause runtime errors.

  • let/const, arrow functions, template literals
  • Array.find(), Array.includes(), Object.assign()
  • Promise, async/await, classes

Use ES5.1 Compatible Syntax

  • var declarations (not let/const)
  • function() {} syntax (not arrow functions =>)
  • String concatenation with + (not template literals)
  • Traditional for loops (not for...of)
  • ES5.1 methods only

See the complete ES5.1 syntax guide below for detailed examples.

Quick Navigation

Workflow Context Access

JavaScript nodes have full access to the workflow execution context via the global ctx object, just like all other core nodes. This provides complete access to node data, variables, constants, and system information.

📖 Reference

For comprehensive context documentation, see the Workflow Context reference.

Context Structure

The ctx object contains:

var ctx = {
  nodes: {
    // Access inputs, outputs, metadata, and errors from all executed nodes
    start: { inputs: {}, outputs: {}, metadata: {} },
    apiCall: { inputs: {}, outputs: {}, metadata: {}, error: "" },
    dataProcessor: { inputs: {}, outputs: {}, metadata: {} }
  },
  vars: {},              // Workflow variables (mutable during execution)
  consts: {},            // Workflow constants (immutable values)
  workspace_id: "uuid",  // Unique workspace identifier
  workspace_slug: "workspace-name", // Human-readable workspace name
  app_id: "uuid",       // Unique application identifier
  app_slug: "app-name", // Human-readable application name
  user: {
    id: "uuid",         // Unique user identifier
    login: "username",   // Username or email
    roles: ["role1", "role2"], // Array of user roles
    attrs: {}           // Additional user attributes
  }
};

Accessing Node Data

// Get inputs and outputs from any executed node
var userData = ctx.nodes.start.inputs.userData;
var apiResponse = ctx.nodes.apiCall.outputs.data;
var processedData = ctx.nodes.dataProcessor.outputs.result;

// Check for node execution errors
if (ctx.nodes.apiCall.error) {
  return { success: false, error: ctx.nodes.apiCall.error };
}

// Access detailed metadata (varies by node type)
var httpStatus = ctx.nodes.apiCall.metadata.statusCode;
var responseHeaders = ctx.nodes.apiCall.metadata.response.headers;
var requestBody = ctx.nodes.apiCall.metadata.request.body;

Working with Variables and Constants

// Read workflow variables (mutable during execution)
var userSettings = ctx.vars.userSettings;
var sessionData = ctx.vars.currentSession;

// Also access other context data as needed
var previousNodeData = ctx.nodes.dataProcessor.outputs.result;
var userRole = ctx.user.roles[0] || 'user';

// Read workflow constants (immutable configuration)
var apiEndpoint = ctx.consts.API_BASE_URL;
var maxRetries = ctx.consts.MAX_RETRY_ATTEMPTS;

// JavaScript nodes are read-only for variables
// Results are automatically stored in workflow context for subsequent nodes

💡 Helper Functions

For safe variable access, use the defaultValue() helper function to handle undefined values gracefully.

System and User Information

// Access workspace and application context
var workspaceId = ctx.workspace_id;
var workspaceName = ctx.workspace_slug;
var appId = ctx.app_id;
var appName = ctx.app_slug;

// Access current user information
var currentUser = ctx.user.login;
var userId = ctx.user.id;
var userRoles = ctx.user.roles;
var userAttributes = ctx.user.attrs;

// Check user permissions (ES5.1 compatible)
var isAdmin = false;
for (var i = 0; i < ctx.user.roles.length; i++) {
  if (ctx.user.roles[i] === 'admin') {
    isAdmin = true;
    break;
  }
}

Complete Workflow Example

This example demonstrates core concepts covered in this guide: workflow context access, ES5.1 syntax, and built-in utilities.

// Access data from previous nodes and workflow context
var orders = ctx.nodes.dataSource.outputs.orders || [];
var userRole = ctx.user.roles[0] || 'user';
var currencyRate = ctx.consts.USD_RATE || 1.0;

// Check if previous node had errors
if (ctx.nodes.dataSource.error) {
  return {
    success: false,
    error: 'Data source failed: ' + ctx.nodes.dataSource.error
  };
}

// Process data (ES5.1 compatible)
var processedOrders = [];
var totalValue = 0;
var userCanViewAll = (userRole === 'admin' || userRole === 'manager');

for (var i = 0; i < orders.length; i++) {
  var order = orders[i];
  
  // Apply user-based filtering
  if (!userCanViewAll && order.userId !== ctx.user.id) {
    continue;
  }
  
  // Process and convert currency
  var processedOrder = {
    id: order.id,
    amount: order.amount * currencyRate,
    status: order.status,
    timestamp: order.createdAt,
    processedBy: ctx.user.login
  };
  
  processedOrders.push(processedOrder);
  totalValue += processedOrder.amount;
}

// Return result (automatically stored in workflow context)
return {
  processedOrders: processedOrders,
  totalValue: totalValue,
  count: processedOrders.length,
  processor: ctx.user.login,
  workspace: ctx.workspace_slug,
  timestamp: new Date().toISOString()
};

ES5.1 Syntax Requirements

Important

All JavaScript code must be ES5.1 compatible. Use the patterns below for reliable execution. See practical examples for real-world usage.

Supported (ES5.1 Compatible Syntax)

Not supported (Non ES6+ Syntax)

🚫 Runtime Errors

The following modern JavaScript features will cause runtime errors in the sandbox. Always use ES5.1 alternatives.

Built-in Utility Functions

✨ Available Functions

JavaScript nodes provide these utility functions for common operations. All functions are pre-loaded and available globally. See usage examples for practical implementations.

Function Reference

CategoryFunctionsPurpose
Base64 Encodingbase64encode(), base64decode()Encode and decode Base64 strings
Cryptographic Functionscrypto.sha256(), crypto.hmac256(), crypto.aes.encrypt(), crypto.aes.decrypt()Secure hashing, HMAC signing, AES encryption
Random Generationrandom.uuid(), random.uuidv7(), random.int(), random.string()Generate UUIDs, numbers, and strings
XML/JSON Conversionconvert.xmlToJSON(), convert.jsonToXML()Convert between XML and JSON formats
String Utilitiesstrings.xmlEscape(), strings.jsonEscape(), strings.jsonUnescape()Escape special characters
File Access & HelpersgetFileContent(), defaultValue()File access and value fallback handling

Base64 Encoding

base64encode(string) - Encode a string to Base64 format
base64decode(string) - Decode a Base64 encoded string

// Encoding example
var text = "Hello World!";
var encoded = base64encode(text);
// Result: "SGVsbG8gV29ybGQh"

// Decoding example
var decoded = base64decode(encoded);
// Result: "Hello World!"

return { encoded: encoded, decoded: decoded };

Cryptographic Functions

🔐 Security Warning

These functions use cryptographically secure algorithms. Handle keys and sensitive data carefully.

crypto.sha256(string) - Generate SHA-256 hash
crypto.hmac256(message, secret) - Generate HMAC-SHA256 signature
crypto.aes.encrypt(plaintext, passphrase, algorithm?) - AES-256-GCM encryption
crypto.aes.decrypt(ciphertext, nonce, salt, passphrase, algorithm?) - AES-256-GCM decryption

// SHA-256 hashing
var hash = crypto.sha256("password123");

// HMAC signing
var signature = crypto.hmac256("user@example.com", "secret-key");

// AES encryption (returns {ciphertext, nonce, salt})
var encrypted = crypto.aes.encrypt("sensitive data", "passphrase");

// AES decryption
var decrypted = crypto.aes.decrypt(
  encrypted.ciphertext, 
  encrypted.nonce, 
  encrypted.salt, 
  "passphrase"
);

return { hash: hash, signature: signature, decrypted: decrypted };

💡 Error Handling

For production code, wrap crypto operations in try/catch blocks. See Error Handling patterns for best practices.

Random Generation

random.uuid() - Generate random UUID v4
random.uuidv7() - Generate time-ordered UUID v7
random.int(min, max) - Generate random integer between min and max (inclusive)
random.string(length) - Generate random string of specified length

// Generate IDs
var id = random.uuid();                    // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
var timeId = random.uuidv7();             // "017F22E2-79B0-7CC3-98C4-DC0C0C07398F"

// Generate numbers and strings
var randomNum = random.int(1, 100);       // 42
var token = random.string(16);            // "a7b2c9d4e8f1g5h3"

return { id: id, timeId: timeId, randomNum: randomNum, token: token };

💡 Usage Tip

Random IDs are commonly used in Data Validation patterns for generating unique identifiers.

XML/JSON Conversion

convert.xmlToJSON(xml) - Convert XML string to JSON object
convert.jsonToXML(json, options?) - Convert JSON object to XML string

// XML to JSON conversion
var xml = '<user><name>John</name><age>30</age></user>';
var json = convert.xmlToJSON(xml);

// JSON to XML conversion  
var data = { user: { name: "John", age: 30 } };
var xmlOutput = convert.jsonToXML(data);

return { json: json, xml: xmlOutput };

💡 Data Processing

XML/JSON conversion is frequently used in Data Transformation patterns for API integrations.

String Utilities

strings.xmlEscape(str) - Escape special XML characters
strings.jsonEscape(str) - Escape special JSON characters
strings.jsonUnescape(str) - Unescape JSON-escaped characters

// XML escaping
var text = 'Hello <world> & "friends"';
var xmlEscaped = strings.xmlEscape(text);      // "Hello &lt;world&gt; &amp; &quot;friends&quot;"

// JSON escaping and unescaping
var text2 = 'Line 1\nLine 2\tTabbed';
var jsonEscaped = strings.jsonEscape(text2);
var jsonUnescaped = strings.jsonUnescape(jsonEscaped);

return { xmlEscaped: xmlEscaped, jsonEscaped: jsonEscaped, jsonUnescaped: jsonUnescaped };

File Access & Helpers

getFileContent(blobId) - Get file content by blob ID
defaultValue(value, fallback) - Return value or fallback if value is null/undefined

// File access
var fileId = ctx.vars.uploadedFileId;
var content = getFileContent(fileId);

// Default value handling
var userName = defaultValue(ctx.vars.userName, ctx.user.login || "Anonymous");
var userAge = defaultValue(ctx.vars.userAge, 0);
var items = defaultValue(ctx.vars.items, []);

return { content: content, userName: userName, userAge: userAge, items: items };

Logging

🪵 Debug Output

All standard console methods are available for debugging and monitoring. The JavaScript sandbox provides complete console object functionality.

console.log("Info message", { data: value });
console.warn("Warning message");
console.error("Error message", error);
console.debug("Debug information");
console.info("Information message");

💡 Best Practice

Use logging extensively in Error Handling patterns to debug issues in production workflows.

Common Patterns

💡 Proven Patterns

Use these proven patterns for common JavaScript node operations. All examples are ES5.1 compatible and use the built-in functions covered above.

Best Practices

📋 Guidelines for Reliable JavaScript Nodes

  1. Use ES5.1 syntax only - No modern JavaScript features
  2. Validate inputs - Always check for undefined/null values
  3. Use workflow context - Access full context via ctx object including nodes, vars, consts, user, and system data
  4. Return structured data - Use objects for complex results
  5. Handle errors gracefully - Use try/catch blocks
  6. Use built-in utilities - Leverage provided functions for common operations
  7. Keep code focused - Single responsibility per node
  8. Log appropriately - Use console methods for debugging

Complete Examples

🚀 Real-World Examples

These examples demonstrate real-world usage patterns with full workflow context access and ES5.1 compatibility.