Generated banner for N8n Code Javascript
Generated logo for N8n Code Javascript

N8n Code Javascript

Romuald CzlonkowskiCommunityCreated by Romuald Czlonkowski

  • Skill
  • Tool integration
  • Automation and integrations
  • MIT
  • No issues found

From the author

Write, review, or debug JavaScript in an n8n Code node. Use when a Code node is already in the workflow (editing it, fixing an error, choosing its mode, making it faster), or when a new one is justified: no native node fits (check the job-to-node table in using-n8n-mcp-skills first) and the job is on the closed list — loops or recursion no node expresses, state across runs, parsing no node handles, an allowlisted library, heavy all-items work, or one short node replacing 4+ glue nodes. Covers $input/$json/$node in code, this.helpers, Luxon, SplitInBatches loops, cross-iteration data, pairedItem, per-item performance, and the "Why Code:" note. Filtering, totals, dedupe, sorting, joins, file formats and API paging have native nodes (Filter, Summarize, Remove Duplicates, Sort, Merge, Extract From File, HTTP Request): see n8n-node-configuration. EXCEPTION — for the AI-agent-callable Custom Code Tool (@n8n/n8n-nodes-langchain.toolCode), use n8n-code-tool; it has a different runtime contract.
— the description by Romuald Czlonkowski

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to using the n8n Code node. It emphasizes a 'native-first' philosophy, requiring users to verify if a built-in node or expression can handle the task before resorting to custom JavaScript. It covers essential execution modes, data access patterns, return formats, and sandbox limitations, ensuring that custom code is performant, maintainable, and correctly integrated into n8n workflows.

What it does

  • Guides users through the decision gate to determine if a Code node is necessary.
  • Explains the difference between 'Run Once for All Items' and 'Run Once for Each Item' modes.
  • Provides canonical patterns for data access and returning processed items.
  • Details sandbox restrictions, including built-in functions and library allowlisting.
  • Offers best practices for error prevention, null checking, and performance optimization.
  • Standardizes the use of 'Why Code:' notes for better workflow documentation.

When to use it

  • When no native n8n node exists for a specific data transformation or logic task.
  • For complex operations like recursion, state management across runs, or parsing custom formats.
  • When a single short Code node can replace a long, inefficient chain of multiple glue nodes.
  • When handling heavy all-items processing that requires optimized performance.
  • When working with allowlisted external libraries not covered by native nodes.

Advantages

  • Reduces workflow complexity by replacing long chains of nodes with concise logic.
  • Improves performance by choosing the correct execution mode for the dataset size.
  • Ensures code maintainability through standardized documentation and return formats.
  • Prevents common runtime errors related to webhook structures and sandbox limitations.
  • Promotes the use of native nodes for standard tasks, keeping workflows cleaner.

Usage examples

“How do I calculate a running total for my items in n8n?”
The agent will recommend using a Code node in 'Run Once for All Items' mode, providing a JavaScript snippet that iterates through the items and maintains a running balance variable.
“I have a Code node that is failing with a 'Code doesn't return items properly' error. How do I fix it?”
The agent will guide you to wrap your output in the canonical [{json: {...}}] format and ensure your code does not return a primitive value or null.
“Should I use a Code node to filter my data?”
The agent will advise against it, suggesting the native Filter node instead, and explain how to check the job-to-node table to confirm if a native alternative exists.
“How do I access webhook data inside a Code node?”
The agent will clarify that webhook data is nested under $json.body and provide the correct syntax to access fields like $input.first().json.body.fieldName.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/czlonkowski/n8n-code-javascript/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip n8n-code-javascript.zip -d .agents/skills

Documentation by Romuald Czlonkowski

JavaScript Code Node

Expert guidance for writing JavaScript code in n8n Code nodes.


Before you write a Code node

A new Code node has to pass this gate first:

  1. Is there a native node for the job? Check the job-to-node table in using-n8n-mcp-skills: Filter, IF / Switch, Summarize, Aggregate, Split Out, Merge, Compare Datasets, Remove Duplicates, Sort + Limit, Date & Time, XML / HTML / Extract From File / Convert To File, HTTP Request (pagination, batching) and Crypto cover most reaches for Code. Their configs are in n8n-node-configuration → NATIVE_NODES.md.

  2. Would a short expression in that node do? One expression, no function body — the helper methods (.pluck(), .sum(), .unique(), $ifEmpty(), .diffTo()) are in n8n-expression-syntax and, on n8n-mcp 2.97.0+, in tools_documentation({topic: "expression_helpers"}). Several statements inside {{ }} count as code, so they belong here rather than in an Edit Fields field.

  3. Is the job on the closed list? Loops or recursion no node expresses, state across runs ($getWorkflowStaticData), parsing no node handles, an allowlisted library, heavy all-items work (thousands of items, stated or measured), or one short Code node (~15 lines) replacing 4+ glue nodes that only reshape data.

If it passes, write the Code node and give it a note, so the next reader (and the review hooks) can see why:

{ "name": "Flatten category tree", "type": "n8n-nodes-base.code", "notes": "Why Code: Split Out considered — the tree has arbitrary depth (recursion)", "notesInFlow": true }

Editing or debugging a Code node that is already there doesn't need the gate, but if the node does a native-node job, say so and offer the native replacement.


Quick Start

// Basic template for Code nodes
const items = $input.all();

// Process data
const processed = items.map(item => ({
  json: {
    ...item.json,
    processed: true,
    timestamp: new Date().toISOString()
  }
}));

