Skip to main content

Code

The Code node allows you to execute custom JavaScript code within your workflows, providing unlimited flexibility for data transformation, business logic implementation, and complex calculations that aren't available in standard nodes.

Overview

The Code node is essential when you need to:

  • Transform data - Convert between formats, restructure objects, or calculate derived values
  • Implement business logic - Apply complex rules that require custom programming
  • Process arrays - Loop through collections, filter items, or aggregate data
  • Call external APIs - Make HTTP requests with custom headers and authentication
  • Validate data - Perform complex validation beyond standard node capabilities
  • Generate content - Create dynamic text, HTML, or other formatted output

Configuration

Parameters

The Code node provides access to workflow data through parameters:

  • Default data parameter - Automatically contains output from the previous workflow node
  • Additional named parameters - Define custom parameters with specific names to access data from other workflow nodes
  • Data mapping - Each parameter can be mapped to data from any previous node in the workflow
  • Type flexibility - Parameters can contain any JavaScript data type (String, Number, Boolean, Object, Array)

Code Editor

Write JavaScript code using the built-in editor with:

  • Syntax highlighting - Color-coded JavaScript syntax
  • Auto-completion - Suggestions for variables and functions
  • Error detection - Real-time syntax error highlighting
  • Multi-line support - Full JavaScript code blocks

JavaScript Environment

Available Variables

  • Configured parameters - Access via the names you defined
  • Standard JavaScript - All built-in JavaScript functions and objects

Built-in Libraries

  • Date manipulation - Full Date object support
  • Math operations - Complete Math library
  • String processing - Regular expressions and string methods
  • JSON handling - JSON.parse() and JSON.stringify()

Return Values

Your code must return a value that becomes the node's output:

// Return a simple value
return "Hello World";

// Return an object
return {
processedData: transformedValue,
timestamp: new Date().toISOString()
};

// Return an array
return items.map(item => item.name);

Example Usage

Data Transformation

// Parameters: shipmentData (object)
// Transform shipment status to standardized format

const statusMap = {
'In Transit': 'TRANSIT',
'Delivered': 'DELIVERED',
'Delayed': 'DELAYED'
};

return {
id: shipmentData.tracking_number,
status: statusMap[shipmentData.current_status] || 'UNKNOWN',
lastUpdate: new Date(shipmentData.last_updated).toISOString(),
estimatedDelivery: shipmentData.eta
};

Array Processing

// Parameters: invoices (array)
// Calculate total value and filter high-value invoices

const highValueThreshold = 10000;
const totalValue = invoices.reduce((sum, inv) => sum + inv.amount, 0);
const highValueInvoices = invoices.filter(inv => inv.amount > highValueThreshold);

return {
totalValue: totalValue,
invoiceCount: invoices.length,
highValueInvoices: highValueInvoices,
averageValue: totalValue / invoices.length
};

Business Logic Implementation

// Parameters: customer (object), orderValue (number)
// Apply dynamic pricing based on customer tier and order size

let discountRate = 0;

// Customer tier discounts
if (customer.tier === 'PREMIUM') {
discountRate = 0.15;
} else if (customer.tier === 'GOLD') {
discountRate = 0.10;
} else if (customer.tier === 'SILVER') {
discountRate = 0.05;
}

// Volume discounts
if (orderValue > 50000) {
discountRate += 0.05;
} else if (orderValue > 25000) {
discountRate += 0.03;
}

// Cap maximum discount
discountRate = Math.min(discountRate, 0.25);

const discountAmount = orderValue * discountRate;
const finalAmount = orderValue - discountAmount;

return {
originalAmount: orderValue,
discountRate: discountRate,
discountAmount: discountAmount,
finalAmount: finalAmount,
customerTier: customer.tier
};

Date and Time Processing

// Parameters: deliveryDate (string), businessHours (object)
// Calculate business days until delivery

const delivery = new Date(deliveryDate);
const today = new Date();
const msPerDay = 24 * 60 * 60 * 1000;

let businessDays = 0;
let currentDate = new Date(today);

while (currentDate < delivery) {
const dayOfWeek = currentDate.getDay();
// Skip weekends (0 = Sunday, 6 = Saturday)
if (dayOfWeek !== 0 && dayOfWeek !== 6) {
businessDays++;
}
currentDate.setDate(currentDate.getDate() + 1);
}

return {
deliveryDate: delivery.toISOString(),
businessDaysUntilDelivery: businessDays,
isUrgent: businessDays <= 2,
weekendDelivery: delivery.getDay() === 0 || delivery.getDay() === 6
};

Best Practices

Code Organization

  • Keep it focused - Each Code node should have a single, clear purpose
  • Use comments - Document complex logic for future maintenance
  • Handle errors - Use try/catch blocks for operations that might fail
  • Validate inputs - Check parameter values before processing

Performance

  • Minimize complexity - Avoid deeply nested loops or recursive functions
  • Efficient algorithms - Use appropriate data structures and methods
  • Limit external calls - Minimize HTTP requests within code blocks
  • Cache calculations - Store expensive computations in variables

Debugging

  • Use console.log() - Output intermediate values for troubleshooting
  • Test incrementally - Build complex logic step by step
  • Validate outputs - Ensure return values match expected format
  • Handle edge cases - Test with null, undefined, and empty values

Error Handling

Common Issues

  • Undefined parameters - Check if required data is available
  • Type mismatches - Verify data types match expectations
  • Syntax errors - Use the editor's error highlighting
  • Runtime exceptions - Wrap risky operations in try/catch blocks

Error Prevention

// Check for required parameters
if (!shipmentData || !shipmentData.tracking_number) {
throw new Error('Missing required shipment data');
}

// Validate data types
if (typeof orderValue !== 'number' || orderValue < 0) {
throw new Error('Order value must be a positive number');
}

// Safe property access
const status = shipmentData.status || 'UNKNOWN';
const items = shipmentData.items || [];

Security Considerations

  • No sensitive data - Avoid hardcoding credentials or secrets
  • Input validation - Always validate and sanitize input data
  • Limited scope - Code runs in a sandboxed environment
  • No file system access - Cannot read/write files directly
  • Network restrictions - External API calls may have limitations

The Code node provides powerful customization capabilities while maintaining security and performance within your Splice workflows.