Reference for the n8n Code node -- JavaScript and Python execution, available APIs, built-in libraries, and patterns.
The Code node executes custom JavaScript or Python code inside a workflow. Use it for data transformation, complex logic, API calls, and anything that built-in nodes cannot handle directly.
| Mode | Runtime | Notes |
|---|---|---|
| JavaScript | Node.js (V8) | Default mode. Full access to n8n helper APIs. |
| Python | Python 3 (via Pyodide) | Available in n8n 1.0+. Some limitations on external libraries. |
| Mode | Behavior |
|---|---|
| Run Once for All Items | The code receives all input items at once as an array. Use this when you need to aggregate, sort, or compare across items. |
| Run Once for Each Item | The code runs separately for every input item. Use this for simple per-item transformations. |
Warning: Run mode affects which APIs are available
In Run Once for All Items mode, use
$input.all()to get all items. In Run Once for Each Item mode, use$input.itemto get the current item. Mixing these up is the most common source of Code node errors.
| API | Description |
|---|---|
$input.all() |
Returns all input items as an array. Each item has .json and optional .binary properties. Available in "All Items" mode. |
$input.item |
Returns the current input item. Available in "Each Item" mode. |
$input.first() |
Returns the first input item. |
$input.last() |
Returns the last input item. |
$json |
Shorthand for $input.item.json in "Each Item" mode. Gives direct access to the current item's data. |
$('Node Name').all() |
Access output items from any upstream node by name. |
$('Node Name').first() |
Access the first output item from a named upstream node. |
$execution.id |
The current execution ID. |
$workflow.id |
The current workflow ID. |
$workflow.name |
The current workflow name. |
$env |
Access environment variables defined on the n8n instance (e.g., $env.API_KEY). |
$now |
Current timestamp as a Luxon DateTime object. |
$today |
Today's date at midnight as a Luxon DateTime object. |
this.helpers.httpRequest() |
Make HTTP requests from within the Code node. Supports the same options as the HTTP Request node. |
These libraries are available without any require() or import statements:
| Library | Access | Use Case |
|---|---|---|
| Luxon | const { DateTime } = require('luxon') |
Date and time parsing, formatting, math, and timezone conversion. |
| JMESPath | const jmespath = require('jmespath') |
Query and extract data from complex JSON structures. |
| Lodash | const _ = require('lodash') |
Utility functions for arrays, objects, and strings. Available in most n8n versions. |
Note
External npm modules are not available by default. Self-hosted users can allow specific modules via the
NODE_FUNCTION_ALLOW_EXTERNALenvironment variable (e.g.,NODE_FUNCTION_ALLOW_EXTERNAL=axios,moment). n8n Cloud does not support external modules.
The Code node must return an array of items. Each item is an object with a json property:
// Run Once for All Items
const items = $input.all();
const results = [];
for (const item of items) {
results.push({
json: {
name: item.json.name.toUpperCase(),
processed: true,
},
});
}
return results;
// Run Once for Each Item
return {
json: {
name: $json.name.toUpperCase(),
processed: true,
},
};
Warning: Always return
{ json: {...} }If you return plain objects without the
jsonwrapper, downstream nodes will receive empty items. This is the second most common Code node mistake.
Transform and reshape data (All Items):
const items = $input.all();
return items.map(item => ({
json: {
fullName: `${item.json.firstName} ${item.json.lastName}`,
email: item.json.email.toLowerCase(),
createdAt: DateTime.fromISO(item.json.date).toFormat('yyyy-MM-dd'),
},
}));
Filter items by a condition:
const items = $input.all();
return items.filter(item => item.json.status === 'active');
Aggregate data across items:
const items = $input.all();
const total = items.reduce((sum, item) => sum + item.json.amount, 0);
return [{ json: { total, count: items.length, average: total / items.length } }];
Make an HTTP request inside the Code node:
const response = await this.helpers.httpRequest({
method: 'GET',
url: 'https://api.example.com/data',
headers: { Authorization: 'Bearer ' + $env.API_TOKEN },
});
return [{ json: response }];
Access data from a previous node by name:
const webhookData = $('Webhook').first().json;
const dbRows = $('PostgreSQL').all();
return dbRows.map(row => ({
json: {
...row.json,
triggeredBy: webhookData.headers.host,
},
}));
Warning: Async/await is required for HTTP calls
When using
this.helpers.httpRequest()or any promise-based API, you must useawait. Without it, the node returns a Promise object instead of the actual data.
$input.all() vs $input.item. In "All Items" mode, $input.item is undefined. In "Each Item" mode, $input.all() works but is inefficient because it fetches all items on every iteration.[], downstream nodes will not execute. Return at least one item or use a conditional branch.console.log() output. Logs appear in the n8n server console (Docker logs, terminal output). They do not appear in the editor UI. Use them for debugging on self-hosted instances.try/catch. Unhandled exceptions stop the workflow. Use this.continueOnFail() to check if the node is configured to continue on failure.this.helpers or the same helper functions. Use the _input and _execution objects instead. External Python packages are limited to what Pyodide bundles.TypeError: Cannot read properties of undefined (reading 'json')
You are using $input.item in "Run Once for All Items" mode, where it is undefined. Switch to $input.all() to get the array of items, or change the run mode to "Run Once for Each Item."
Error: The output of the code node must be an array of objects with a "json" property.
Your code is returning plain objects instead of wrapping them in { json: {...} }. Every returned item must have a json key. For example, return [{ json: { name: "Alice" } }] instead of [{ name: "Alice" }].
ReferenceError: require is not defined (when trying to load external modules)
External npm modules are not available by default. On self-hosted instances, allow specific modules via the NODE_FUNCTION_ALLOW_EXTERNAL environment variable (e.g., NODE_FUNCTION_ALLOW_EXTERNAL=axios,moment). On n8n Cloud, external modules are not supported -- use the built-in libraries (Luxon, Lodash, JMESPath) or this.helpers.httpRequest() instead.
I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.