return processed;
Essential Rules
  1. Choose "Run Once for All Items" mode (recommended for most use cases)

  2. Access data: $input.all(), $input.first(), or $input.item

  3. Return [{json: {...}}] — the canonical, mode-portable form. In Run Once for All Items mode n8n also auto-wraps a bare return {…} object, so that runs too; what genuinely fails is returning a primitive (string/number) or null.

  4. CRITICAL: Webhook data is under $json.body (not $json directly)

  5. Built-ins available: this.helpers.httpRequest() (no auth — the bare $helpers global is undefined in the task-runner sandbox, so $helpers.httpRequest() throws ReferenceError: $helpers is not defined), DateTime (Luxon), $jmespath(). Not available: this.helpers.httpRequestWithAuthentication (deny-listed), $env (when N8N_BLOCK_ENV_ACCESS_IN_NODE=true), require() (unless allowlisted). For anything beyond a trivial unauthenticated GET (auth, pagination, retries), prefer the HTTP Request node and keep Code nodes for pure logic.

  6. Instance-allowlisted libraries: Self-hosted instances can allowlist modules via N8N_RUNNERS_ALLOWED_BUILT_IN_MODULES and N8N_RUNNERS_ALLOWED_EXTERNAL_MODULES (legacy: NODE_FUNCTION_ALLOW_BUILTIN / NODE_FUNCTION_ALLOW_EXTERNAL). If the user says their instance allows specific modules (e.g. axios, lodash, crypto), use them via require() — don't refuse. If unsure, ask or default to built-ins only.

  7. Wrong skill? If you're writing code for a Custom Code Tool attached to an AI Agent (@n8n/n8n-nodes-langchain.toolCode), stop — that node has a different contract (input via query, must return a string, no $input/$helpers). Use the n8n-code-tool skill.


Mode Selection Guide

The Code node offers two execution modes. Choose based on your use case:

Use this mode for: 95% of use cases

  • How it works: Code executes once regardless of input count

  • Data access: $input.all() or items array

  • Best for: logic that needs every item at once and passed the gate above

  • Performance: Faster for multiple items (single execution)

// Example: running balance — each item depends on the ones before it,
// which no native node expresses (Summarize gives one total per group, not a running one)
let balance = 0;
return $input.all().map(item => {
  balance += item.json.amount || 0;
  return { json: { ...item.json, balance } };
});

When to use:

  • ✅ Each item depends on earlier items (running totals, sessionizing events, gap detection)

  • ✅ Multi-pass algorithms or recursion over nested data of unknown depth

  • ✅ Heavy transforms over thousands of items where one node beats a long chain (measured)

Native first: totals, averages and counts → Summarize; sorting or ranking → Sort + Limit; deduplication → Remove Duplicates; items into one array → Aggregate; joining two lists → Merge.

Run Once for Each Item

Use this mode for: Specialized cases only

  • How it works: Code executes separately for each input item

  • Data access: $input.item or $item

  • Best for: Item-specific logic, independent operations, per-item validation

  • Performance: Slower for large datasets (multiple executions)

// Example: Add processing timestamp to each item
const item = $input.item;

return [{
  json: {
    ...item.json,
    processed: true,
    processedAt: new Date().toISOString()
  }
}];

When to use:

  • ✅ Each item needs independent API call

  • ✅ Per-item validation with different error handling

  • ✅ Item-specific transformations based on item properties

  • ✅ When items must be processed separately for business logic

Decision Shortcut:

  • Need to look at multiple items? → Use "All Items" mode

  • Each item completely independent? → Use "Each Item" mode

  • Not sure? → Use "All Items" mode (you can always loop inside)

Why "All Items" is faster — the per-item boundary

Mode choice is the single biggest performance lever in a Code node. Each per-item execution context costs a setup tax (measured on n8n 2.x, small records):

What runs per itemApprox. cost
Code All Items (one run for the whole set)~0.02 ms/item
Expression in any node (IF / Set / etc.)~0.2 ms/item
Code Each Item (a full sandbox per item)~0.6 ms/item — ~25–30× All Items

