Skip to main content
Code

Overview

The Code node lets you write custom JavaScript to transform data, perform calculations, implement complex logic, or handle tasks that other nodes can’t.
Best for: Data transformations, calculations, custom business logic, data formatting, and complex data manipulation.
Need Python? For Python code execution with pandas and data analysis libraries, use an Agent node with the Data Analysis capability enabled. The Agent can write and execute Python code in a Jupyter environment.

When to Use Code Node

Perfect for:
  • Data transformations and formatting
  • Mathematical calculations
  • Custom business logic
  • JSON parsing and manipulation
  • Data validation and cleaning
  • Date/time operations
Not ideal for:
  • AI analysis (use Agent node)
  • API calls (use HTTP Request node)
  • Simple conditions (use Condition node)
  • Complex data analysis with pandas (use Agent with Data Analyst)

Configuration

Code Editor: Write your transformation logic in JavaScript Access Previous Nodes: All previous node outputs are available as variables

JavaScript Examples

Calculate Statistics

// Access data from previous nodes
const scores = agent.output.structured.scores || [];

// Calculate statistics
const average = scores.reduce((a, b) => a + b, 0) / scores.length;
const max = Math.max(...scores);
const min = Math.min(...scores);

// Return result
return {
  average_score: average.toFixed(2),
  highest_score: max,
  lowest_score: min,
  grade: average >= 90 ? "A" : average >= 80 ? "B" : "C"
};

Validate and Clean Data

// Access form data
const email = trigger.output.email || "";
const amount = trigger.output.amount || 0;

// Validate
if (!email.includes("@")) {
  throw new Error("Invalid email format");
}

if (amount <= 0) {
  throw new Error("Amount must be greater than zero");
}

// Clean and return
return {
  email: email.trim().toLowerCase(),
  amount: parseFloat(amount.toFixed(2)),
  validated: true
};

Transform and Filter Arrays

// Access data from previous node
const customers = trigger.output.customers || [];

// Filter active customers
const activeCustomers = customers.filter(c => c.status === "active");

// Transform data
const processed = activeCustomers.map(customer => ({
  id: customer.id,
  name: `${customer.firstName} ${customer.lastName}`.trim(),
  email: customer.email.toLowerCase(),
  tier: customer.totalSpent > 1000 ? "premium" : "standard"
}));

return {
  customers: processed,
  total: processed.length,
  premiumCount: processed.filter(c => c.tier === "premium").length
};

Date Operations

// Access event data
const events = trigger.output.events || [];
const now = new Date();

const processedEvents = events.map(event => {
  const eventDate = new Date(event.date);
  const daysUntil = Math.ceil((eventDate - now) / (1000 * 60 * 60 * 24));

  return {
    title: event.title,
    date: eventDate.toISOString(),
    formatted: eventDate.toLocaleDateString("en-US", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric"
    }),
    daysUntil: daysUntil,
    isUpcoming: daysUntil >= 0,
    isThisWeek: daysUntil >= 0 && daysUntil <= 7
  };
});

return {
  events: processedEvents,
  upcomingCount: processedEvents.filter(e => e.isUpcoming).length,
  thisWeekCount: processedEvents.filter(e => e.isThisWeek).length
};

JSON Processing

// Nested JSON from API response
const apiResponse = http_request.output || {};

// Extract and flatten nested data
const users = apiResponse.data?.users || [];

const flattened = users.map(user => ({
  id: user.id,
  name: `${user.first_name || ""} ${user.last_name || ""}`.trim(),
  email: user.contact?.email || "",
  city: user.address?.city || "Unknown",
  isActive: user.status === "active"
}));

return {
  users: flattened,
  total: flattened.length,
  activeCount: flattened.filter(u => u.isActive).length
};

Aggregate and Summarize

// Sales data from previous node
const sales = http_request.output.sales || [];

// Group by category
const byCategory = {};
sales.forEach(sale => {
  const cat = sale.category || "Other";
  if (!byCategory[cat]) {
    byCategory[cat] = { total: 0, count: 0, items: [] };
  }
  byCategory[cat].total += sale.amount || 0;
  byCategory[cat].count += 1;
  byCategory[cat].items.push(sale);
});

// Calculate summary
const summary = Object.entries(byCategory).map(([category, data]) => ({
  category,
  totalRevenue: data.total.toFixed(2),
  orderCount: data.count,
  averageOrder: (data.total / data.count).toFixed(2)
}));

// Sort by revenue
summary.sort((a, b) => parseFloat(b.totalRevenue) - parseFloat(a.totalRevenue));

return {
  summary: summary,
  topCategory: summary[0]?.category || "None",
  grandTotal: sales.reduce((sum, s) => sum + (s.amount || 0), 0).toFixed(2)
};

Accessing Code Output

Use the code node name to access returned values in subsequent nodes:
{{code_node_name.output.customer}}
{{code_node_name.output.total}}
{{code_node_name.output.formatted_date}}
{{code_node_name.output.processed_items[0].name}}

Available Functions

The Code node runs in a secure sandbox environment, giving you access to built-in utility functions:
  • ld.request() - Make HTTP requests
  • ld.log() - Output debugging information
  • Data conversions - CSV, Parquet, Arrow format conversions
  • Standard JavaScript - JSON, Date, Math, Array, Object methods

Complete Utilities Reference

View all available sandbox utilities including data conversions, SQL validation, cryptography, and more.

Best Practices

Return data as objects for easy access in later nodes. This makes it simple to reference specific values in subsequent nodes using dot notation.
Use || or optional chaining (?.) to provide default values and prevent errors when data is undefined or null.
Wrap risky operations in try-catch blocks to prevent workflow failures. This allows you to handle errors gracefully and provide meaningful error messages.
Complex logic might be better in an Agent node. Use code nodes for straightforward transformations and calculations, not for tasks requiring intelligence or context understanding.
Document what your code does for future reference. Clear comments help you and your team understand the logic when revisiting the workflow later.

Next Steps