n8n Code Node and Expressions: When to Write JavaScript

When to use expressions or the n8n Code node: JavaScript patterns, item handling, task runner isolation, secrets and the mistakes that bite in production.

Executive Summary: Most n8n workflows need less code than engineers expect, and more discipline than low-code fans admit. I use a simple ladder: an expression first, a built-in transform node second, the n8n Code node third and a real service last. This article explains each rung, how expressions and the Code node handle items, what changed with task runners in n8n 2.0, and the safety rules that keep code in workflows maintainable and secure.

Give an engineer a canvas and a Code node, and within a week half the workflow is JavaScript. Give the same canvas to an operations analyst, and they will chain twelve nodes to avoid writing three lines. Neither outcome is good.

The useful question is not “code or no code”. It is “where does this piece of logic belong so that the next person can understand and change it?” This article gives a practical answer for n8n, aimed at teams who are comfortable with JavaScript and want to use it well inside workflows.

The Ladder: Expression, Node, Code, Service

When I review workflows, I check each piece of logic against four rungs, from lightest to heaviest. Each rung up adds power and maintenance cost.

Rung Use it for Avoid it when
Expression Reading a field, formatting a value, a simple condition It no longer fits on one readable line
Built-in node (Edit Fields, Filter, Sort, Aggregate, Split Out) Common transformations that others will recognise You need many chained nodes to express one idea
n8n Code node Non-trivial logic over items, validation, reshaping complex data The logic is shared by many workflows or needs heavy testing
Service you own Core business rules, shared logic, anything that needs unit tests The logic is truly one-off glue

In other words, the ladder is not about avoiding code. It is about making logic visible at the right level. An Edit Fields node that renames five fields is easier to review than ten lines of JavaScript doing the same thing. Conversely, a 40-node chain that implements a pricing rule is harder to review than a short, well-named function.

Expressions: The First Rung

Expressions are JavaScript snippets wrapped in double curly braces, and they work in almost any node field. They resolve once per item, using that item’s data.

  • {{ $json.email }} reads a field from the current item.
  • {{ $('Webhook').item.json.body.orderId }} reads the matching item from an earlier node.
  • {{ $json.total.toFixed(2) }} calls a normal JavaScript method.
  • {{ $now.toISO() }} uses the built-in Luxon date helpers.

As a result, expressions are perfect for small, local transformations. However, they hide logic inside node fields, where nobody sees it during a quick review. My rule of thumb: if an expression needs a ternary inside a ternary, or a comment to explain it, move it to a Code node or an Edit Fields node with a clear name.

The n8n Code Node: Modes and Item Shapes

The n8n Code node runs JavaScript or Python against the items flowing through a workflow. It has two modes, and choosing the right one prevents most bugs.

  • Run Once for All Items gives you every item through $input.all(). You return an array of items. Use it for aggregation, sorting, deduplication or fanning one item out into many.
  • Run Once for Each Item runs your code separately for every item, exposed as $input.item. You return one item. Use it for per-record validation and reshaping.

In both modes, items must keep n8n’s shape: objects with a json property. Return plain objects, and n8n will usually wrap them, but being explicit avoids confusion. Here is a per-item validator that I tested on a local instance. It normalises an email, rejects bad records clearly and keeps the original fields:

// n8n Code node, mode: Run Once for Each Item
const data = $input.item.json;
const email = String(data.email ?? '').trim().toLowerCase();

if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
  throw new Error(`Invalid email for record ${data.id ?? 'unknown'}`);
}

return {
  json: {
    ...data,
    email,
    domain: email.split('@')[1],
    checkedAt: new Date().toISOString(),
  },
};

Throwing an error here is deliberate. Combined with the node’s On Error setting, a thrown error can stop the workflow or send the bad item down an error output, where you can log it and alert someone. Silently returning a half-valid item is worse than failing loudly.

Keep item linking intact

n8n tracks which input item produced each output item. Later nodes rely on this when an expression references an earlier node with .item. In “Run Once for Each Item” mode, n8n keeps the link for you. In “Run Once for All Items” mode, if you build brand new items, add a pairedItem reference to the source index, or later expressions may fail with item-linking errors.

One Rule, Three Ways

To see the ladder in practice, take one small rule: build a display name from first and last name, falling back to the email when names are missing.

As an expression in an Edit Fields node, it looks like this:

{{ [$json.firstName, $json.lastName].filter(Boolean).join(' ') || $json.email }}

That is still readable, so an expression is the right rung. Now add two more requirements: trim whitespace and title-case the result. The expression quickly becomes a puzzle. At that point, a short n8n Code node in “Run Once for Each Item” mode is clearer:

const { firstName = '', lastName = '', email = '' } = $input.item.json;
const titleCase = (s) => s.trim().toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());