So Run Once for Each Item over 10k items is ~6 s of pure overhead vs ~0.2 s in Run Once for All Items. Use Each Item only when an item genuinely needs isolating (independent error handling, or a per-item API call you can't batch); otherwise loop inside one All Items node. Expression complexity itself is essentially free (~90% of the cost is the per-item context, not your code) and every node→node hop re-copies all items — so reduce the number of per-item boundaries, don't micro-optimize each one.

On top of the per-item cost, every Code node run pays a fixed hand-off to the task runner. In the default internal mode the runner stops after 15 s idle (N8N_RUNNERS_AUTO_SHUTDOWN_TIMEOUT), so a workflow that runs now and then pays a cold start of hundreds of milliseconds on most runs. Native transform nodes process all items in one in-process call and skip that hand-off.

What this means for node choice. Most workflows are I/O-bound, and below a few hundred items none of these costs matter: choose by readability, which means native nodes first. Performance becomes the deciding argument only for heavy all-items work — thousands of items per run, transform work rather than I/O dominating, stated by the user or measured. Then one All Items Code node can beat a long chain of nodes, and the reason goes in its Why Code: note. These figures are the pack's one measured reference; the other skills point here instead of repeating them.

See: DATA_ACCESS.md → "Mode Performance" for the corollaries, hop costs, and scale check.


Data Access Patterns

Four ways to pull data from upstream nodes. Note $node["Name"] and $('Name') need .first().json or .all() — never .json directly.

const allItems = $input.all();          // 1. All items — batch ops, aggregation (most common)
const data = $input.first().json;       // 2. First item — single objects, API responses
const item = $input.item;               // 3. Current item — "Each Item" mode ONLY (undefined otherwise)
const other = $node["Webhook"].json;    // 4. Named node — combine data across nodes

Always access fields via .json (e.g. item.json.name, not item.name), and prefer the explicit $input.first().json.field over a bare $json.field.

See: DATA_ACCESS.md for the full guide — every pattern with examples, a decision tree, and the common mistakes (mutating originals, missing length checks, $input.item in the wrong mode).


Critical: Webhook Data Structure

MOST COMMON MISTAKE: Webhook data is nested under .body

// ❌ WRONG - Will return undefined
const name = $json.name;
const email = $json.email;

// ✅ CORRECT - Webhook data is under .body
const name = $json.body.name;
const email = $json.body.email;

// Or with $input
const webhookData = $input.first().json.body;
const name = webhookData.name;

Why: Webhook node wraps all request data under body property. This includes POST data, query parameters, and JSON payloads.

See: DATA_ACCESS.md for full webhook structure details


Return Format Requirements

Canonical form: [{json: {...}}] — an array of objects each with a json property. It is unambiguous and works identically in both execution modes, so make it your default.

In Run Once for All Items mode n8n auto-normalizes looser shapes on the way out: a single bare object, or an array of bare objects, gets wrapped under json for you. So return {foo: 1} runs. What has nothing to wrap — and therefore genuinely fails at runtime with "Code doesn't return items properly" — is a primitive (string/number/boolean) or null/undefined. (n8n-mcp ≥ 2.63.0 no longer flags a bare-object return as an error; it reflects this auto-wrap behavior.)

Correct Return Formats
// ✅ Single result
return [{
  json: {
    field1: value1,
    field2: value2
  }
}];

// ✅ Multiple results
return [
  {json: {id: 1, data: 'first'}},
  {json: {id: 2, data: 'second'}}
];

// ✅ Transformed array
const transformed = $input.all()
  .filter(item => item.json.valid)
  .map(item => ({
    json: {
      id: item.json.id,
      processed: true
    }
  }));
return transformed;

// ✅ Empty result (when no data to return)
return [];

// ✅ Conditional return
if (shouldProcess) {
  return [{json: processedData}];
} else {
  return [];
}
Non-Canonical Returns (auto-wrapped — prefer the canonical form)
// ⚠️ Auto-wrapped in All Items mode → [{json: {field: value}}]. Runs, but prefer the array form.
return {
  json: {field: value}
};

// ⚠️ Auto-wrapped → [{json: {field: value}}]. Runs, but add the json wrapper for clarity.
return [{field: value}];

// ✅ Fine — input items already carry a json property, so returning them unchanged is a valid passthrough
return $input.all();
Genuinely Broken Returns
// ❌ FAILS: primitive — n8n errors "Code doesn't return items properly"
return "processed";

// ❌ FAILS: null / undefined — nothing to pass to the next node
return null;

Why it matters: The canonical [{json: {...}}] is unambiguous and behaves the same in both modes. n8n auto-normalizes bare objects and arrays-of-objects in All Items mode, but a primitive or null return has nothing to wrap and stops execution.

See: ERROR_PATTERNS.md #3 for detailed error solutions


Common Patterns Overview

The most useful Code node shapes from production workflows, for when Code passed the gate. Several of them have a native equivalent (totals → Summarize, top-N → Sort + Limit, JSON comparison → Compare Datasets, string aggregation → Aggregate or Summarize concatenate); each pattern in the library opens with its native alternative. The full library covers 10 patterns: multi-source aggregation, regex filtering, markdown/structured-text parsing, JSON comparison, CRM/form transformation, release processing, array transformation with computed fields, Slack Block Kit formatting, top-N ranking, and string-aggregation reporting — each with variations.

See: COMMON_PATTERNS.md for the 10 detailed production patterns (and the Best Practices section: validate input, try-catch, filter-early, array methods over loops, console.log debugging).


Error Prevention - Top Mistakes

The recurring Code node failures, in rough frequency order:

  1. Empty code / missing return — always end with return [...], and make sure every branch returns.

  2. Expression syntax as code — don't write {{ }} where JavaScript belongs (return {{ $json.x }} is a syntax error). Use `${$json.field}` or $input.first().json.field. {{ }} inside a string literal is fine — it's just literal text n8n won't evaluate.

  3. Return shape — prefer return [{json:{...}}]. A bare return {…} auto-wraps in All Items mode, but returning a primitive (string/number) or null is what actually fails.

  4. Missing null checks — use optional chaining: item.json?.user?.email || 'fallback'.

  5. Webhook body nesting — $json.email is undefined; use $json.body.email.

  6. Auth helpers blocked (httpRequestWithAuthentication) and $env blocked — route secrets through credentials/HTTP Request node, not the Code node sandbox.

See: ERROR_PATTERNS.md for the comprehensive guide — each error with wrong/right code, escaping rules, the sandbox restrictions (Errors #6–#7), a prevention checklist, and a quick error-message lookup table.


Built-in Functions & Helpers

// HTTP requests (no auth — see sandbox note below)
const res = await this.helpers.httpRequest({ method: 'GET', url: 'https://api.example.com/data' });

// DateTime (Luxon): now, formatting, arithmetic
const now = DateTime.now();
const formatted = now.toFormat('yyyy-MM-dd');
const tomorrow = now.plus({ days: 1 });

// $jmespath() — query JSON structures
const adults = $jmespath($input.first().json, 'users[?age >= `18`]');

// $getWorkflowStaticData() — data that persists across executions

Sandbox (since n8n v2.0, JsTaskRunnerSandbox): the accessor is this.helpers.httpRequest() — the bare $helpers global is undefined here ($helpers.httpRequest() throws ReferenceError). Inside a nested async function where this is lost, call it as await fn.call(this, ...). this.helpers.httpRequestWithAuthentication and this.helpers.requestWithAuthenticationPaginated are deny-listed (→ UnsupportedFunctionError); for authenticated calls use an HTTP Request node with the credential (preferred), a sub-workflow, or a manual Authorization: Bearer ${token} header on this.helpers.httpRequest() only when the token already flows through the workflow as data. $env is blocked when N8N_BLOCK_ENV_ACCESS_IN_NODE=true; require() works only for allowlisted modules. Buffer, URL, and standard JS globals (Math, JSON, Object, Array) always work.

See: BUILTIN_FUNCTIONS.md for the complete reference — full httpRequest options, all DateTime/Luxon operations, JMESPath patterns, static-data use cases, and the sandbox-restriction details.


Best Practices

  • Validate input first — guard for empty arrays / missing .json before processing.

  • Try-catch risky work (HTTP calls) and return an error object instead of crashing.

  • Prefer array methods (filter/map/reduce) over manual loops.

  • Filter early, transform late — shrink the dataset before expensive work.

  • Descriptive names and console.log() for debugging (output goes to the browser console).

See: COMMON_PATTERNS.md → "Best Practices" for code examples of each.


Production Gotchas

Hard-won lessons from real deployments — summarized here, with code in DATA_ACCESS.md → "Production Gotchas":

  • SplitInBatches outputs are counterintuitive: main[0] = done (fires once, after all batches), main[1] = each batch (the loop body). Add a Limit 1 node after the done output as a safety.

  • Iteration count is the cost: each loop iteration re-runs the whole body through the engine (~0.8 ms overhead each). batchSize: 1 is the loop equivalent of Each Item — use the largest batch your real constraint (rate limit, page size, memory) allows, or don't loop at all.

  • Cross-iteration accumulation (CRITICAL): after the loop, $('Node Inside Loop').all() returns ONLY the last iteration's items. Accumulate via $getWorkflowStaticData('global') (reset before, push inside, read after).

  • pairedItem: when emitting items that don't map 1:1 to input, set pairedItem: { item: i } or downstream Set nodes fail with paired_item_no_info.

  • Node reference syntax: $('Node').first().json or $('Node').all() — never .json directly on the reference.

  • Float precision: compare currency at the cent level — Math.round(a*100) !== Math.round(b*100) — to avoid false positives from float noise.


When to Use Code Node

Code is the last rung, after the service's own node, a native node for the job, and a short expression inside that node. The gate at the top of this skill is the test; this is the closed list it checks against:

Code is right forExampleNot Code
Loops or recursion no node expressesflatten a tree of unknown depth; multi-pass matchingone level of nesting → Split Out
State across runscounters or cursors in $getWorkflowStaticData"only new items" → Remove Duplicates across executions
Parsing no node handlesfixed-width records, a custom log formatCSV / XLSX / PDF / XML / HTML → Extract From File, XML, HTML
An allowlisted libraryrequire('some-lib') the instance allowshashing / HMAC / UUID → Crypto
Heavy all-items workthousands of items, transform-bound, stated or measureda few hundred items → native nodes
One short node replacing 4+ glue nodes~15 lines that would otherwise be a Set → Split Out → Set → Aggregate chain that only reshapes dataa chain with real routing or I/O in it

Not on the list, so not Code: filtering (Filter), routing (IF / Switch), totals and counts (Summarize), top-N (Sort + Limit), dedupe (Remove Duplicates), joins (Merge), diffs (Compare Datasets), dates (Date & Time or a Luxon expression), API calls and paging (HTTP Request), crypto and XML (Crypto, XML).

Every Code node that stays carries the note Why Code: <native node considered> — <reason> (set notes, and notesInFlow: true to show it on the canvas). The create/update hooks remind you when a Code node has no such note.


Integration with Other Skills

Works With:

n8n Expression Syntax:

  • Expressions use {{ }} syntax in other nodes

  • Code nodes use JavaScript directly (no {{ }})

  • When to use expressions vs code

n8n MCP Tools Expert:

  • How to find Code node: search_nodes({query: "code"})

  • Get configuration help: get_node({nodeType: "nodes-base.code"})

  • Validate code: validate_node({nodeType: "nodes-base.code", config: {...}})

n8n Node Configuration:

  • Mode selection (All Items vs Each Item)

  • Language selection (JavaScript vs Python)

  • Understanding property dependencies

n8n Workflow Patterns:

  • Code nodes in transformation step

  • Webhook → Code → API pattern

  • Error handling in workflows

n8n Validation Expert:

  • Validate Code node configuration

  • Handle validation errors

  • Auto-fix common issues


Quick Reference Checklist

Before deploying Code nodes, verify:

  • [ ] Passed the gate - No native node fits; notes starts with Why Code:

  • [ ] Code is not empty - Must have meaningful logic

  • [ ] Return statement exists - Returns items, not a primitive/null

  • [ ] Canonical return format - Each item: {json: {...}} (bare objects auto-wrap, but be explicit)

  • [ ] Data access correct - Using $input.all(), $input.first(), or $input.item

  • [ ] No {{ }} written as code - Use JavaScript template literals: `${value}`

  • [ ] Error handling - Guard clauses for null/undefined inputs

  • [ ] Webhook data - Access via .body if from webhook

  • [ ] Mode selection - "All Items" for most cases

  • [ ] Performance - Prefer map/filter over manual loops

  • [ ] Output consistent - All code paths return same structure


Additional Resources

n8n Documentation

Ready to write JavaScript in n8n Code nodes! Start with simple transformations, use the error patterns guide to avoid common mistakes, and reference the pattern library for production-ready examples.

Files

ERROR_PATTERNS.md

Error Patterns - JavaScript Code Node

Complete guide to avoiding the most common Code node errors.


Overview

This guide covers the top 5 error patterns encountered in n8n Code nodes. Understanding and avoiding these errors will save you significant debugging time.

Error frequency (roughly ordered):

  1. Empty Code / Missing Return - the dominant error n8n itself rejects

  2. Expression Syntax used as Code - {{ }} written where JavaScript belongs

  3. Return Shape - primitive/null returns (bare objects auto-wrap)

  4. Broken Strings / Escaping - unbalanced quotes/brackets throw a JS syntax error

  5. Missing Null Checks - common runtime error


Error #1: Empty Code or Missing Return Statement

Frequency: Most common error (38% of all validation failures)

What Happens:

  • Workflow execution fails

  • Next nodes receive no data

  • Error: "Code cannot be empty" or "Code must return data"

The Problem
// ❌ ERROR: No code at all
// (Empty code field)
// ❌ ERROR: Code executes but doesn't return anything
const items = $input.all();

// Process items
for (const item of items) {
  console.log(item.json.name);
}

// Forgot to return!
// ❌ ERROR: Early return path exists, but not all paths return
const items = $input.all();

if (items.length === 0) {
  return [];  // ✅ This path returns
}

// Process items
const processed = items.map(item => ({json: item.json}));

// ❌ Forgot to return processed!
The Solution
// ✅ CORRECT: Always return data
const items = $input.all();

// Process items
const processed = items.map(item => ({
  json: {
    ...item.json,
    processed: true
  }
}));

return processed;  // ✅ Return statement present
// ✅ CORRECT: Return empty array if no items
const items = $input.all();

if (items.length === 0) {
  return [];  // Valid: empty array when no data
}

// Process and return
return items.map(item => ({json: item.json}));
// ✅ CORRECT: All code paths return
const items = $input.all();

if (items.length === 0) {
  return [];
} else if (items.length === 1) {
  return [{json: {single: true, data: items[0].json}}];
} else {
  return items.map(item => ({json: item.json}));
}

// All paths covered
Checklist
  • [ ] Code field is not empty

  • [ ] Return statement exists

  • [ ] ALL code paths return data (if/else branches)

  • [ ] Return format is correct ([{json: {...}}])

  • [ ] Return happens even on errors (use try-catch)


Error #2: Expression Syntax Confusion

What Happens — there are two distinct cases, and only one is a syntax error:

  • {{ }} inside a string literal: valid JavaScript that runs fine, but you get the literal text {{ ... }} instead of a value — n8n does not evaluate expressions inside Code-node code. A logic bug, not a validation error. (n8n-mcp ≥ 2.63.0 no longer flags {{ }} inside string literals — prompt templates, payload placeholders, and .replace() tokens are legitimate.)

  • {{ }} written as bare code (e.g. return {{ $json.x }}): a genuine JavaScript syntax error. The validator reports "Expression syntax {{...}} is not valid in Code nodes" and n8n throws "Unexpected token".

The Problem

n8n has TWO distinct syntaxes:

  1. Expression syntax {{ }} - Used in OTHER nodes (Set, IF, HTTP Request)

  2. JavaScript - Used in CODE nodes

Many developers mistakenly reach for expression syntax inside a Code node when they want a value. Putting {{ }} in a string does not interpolate it:

// ❌ LOGIC BUG: n8n never evaluates {{ }} in Code-node strings
const userName = "{{ $json.name }}";
const userEmail = "{{ $json.body.email }}";

return [{
  json: {
    name: userName,
    email: userEmail
  }
}];

// Result: Literal string "{{ $json.name }}", NOT the value!
// (This runs — it just doesn't do what you meant. Use $json.name directly.)
// ❌ SYNTAX ERROR: {{ }} used as code, not inside a string
const value = {{ $now.toFormat('yyyy-MM-dd') }};  // "Unexpected token"
The Solution
// ✅ CORRECT: Use JavaScript directly (no {{ }})
const userName = $json.name;
const userEmail = $json.body.email;

return [{
  json: {
    name: userName,
    email: userEmail
  }
}];
// ✅ CORRECT: JavaScript template literals (use backticks)
const message = `Hello, ${$json.name}! Your email is ${$json.email}`;

return [{
  json: {
    greeting: message
  }
}];
// ✅ CORRECT: Direct variable access
const item = $input.first().json;

return [{
  json: {
    name: item.name,
    email: item.email,
    timestamp: new Date().toISOString()  // JavaScript Date, not {{ }}
  }
}];
Comparison Table
ContextSyntaxExample
Set node{{ }} expressions{{ $json.name }}
IF node{{ }} expressions{{ $json.age > 18 }}
HTTP Request URL{{ }} expressions{{ $json.userId }}
Code nodeJavaScript$json.name
Code node stringsTemplate literals`Hello ${$json.name}`
Quick Fix Guide
// WRONG → RIGHT conversions

// ❌ "{{ $json.field }}"
// ✅ $json.field

// ❌ "{{ $now }}"
// ✅ new Date().toISOString()

// ❌ "{{ $node['HTTP Request'].json.data }}"
// ✅ $node["HTTP Request"].json.data

// ❌ `{{ $json.firstName }} {{ $json.lastName }}`
// ✅ `${$json.firstName} ${$json.lastName}`

Error #3: Return Shape

What actually happens — n8n is more forgiving than the old advice implied:

  • In Run Once for All Items mode, n8n auto-normalizes a single bare object, or an array of bare objects, by wrapping each under a json property. So these run.

  • What genuinely fails, with "Code doesn't return items properly", is returning a primitive (string/number/boolean) or null/undefined — there is nothing to wrap.

(n8n-mcp ≥ 2.63.0 no longer errors "Return value must be an array of objects" on a bare-object return; the earlier claim contradicted n8n's auto-wrap behavior.)

Prefer the Canonical Form

The canonical [{json: {...}}] is unambiguous and behaves identically in both execution modes, so make it your default even though looser shapes are auto-wrapped:

// ⚠️ Auto-wrapped → [{json: {result: 'success'}}]. Runs, but prefer the array + json form.
return {
  json: {
    result: 'success'
  }
};
// ⚠️ Auto-wrapped → each object gets a json wrapper. Runs, but be explicit.
return [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'}
];
// ✅ Fine — input items already carry a json property; returning them unchanged is a valid passthrough
return $input.all();
// ❌ FAILS: primitive value — nothing to wrap into an item
return "processed";
// ❌ FAILS: null / undefined — no items to pass on
return null;
The Solution
// ✅ CORRECT: Single result
return [{
  json: {
    result: 'success',
    timestamp: new Date().toISOString()
  }
}];
// ✅ CORRECT: Multiple results
return [
  {json: {id: 1, name: 'Alice'}},
  {json: {id: 2, name: 'Bob'}},
  {json: {id: 3, name: 'Carol'}}
];
// ✅ CORRECT: Transforming array
const items = $input.all();

return items.map(item => ({
  json: {
    id: item.json.id,
    name: item.json.name,
    processed: true
  }
}));
// ✅ CORRECT: Empty result
return [];
// Valid when no data to return
// ✅ CORRECT: Conditional returns
if (shouldProcess) {
  return [{json: {result: 'processed'}}];
} else {
  return [];
}
Return Format Checklist
  • [ ] Return value is an array [...] (canonical — preferred)

  • [ ] Each array element has a json property

  • [ ] Structure is [{json: {...}}] or [{json: {...}}, {json: {...}}]

  • [ ] Not a primitive (string/number/boolean) or null/undefined — those are the shapes that actually fail

Common Scenarios
// Scenario 1: Single object from API
const response = $input.first().json;

// ✅ CANONICAL
return [{json: response}];

// ⚠️ Auto-wrapped to the same thing — runs, but prefer the array form
return {json: response};


// Scenario 2: Array of objects
const users = $input.all();

// ✅ CANONICAL
return users.map(user => ({json: user.json}));

// ✅ Also fine — a passthrough of items that already carry json
return users;


// Scenario 3: Computed result
const total = $input.all().reduce((sum, item) => sum + item.json.amount, 0);

// ✅ CANONICAL
return [{json: {total}}];

// ⚠️ Auto-wrapped → [{json: {total}}] in All Items mode — runs, but be explicit
return {total};


// Scenario 4: No results
// ✅ CORRECT
return [];

// ❌ FAILS — null has no items to pass on
return null;

Error #4: Broken Strings & Escaping (JavaScript syntax errors)

What Happens:

  • The Code node throws a JavaScript syntax error at execution: "Unexpected token" or "Unexpected end of input"

  • Cause is your own JS — unbalanced quotes or a raw newline inside a plain quoted string

This is a plain JavaScript concern, not a validator check. The validator (n8n-mcp ≥ 2.63.0) does not flag balanced apostrophes, { } in regex, or {{ }} sitting inside a string literal — those are all valid JavaScript. Only genuinely malformed JS throws, and it throws at runtime.

The Problem

This happens when:

  1. A quote inside a same-quoted string is left unescaped

  2. A plain (non-template) string spans multiple lines

  3. Backslashes in paths/regex are not escaped

// ✅ FINE: an apostrophe inside a double-quoted string is valid JavaScript
const message = "It's a nice day";

// ✅ FINE: braces in a regex literal are valid
const pattern = /\{(\w+)\}/;
// ❌ SYNTAX ERROR: raw newline + unescaped inner double-quotes in a plain string
const html = "
  <div class="container">
    <p>Hello</p>
  </div>
";
The Solution
// ✅ Mix quote styles or escape, whichever reads cleaner
const message = "It's a nice day";     // double quotes around an apostrophe — fine
const other   = 'She said "hello"';    // single quotes around double quotes — fine
// ✅ Regex literals need no extra escaping of their own braces
const pattern = /\{(\w+)\}/;
// ✅ CORRECT: Template literals for multi-line
const html = `
  <div class="container">
    <p>Hello</p>
  </div>
`;
// Backticks handle multi-line and quotes
// ✅ CORRECT: Escape backslashes
const path = "C:\\\\Users\\\\Documents\\\\file.txt";
Escaping Guide
CharacterEscape AsExample
Single quote in single-quoted string\\''It\\'s working'
Double quote in double-quoted string\\""She said \\"hello\\""
Backslash\\\\"C:\\\\path"
Newline\\n"Line 1\\nLine 2"
Tab\\t"Column1\\tColumn2"
Best Practices
// ✅ BEST: Use template literals for complex strings
const message = `User ${name} said: "Hello!"`;

// ✅ BEST: Use template literals for HTML
const html = `
  <div class="${className}">
    <h1>${title}</h1>
    <p>${content}</p>
  </div>
`;

// ✅ BEST: Use template literals for JSON
const jsonString = `{
  "name": "${name}",
  "email": "${email}"
}`;

Error #5: Missing Null Checks / Undefined Access

Frequency: Very common runtime error

What Happens:

  • Workflow execution stops

  • Error: "Cannot read property 'X' of undefined"

  • Error: "Cannot read property 'X' of null"

  • Crashes on missing data

The Problem
// ❌ WRONG: No null check - crashes if user doesn't exist
const email = item.json.user.email;
// ❌ WRONG: Assumes array has items
const firstItem = $input.all()[0].json;
// ❌ WRONG: Assumes nested property exists
const city = $json.address.city;
// ❌ WRONG: No validation before array operations
const names = $json.users.map(user => user.name);
The Solution
// ✅ CORRECT: Optional chaining
const email = item.json?.user?.email || '[email protected]';
// ✅ CORRECT: Check array length
const items = $input.all();

if (items.length === 0) {
  return [];
}

const firstItem = items[0].json;
// ✅ CORRECT: Guard clauses
const data = $input.first().json;

if (!data.address) {
  return [{json: {error: 'No address provided'}}];
}

const city = data.address.city;
// ✅ CORRECT: Default values
const users = $json.users || [];
const names = users.map(user => user.name || 'Unknown');
// ✅ CORRECT: Try-catch for risky operations
try {
  const email = item.json.user.email.toLowerCase();
  return [{json: {email}}];
} catch (error) {
  return [{
    json: {
      error: 'Invalid user data',
      details: error.message
    }
  }];
}
Safe Access Patterns
// Pattern 1: Optional chaining (modern, recommended)
const value = data?.nested?.property?.value;

// Pattern 2: Logical OR with default
const value = data.property || 'default';

// Pattern 3: Ternary check
const value = data.property ? data.property : 'default';

// Pattern 4: Guard clause
if (!data.property) {
  return [];
}
const value = data.property;

// Pattern 5: Try-catch
try {
  const value = data.nested.property.value;
} catch (error) {
  const value = 'default';
}
Webhook Data Safety
// Webhook data requires extra safety

// ❌ RISKY: Assumes all fields exist
const name = $json.body.user.name;
const email = $json.body.user.email;

// ✅ SAFE: Check each level
const body = $json.body || {};
const user = body.user || {};
const name = user.name || 'Unknown';
const email = user.email || 'no-email';

// ✅ BETTER: Optional chaining
const name = $json.body?.user?.name || 'Unknown';
const email = $json.body?.user?.email || 'no-email';
Array Safety
// ❌ RISKY: No length check
const items = $input.all();
const firstId = items[0].json.id;

// ✅ SAFE: Check length
const items = $input.all();

if (items.length > 0) {
  const firstId = items[0].json.id;
} else {
  // Handle empty case
  return [];
}

// ✅ BETTER: Use $input.first()
const firstItem = $input.first();
const firstId = firstItem.json.id;  // Built-in safety
Object Property Safety
// ❌ RISKY: Direct access
const config = $json.settings.advanced.timeout;

// ✅ SAFE: Step by step with defaults
const settings = $json.settings || {};
const advanced = settings.advanced || {};
const timeout = advanced.timeout || 30000;

// ✅ BETTER: Optional chaining
const timeout = $json.settings?.advanced?.timeout ?? 30000;
// Note: ?? (nullish coalescing) vs || (logical OR)

Error #6: UnsupportedFunctionError (Auth Helpers Blocked)

Frequency: The most common "this worked yesterday in old n8n" error after upgrading to v2.0+

What Happens:

  • Error: UnsupportedFunctionError: The function "helpers.httpRequestWithAuthentication" is not supported in the Code Node

  • Same for helpers.requestWithAuthenticationPaginated

  • Throws on execution, not on save

The Problem

Since n8n v2.0, Code nodes execute in the task runner sandbox which deliberately blocks the auth helpers. The legacy vm2 sandbox used to bind them, which is why old forum posts and tutorials show them working. n8n's source comment explains why: the Code node has no credential of its own, so the helper had nothing to authenticate against — it was always semantically broken, just not always loud about it.

// ❌ BLOCKED in task runner sandbox (default since v2.0)
const data = await this.helpers.httpRequestWithAuthentication.call(
  this,
  'baseLinkerApi',
  { url: '...', method: 'POST' }
);
The Solution

There is no env flag to re-enable these in the runner — the deny-list is compiled-in. Pick one of:

Option A — Replace the Code node with an HTTP Request node (best):

The HTTP Request node natively supports credential attachment with full expression support for URL/body/headers. Most "Code-node-makes-an-API-call" patterns are leftovers from before HTTP Request had pagination and expression support.

Option B — Sub-workflow with HTTP Request node (when you need code-level logic before/after):

// Parent Code node — prepare payloads, then delegate
return $input.all().map(i => ({ json: {
  url: 'https://api.example.com/things',
  method: 'POST',
  body: { sku: i.json.sku }
}}));

Then wire to Execute Workflow → child workflow with Execute Workflow Trigger → HTTP Request node using ={{ $json.url }}, ={{ $json.body }}, with the credential attached natively.

Option C — Token as runtime data (only when the token genuinely flows through the workflow):

// ✅ Works — manual auth header, token came from upstream
const token = $('Get Token').first().json.access_token;

const data = await this.helpers.httpRequest({
  url: 'https://api.example.com/data',
  headers: { 'Authorization': `Bearer ${token}` }
});
Decision Guide
NeedUse
Single authenticated API callHTTP Request node directly
Many API calls + pre/post processingSub-workflow pattern (Option B)
Token already in the data flowManual this.helpers.httpRequest() with header
httpRequestWithAuthenticationDoesn't work — pick A, B, or C above

Error #7: $env is not defined / Cannot access $env

Frequency: Common in hardened production instances

What Happens:

  • Error: $env is not defined or ReferenceError: $env is not defined

  • Code looks correct, runs fine on dev instance, throws in production

The Problem

$env access is gated by the N8N_BLOCK_ENV_ACCESS_IN_NODE environment variable. When set to true (a common production hardening setting), $env is removed from the Code node sandbox entirely. This is increasingly the default in security-conscious deployments.

// ❌ Throws if N8N_BLOCK_ENV_ACCESS_IN_NODE=true
const apiKey = $env.API_KEY;
The Solution

Treat secrets as a credential concern, not a Code-node concern:

// ✅ Token arrives as data from an upstream node that used a credential
const apiKey = $('Set Secret').first().json.apiKey;

// Or: secret was attached server-side by an HTTP Request node with the credential
// — your Code node never sees the raw secret, which is the whole point

For values you genuinely need to inject from outside the workflow (config, not secrets), use:

  • A Set node at the top of the workflow with hardcoded constants, or

  • An n8n credential referenced by an HTTP Request node, or

  • The External Secrets integration ($secrets) if your edition supports it.

Why This Matters

Skills and tutorials written before 2024 routinely use $env.API_KEY because it was the path of least resistance. Modern n8n setups block it because letting Code nodes read arbitrary env vars is a privilege escalation surface — any user with workflow-edit access could exfiltrate DB_PASSWORD, N8N_ENCRYPTION_KEY, etc. Don't fight the restriction; route secrets through credentials.


Error Prevention Checklist

Use this checklist before deploying Code nodes:

Code Structure
  • [ ] Code field is not empty

  • [ ] Return statement exists

  • [ ] All code paths return data

Return Format
  • [ ] Returns items, not a primitive/null

  • [ ] Canonical shape [{json: {...}}] (bare objects auto-wrap, but be explicit)

Syntax
  • [ ] No {{ }} written as code (it's for other nodes' fields; in a string it's just literal text)

  • [ ] Template literals use backticks: `${variable}`

  • [ ] All quotes and brackets balanced

  • [ ] Strings properly escaped

Data Safety
  • [ ] Null checks for optional properties

  • [ ] Array length checks before access

  • [ ] Webhook data accessed via .body

  • [ ] Try-catch for risky operations

  • [ ] Default values for missing data

Testing
  • [ ] Test with empty input

  • [ ] Test with missing fields

  • [ ] Test with unexpected data types

  • [ ] Check browser console for errors


Quick Error Reference

Error MessageLikely CauseFix
"Code cannot be empty"Empty code fieldAdd meaningful code
"Code must return data"Missing return statementAdd return [...]
"Code doesn't return items properly"Returned a primitive (string/number) or nullReturn [{json:{...}}] (objects/arrays auto-wrap; primitives don't)
"Not all items have a json key"Mixed return — some items wrapped, some bareWrap every item: {json: {...}}
"Expression syntax {{...}} is not valid in Code nodes" / "Unexpected token"{{ }} written as code (not inside a string)Use JavaScript: $json.x or `${$json.x}`
"Cannot read property X of undefined"Missing null checkUse optional chaining ?.
"Cannot read property X of null"Null value accessAdd guard clause or default
"Unexpected end of input"Unbalanced quotes/brackets in your JSEscape strings or use backtick template literals
"UnsupportedFunctionError ... httpRequestWithAuthentication"Auth helper blocked in task runnerUse HTTP Request node + credential, or sub-workflow pattern (Error #6)
"$env is not defined"N8N_BLOCK_ENV_ACCESS_IN_NODE=trueRoute secrets through credentials, not $env (Error #7)
"Cannot find module 'crypto'"require() allowlist not setMove logic out of Code node, or set N8N_RUNNERS_ALLOWED_BUILT_IN_MODULES

Debugging Tips

1. Use console.log()
const items = $input.all();
console.log('Items count:', items.length);
console.log('First item:', items[0]);

// Check browser console (F12) for output
2. Return Intermediate Results
// Debug by returning current state
const items = $input.all();
const processed = items.map(item => ({json: item.json}));

// Return to see what you have
return processed;
3. Try-Catch for Troubleshooting
try {
  // Your code here
  const result = riskyOperation();
  return [{json: {result}}];
} catch (error) {
  // See what failed
  return [{
    json: {
      error: error.message,
      stack: error.stack
    }
  }];
}
4. Validate Input Structure
const items = $input.all();

// Check what you received
console.log('Input structure:', JSON.stringify(items[0], null, 2));

// Then process

Summary

Top 7 Errors to Avoid:

  1. Empty code / missing return - Always return data

  2. Expression syntax as code - Use JavaScript, not {{ }} (in-string {{ }} is just literal text)

  3. Return shape - prefer [{json: {...}}]; primitives/null fail (bare objects auto-wrap)

  4. Broken strings - unbalanced quotes/brackets throw a JS syntax error; escape or use template literals

  5. Missing null checks - Use optional chaining ?.

  6. httpRequestWithAuthentication blocked - Use HTTP Request node + credential

  7. $env blocked - Route secrets through credentials, not env access

Quick Prevention:

  • Prefer the canonical [{json: {...}}] return; never return a primitive or null

  • Write JavaScript — don't put {{ }} where code belongs

  • Check for null/undefined before accessing

  • Test with empty and invalid data

  • Use browser console for debugging

See Also:

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Node.js

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Romuald Czlonkowski
Publisher
Romuald Czlonkowski (Community)
Source
czlonkowski/n8n-skills · skills/n8n-code-javascript · commit e037563
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Romuald Czlonkowski.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download n8n-code-javascript.zip