n8n Code Node: Write JavaScript, Python, and Custom Functions (2026)
Tutorial

n8n Code Node: Write JavaScript, Python, and Custom Functions (2026)

6 min read

The n8n Code Node is the fastest way to transform data, parse complex payloads, and inject custom logic when built-in nodes fall short. Instead of chaining ten helper nodes, you can write a short script that does exactly what you need.

n8n is an open-source workflow automation tool that connects APIs, databases, and services into visual pipelines.

If you are looking for a faster way to build and validate n8n workflows, Synta is an MCP server for n8n that gives your AI assistant operational access to inspect, edit, test, and fix nodes directly inside your instance.

What is the n8n Code Node?

The Code Node is a built-in n8n node that runs custom scripts against the data passing through your workflow. It supports JavaScript by default and Python when configured. You can map fields, filter arrays, call external libraries, and format outputs in ways that standard nodes cannot.

Think of it as a function block inside your pipeline. Data goes in, your script runs, and an array of objects comes out.

How do I add a Code Node to my workflow?

Open your workflow canvas and search for "Code" in the node panel. Drag the Code Node into your pipeline and connect it to the previous node. Double-click the node to open the editor.

Choose your runtime mode in the node settings:
- Run Once for All Items — receives the full `items` array. Best for aggregations, sorting, and batch operations.
- Run Once for Each Item — receives one item at a time. Best for per-row transforms and simple mappings.

How do I write JavaScript in the n8n Code Node?

Code Node editor overview

JavaScript is the default language. You do not need extra setup.

A basic mapping looks like this. Assume the previous node returns a list of users and you want to extract only names and emails.

Return an array where each object becomes the new `json` payload for the next node.

const results = items.map(item => {
return {
json: {
name: item.json.name,
email: item.json.email.toLowerCase(),
created: new Date(item.json.created_at).toISOString()
}
};
});
return results;

Key points:
- `items` is always available and contains the full input array.
- Each element has a `json` property with the actual data.
- You must return an array. Returning a single object will break the workflow.
- Use standard JavaScript methods like `map`, `filter`, `reduce`, and `sort`.

How do I use Python in the n8n Code Node?

Python mode is available but requires the `python` executable and `pandas` to be installed in your n8n environment. Self-hosted users can install dependencies via Docker or the host OS. Cloud users may have limited support.

Switch the node language to Python and write your script against the same `items` structure.

results = []
for item in items:
results.append({
"json": {
"name": item["json"]["name"],
"email": item["json"]["email"].lower()
}
})
return results

If Python is not available in your environment, the node will return an execution error. In that case, stick with JavaScript or move the logic to an external microservice.

What variables and methods are available?

The Code Node exposes several helpers:

- `$json` — the `json` payload of the first item (shortcut for `items[0].json`).
- `$input` — metadata about the incoming connection.
- `items` — the full array of input items.
- `$node["Node Name"].json` — access output from a specific upstream node.
- `$env` — environment variables configured in your n8n instance.

You can also import some built-in modules in JavaScript mode, such as `moment` for date handling, depending on your n8n version. Check the n8n docs for the exact module list in your release.

How do I handle errors in the Code Node?

Errors in the Code Node stop the workflow unless you catch them.

Wrap risky logic in a try-catch block and return a fallback object so downstream nodes still receive data.

const safe = items.map(item => {
try {
const parsed = JSON.parse(item.json.raw);
return { json: { success: true, data: parsed } };
} catch (err) {
return { json: { success: false, error: err.message, raw: item.json.raw } };
}
});
return safe;

You can also enable Continue On Fail in the node settings. This passes the error object to the next node instead of halting execution. Use it for non-critical transforms where partial data is acceptable.

Common Code Node patterns and examples

Common Code Node patterns

Here are four patterns that come up in real workflows.

Filter by date range
Return only items where a timestamp is within the last seven days.

Deduplicate by key
Remove duplicate records based on an ID field using a Set.

Merge nested arrays
Flatten a nested structure into a flat list for database insertion.

Format for a specific API
Rename keys and cast types to match what a downstream API expects.

These patterns replace multiple Set, IF, and Merge nodes with a single script that is easier to read and faster to execute.

When should I use the Code Node vs a Function Node?

The Function Node is an older n8n node that also runs JavaScript. The Code Node replaces it and offers better error messages, support for both JavaScript and Python, and a cleaner editor.

Use the Code Node for all new workflows. Only use the Function Node if you are maintaining legacy workflows that you do not want to refactor.

FAQ

Can I install npm packages in the Code Node?
No. The Code Node runs in a sandboxed environment with a fixed set of built-in modules. If you need external packages, use the HTTP Request Node to call an external service or run a custom Docker container.

Why does my Code Node return "Cannot read property of undefined"?
This usually means an upstream item is missing the field you are accessing. Add defensive checks like `item.json?.name || "fallback"` or validate the schema before mapping.

Is Python slower than JavaScript in n8n?
Python can be slower because it spawns a separate process. For high-volume workflows, prefer JavaScript unless you need a library that only exists in Python.

How do I debug a Code Node?
Use `console.log()` inside the script and check the execution log. You can also pin data in the previous node to freeze the input while you iterate on your script.

Can Synta help me write Code Node scripts?
Yes. Synta is an MCP server for n8n. It gives your AI assistant operational access to inspect node inputs, suggest transforms, and validate the output directly inside your n8n instance.