N8n Code Javascript

Write and execute JavaScript code nodes within n8n automation and integration workflows

n8n Code JavaScript is an AI skill that provides guidance for writing custom JavaScript code nodes within n8n workflow automation platform. It covers the n8n code node API, data transformation patterns, external API integration, error handling within workflows, and performance optimization that enable complex automation logic beyond n8n's built-in nodes.

What Is This?

Overview

n8n Code JavaScript delivers patterns and practices for implementing custom logic in n8n workflow code nodes. It addresses data transformation using the n8n item structure with $input, $json, and $binary accessors, HTTP requests to external APIs using the built-in $http helper, workflow context access including environment variables and previous node outputs, error handling that integrates with n8n's retry and error workflow mechanisms, binary data processing for files, images, and documents within workflows, and performance patterns for handling large datasets without exceeding memory limits.

Who Should Use This

This skill serves automation engineers building complex n8n workflows that need custom logic, developers integrating external services that lack dedicated n8n nodes, business analysts who need data transformation beyond what built-in nodes provide, and teams building internal tools and automations on the n8n platform.

Why Use It?

Problems It Solves

n8n's visual node builder handles many common automation scenarios, but complex data transformations, conditional logic, and custom API integrations require code nodes. Without guidance on n8n's specific JavaScript API, developers write code that fails to properly handle n8n's item-based data model, loses binary data between nodes, or creates workflows that timeout on large datasets.

Core Highlights

The skill uses n8n's native helpers for HTTP requests, ensuring proper authentication and error handling integration. Data transformation patterns preserve n8n's item structure for seamless flow to downstream nodes. Binary data handling works with n8n's storage model for file processing workflows. Error patterns leverage n8n's built-in retry and error workflow routing.

How to Use It?

Basic Usage

// n8n Code Node: Transform and enrich input data
const items = $input.all();
const results = [];

for (const item of items) {
  const data = item.json;

  // Transform data structure
  const enriched = {
    fullName: `${data.firstName} ${data.lastName}`,
    email: data.email.toLowerCase().trim(),
    domain: data.email.split('@')[1],
    isBusinessEmail: !['gmail.com', 'yahoo.com', 'hotmail.com']
      .includes(data.email.split('@')[1]),
    processedAt: new Date().toISOString()
  };

  results.push({ json: enriched });
}

return results;

Real-World Examples

// n8n Code Node: Batch API calls with rate limiting
const items = $input.all();
const batchSize = 10;
const delayMs = 1000;
const results = [];

for (let i = 0; i < items.length; i += batchSize) {
  const batch = items.slice(i, i + batchSize);
  const promises = batch.map(async (item) => {
    const response = await $http.request({
      method: 'GET',
      url: `https://api.example.com/users/${item.json.userId}`,
      headers: { 'Authorization': `Bearer ${$env.API_TOKEN}` }
    });
    return {
      json: {
        ...item.json,
        userData: response,
        enrichedAt: new Date().toISOString()
      }
    };
  });

  const batchResults = await Promise.all(promises);
  results.push(...batchResults);

  if (i + batchSize < items.length) {
    await new Promise(resolve => setTimeout(resolve, delayMs));
  }
}

return results;

Advanced Tips

Use $execution.id to create unique identifiers for tracking items through complex workflows. Access data from any previous node using $node["NodeName"].json for cross-node data references. Store intermediate results in workflow static data using $getWorkflowStaticData() for workflows that need to maintain state across executions.

When to Use It?

Use Cases

Use n8n Code JavaScript when built-in n8n nodes cannot perform the required data transformation, when integrating with APIs that lack dedicated n8n community nodes, when implementing complex conditional routing logic that exceeds the IF node's capabilities, or when processing and transforming binary file data within automation workflows.

Related Topics

n8n workflow design patterns, webhook automation, API integration strategies, data pipeline architecture, and low-code automation platforms all complement n8n JavaScript coding.

Important Notes

Requirements

An n8n instance (self-hosted or cloud) with code node support enabled. JavaScript knowledge including async/await for API calls. Understanding of n8n's item-based data model where each node processes arrays of items.

Usage Recommendations

Do: always return data in n8n's expected format as an array of objects with json and optionally binary keys. Use $http.request() instead of raw fetch for HTTP calls, as it integrates with n8n's credential system. Test code nodes with small datasets before running on full production data.

Don't: use external npm packages in code nodes unless your n8n instance is configured to allow them. Process items one at a time when batch processing would be more efficient. Ignore error handling, as unhandled errors in code nodes cause the entire workflow execution to fail.

Limitations

Code nodes run in a sandboxed environment with limited access to Node.js built-in modules. External npm packages are not available by default and require instance-level configuration. Long-running code nodes may trigger execution timeouts depending on the n8n instance configuration. Memory-intensive operations on large datasets can cause workflow failures on resource-constrained instances.