const name = [firstName, lastName].map(titleCase).filter(Boolean).join(' ');

return { json: { ...$input.item.json, displayName: name || email } };

Finally, imagine that marketing, billing and support all need the same display-name rule, with locale handling. Now it belongs in a shared service or, at minimum, a single sub-workflow that every workflow calls. Same rule, three rungs, chosen by how far the logic travels.

This also explains why code reviews of workflows should look at expressions, not only Code nodes. Logic hidden in a field is still logic. If you want to understand why expressions resolve per item, the n8n execution model article walks through it step by step.

Task Runners Changed the Rules in 2.0

n8n 2.0, released in December 2025, made task runners the default for every Code node execution. Your code now runs in a separate, sandboxed process rather than inside the main n8n process. This matters for security and stability, and it changes a few behaviours.

  • Environment variables are blocked by default. $env access from the Code node is off unless an administrator allows it. Store secrets in credentials instead.
  • $evaluateExpression() no longer works in the Code node under the default secure mode. Evaluate expressions in an Edit Fields node first, then read the result.
  • Python runs natively. The old browser-based Pyodide engine is gone. Python Code nodes need task runners in external mode, and the native version does not support the old _input style helpers.
  • Modules are opt-in. On self-hosted instances, built-in modules such as crypto and external npm packages must be allowed explicitly through configuration.

The n8n 2.0 breaking changes guide lists each change with its migration path, and the Code node documentation covers the supported variables per language. If you upgraded an older instance, search your workflows for $env and $evaluateExpression first. Those are the two most common breakages.

Safety Rules for Code in Workflows

Code inside workflows is still production code, even though it lives somewhere less familiar. These rules keep it safe.

  1. No secrets in code. Use credentials and nodes that consume them. A key in a Code node ends up in every export and screenshot.
  2. No unbounded loops or calls. A Code node that loops over thousands of items and calls an API in each iteration bypasses n8n’s batching and retry controls. Use the HTTP Request node for calls, as I explain in the HTTP Request node guide.
  3. Fail loudly. Throw clear errors with record identifiers, rather than returning partial data.
  4. Keep it short. If a Code node grows past a screen or two, it probably wants to be a sub-workflow or a service.
  5. Name the node for its purpose. “Validate signup” tells a reviewer far more than “Code3”.

Testing Code Without Leaving n8n

Admittedly, you cannot unit test a Code node the way you test a module. Still, you can get close.

Pin realistic data on the node before it, including awkward cases such as missing fields, empty strings and unexpected types. Then run the Code node repeatedly while you edit. Add console.log() calls during development; in manual runs, the output appears in the browser console. Remove noisy logs before publishing.

For logic that truly needs tests, however, move it out. A small HTTP service with unit tests, called by an HTTP Request node, is often cleaner than a long Code node. The workflow then handles orchestration, and the service owns the rules. This is the same split I recommend in What is n8n?: orchestration in n8n, core logic in code you own.

Signs You Have Too Much Code

A few warning signs show up in workflow reviews again and again:

  • The workflow is a trigger, one giant Code node and an output node.
  • The same snippet appears in several workflows with small differences.
  • Code nodes make HTTP calls or database queries directly.
  • Nobody except the original author dares to edit the workflow.

Together, these signs mean n8n has become a place to run scripts rather than an orchestrator. The fix is usually to split the logic into nodes that express the flow, plus a service or sub-workflow for the reusable part.

Signs You Have Too Little Code

The opposite problem is just as real, and it tends to come from teams that treat code as a failure.

  • Ten Edit Fields and IF nodes implement one validation rule.
  • Expressions span several lines, with nested ternaries and string concatenation.
  • Workarounds such as looping with counters replace a simple map or filter.

In these cases, therefore, a short n8n Code node with a clear name is easier to read, test and change. Low-code is a means, not a goal.

Frequently Asked Questions

Can I use npm packages in the n8n Code node?

On self-hosted instances, yes, if an administrator allows them through configuration and the packages are installed where the task runner can load them. n8n Cloud does not support arbitrary external packages.

Should I use Python or JavaScript in the Code node?

Use JavaScript by default, since it runs everywhere and has the richest helper support. Use Python when you already have Python logic or libraries, and your instance runs task runners in external mode.

Why does $env return nothing in my Code node?

Since n8n 2.0, environment variable access from the Code node is blocked by default. Use credentials for secrets, or ask an administrator to change the setting if you have a valid reason.

Code Where It Helps, Nodes Where They Explain

The best n8n workflows read like a diagram of the business process, with small, named Code nodes where logic is genuinely easier to express in JavaScript. Climb the ladder one rung at a time, respect the task runner sandbox and move anything shared or critical into a service. That balance keeps workflows fast to build and safe to change.

Last updated on 29 November 2026

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *