Lesson 12medium15 min

Generating New Nodes & Custom Code

Write custom JavaScript and Python logic inside n8n Code nodes for data transformation and API wrapping.

Learning Objectives

  • Write JavaScript code inside Code nodes using modern ES6+
  • Handle multi-item arrays with map, filter, and reduce
  • Wrap external APIs using custom HTTP Request nodes

Generating New Nodes & Custom Code

While n8n has hundreds of built-in nodes, production AI workflows often require custom data parsing, JSON schema restructuring, or regex cleaning.

The Code Node: JavaScript Mode

Inside the Code node, you can execute standard JavaScript. The execution environment provides two modes:

1. Run Once for Each Item

The code executes once per incoming item. Use $input.item.json:

// Clean text and extract domain
const rawEmail = $input.item.json.email || '';
const domain = rawEmail.split('@')[1]?.toLowerCase() || 'unknown';

return {
  email: rawEmail.trim().toLowerCase(),
  domain: domain,
  isCorporate: !['gmail.com', 'yahoo.com', 'hotmail.com'].includes(domain)
};

2. Run Once for All Items

The code executes once with the full array. Use $input.all():

const items = $input.all();

// Filter high priority items and sort by date
const prioritized = items
  .filter(item => item.json.priority === 'urgent')
  .sort((a, b) => new Date(b.json.date) - new Date(a.json.date));

return prioritized;