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://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

BUILTIN_FUNCTIONS.md

Built-in Functions - JavaScript Code Node

Complete reference for n8n's built-in JavaScript functions and helpers.


Overview

n8n Code nodes provide powerful built-in functions beyond standard JavaScript. This guide covers:

  1. Sandbox restrictions - What's blocked and why (READ FIRST)

  2. this.helpers.httpRequest() - Make HTTP requests (the bare $helpers global is undefined in the task runner)

  3. DateTime (Luxon) - Advanced date/time operations

  4. $jmespath() - Query JSON structures

  5. $getWorkflowStaticData() - Persistent storage

  6. Standard JavaScript Globals - Math, JSON, console, etc.

  7. Available Node.js Modules - crypto, Buffer, URL


0. Sandbox Restrictions (Critical)

Since n8n v2.0, Code nodes execute inside a task runner sandbox (JsTaskRunnerSandbox) which deliberately blocks several APIs. The legacy vm2 sandbox is being removed. Knowing what's blocked saves hours of "why does this throw on activation but not in the editor preview."

Blocked helpers
// ❌ BLOCKED — throws UnsupportedFunctionError
await this.helpers.httpRequestWithAuthentication.call(this, 'credType', { ... });
await this.helpers.requestWithAuthenticationPaginated.call(this, { ... }, 'credType');

n8n's source comment explains why: "these rely on checking the credentials from the current node type (Code Node), and Code Node doesn't have credentials." There is no env var to re-enable them in the task runner — the deny-list is compiled-in (packages/@n8n/task-runner/src/runner-types.ts).

Workaround: don't try to authenticate from inside a Code node. Instead, either:

  • Replace the Code node with an HTTP Request node that has the credential attached (the canonical pattern), or

  • Have the Code node prepare a payload and delegate to a sub-workflow whose HTTP Request node holds the credential.

$env may be blocked

$env is gated by N8N_BLOCK_ENV_ACCESS_IN_NODE. When set to true (a common production hardening), any reference to $env.SOMETHING throws. Since you can't tell from inside the Code node whether it's enabled, don't rely on $env for portable skills — treat secrets as a credential concern (HTTP Request node) rather than a Code-node concern.

require() is gated by allowlists
// May throw "Cannot find module 'crypto'" — depends on env vars
const crypto = require('crypto');

Built-in modules need N8N_RUNNERS_ALLOWED_BUILT_IN_MODULES (or legacy NODE_FUNCTION_ALLOW_BUILTIN) set to * or a comma-list including crypto. External npm packages need N8N_RUNNERS_ALLOWED_EXTERNAL_MODULES plus the package being installed in the runner image. On default installs neither is set — require() throws.

Buffer and URL are globals (not require'd), so they always work.

What's always safe

$input.*, $json, $node[…], this.helpers.httpRequest() (without auth), $jmespath(), $getWorkflowStaticData(), DateTime (Luxon), and all standard JavaScript globals (Math, JSON, Object, Array, console, Buffer, URL, URLSearchParams).

Accessor gotcha: the bare $helpers global is undefined in the task-runner sandbox — $helpers.httpRequest() throws ReferenceError: $helpers is not defined. The working accessor is this.helpers.httpRequest() (inside a nested async function where this is lost, call it as await fn.call(this, ...)). The n8n-mcp validator may wrongly suggest $helpers — ignore it. And for anything beyond a trivial unauthenticated GET (pagination, retries, credentials), prefer the HTTP Request node and keep Code nodes for pure logic.


1. this.helpers.httpRequest() - HTTP Requests

Call an API from inside Code logic, for example one lookup per step of a recursive algorithm. A plain API call, paging, retries or credentials belong in the HTTP Request node. The accessor is this.helpers.httpRequest() — the bare $helpers global is undefined in the task-runner sandbox and throws ReferenceError: $helpers is not defined. For non-trivial calls (pagination, retries, credentials) prefer the HTTP Request node.

Basic Usage
const response = await this.helpers.httpRequest({
  method: 'GET',
  url: 'https://api.example.com/users'
});

return [{json: {data: response}}];
Complete Options
const response = await this.helpers.httpRequest({
  method: 'POST',  // GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
  url: 'https://api.example.com/users',
  headers: {
    'Authorization': 'Bearer token123',
    'Content-Type': 'application/json',
    'User-Agent': 'n8n-workflow'
  },
  body: {
    name: 'John Doe',
    email: '[email protected]'
  },
  qs: {  // Query string parameters
    page: 1,
    limit: 10
  },
  timeout: 10000,  // Milliseconds (default: no timeout)
  json: true,  // Auto-parse JSON response (default: true)
  simple: false,  // Don't throw on HTTP errors (default: true)
  resolveWithFullResponse: false  // Return only body (default: false)
});
GET Request
// Simple GET
const users = await this.helpers.httpRequest({
  method: 'GET',
  url: 'https://api.example.com/users'
});

return [{json: {users}}];
// GET with query parameters
const results = await this.helpers.httpRequest({
  method: 'GET',
  url: 'https://api.example.com/search',
  qs: {
    q: 'javascript',
    page: 1,
    per_page: 50
  }
});

return [{json: results}];
POST Request
// POST with JSON body
// NOTE: For authenticated APIs, prefer an HTTP Request node with a credential
// attached. Embedding the token in a Code node only works when (a) the token
// arrives as runtime data (e.g. from a previous node), or (b) you're sure
// $env access is enabled on this instance. See section 0.
const apiToken = $input.first().json.apiToken;  // passed in from a credential-aware upstream node

const newUser = await this.helpers.httpRequest({
  method: 'POST',
  url: 'https://api.example.com/users',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiToken}`
  },
  body: {
    name: $json.body.name,
    email: $json.body.email,
    role: 'user'
  }
});

return [{json: newUser}];
PUT/PATCH Request
// Update resource
const updated = await this.helpers.httpRequest({
  method: 'PATCH',
  url: `https://api.example.com/users/${userId}`,
  body: {
    name: 'Updated Name',
    status: 'active'
  }
});

return [{json: updated}];
DELETE Request
// Delete resource
await this.helpers.httpRequest({
  method: 'DELETE',
  url: `https://api.example.com/users/${userId}`,
  headers: {
    'Authorization': `Bearer ${apiToken}`  // token passed in from upstream node, not $env
  }
});

return [{json: {deleted: true, userId}}];
Authentication Patterns

Strong preference: don't authenticate from inside a Code node. Use an HTTP Request node with a credential attached, or delegate to a sub-workflow whose HTTP Request node holds the credential. The patterns below only apply when the token genuinely flows through the workflow as data.

// Bearer Token (token came from a previous node, not $env)
const response = await this.helpers.httpRequest({
  url: 'https://api.example.com/data',
  headers: {
    'Authorization': `Bearer ${$input.first().json.token}`
  }
});
// API Key in Header (key came from a previous node, not $env)
const response = await this.helpers.httpRequest({
  url: 'https://api.example.com/data',
  headers: {
    'X-API-Key': $input.first().json.apiKey
  }
});
// Basic Auth (manual)
const credentials = Buffer.from(`${username}:${password}`).toString('base64');

const response = await this.helpers.httpRequest({
  url: 'https://api.example.com/data',
  headers: {
    'Authorization': `Basic ${credentials}`
  }
});
Error Handling
// Handle HTTP errors gracefully
try {
  const response = await this.helpers.httpRequest({
    method: 'GET',
    url: 'https://api.example.com/users',
    simple: false  // Don't throw on 4xx/5xx
  });

  if (response.statusCode >= 200 && response.statusCode < 300) {
    return [{json: {success: true, data: response.body}}];
  } else {
    return [{
      json: {
        success: false,
        status: response.statusCode,
        error: response.body
      }
    }];
  }
} catch (error) {
  return [{
    json: {
      success: false,
      error: error.message
    }
  }];
}
Full Response Access
// Get full response including headers and status
const response = await this.helpers.httpRequest({
  url: 'https://api.example.com/data',
  resolveWithFullResponse: true
});

return [{
  json: {
    statusCode: response.statusCode,
    headers: response.headers,
    body: response.body,
    rateLimit: response.headers['x-ratelimit-remaining']
  }
}];

2. DateTime (Luxon) - Date & Time Operations

n8n includes Luxon for powerful date/time handling. Access via DateTime global.

Current Date/Time
// Current time
const now = DateTime.now();

// Current time in specific timezone
const nowTokyo = DateTime.now().setZone('Asia/Tokyo');

// Today at midnight
const today = DateTime.now().startOf('day');

return [{
  json: {
    iso: now.toISO(),  // "2025-01-20T15:30:00.000Z"
    formatted: now.toFormat('yyyy-MM-dd HH:mm:ss'),  // "2025-01-20 15:30:00"
    unix: now.toSeconds(),  // Unix timestamp
    millis: now.toMillis()  // Milliseconds since epoch
  }
}];
Formatting Dates
const now = DateTime.now();

return [{
  json: {
    isoFormat: now.toISO(),  // ISO 8601: "2025-01-20T15:30:00.000Z"
    sqlFormat: now.toSQL(),  // SQL: "2025-01-20 15:30:00.000"
    httpFormat: now.toHTTP(),  // HTTP: "Mon, 20 Jan 2025 15:30:00 GMT"

    // Custom formats
    dateOnly: now.toFormat('yyyy-MM-dd'),  // "2025-01-20"
    timeOnly: now.toFormat('HH:mm:ss'),  // "15:30:00"
    readable: now.toFormat('MMMM dd, yyyy'),  // "January 20, 2025"
    compact: now.toFormat('yyyyMMdd'),  // "20250120"
    withDay: now.toFormat('EEEE, MMMM dd, yyyy'),  // "Monday, January 20, 2025"
    custom: now.toFormat('dd/MM/yy HH:mm')  // "20/01/25 15:30"
  }
}];
Parsing Dates
// From ISO string
const dt1 = DateTime.fromISO('2025-01-20T15:30:00');

// From specific format
const dt2 = DateTime.fromFormat('01/20/2025', 'MM/dd/yyyy');

// From SQL
const dt3 = DateTime.fromSQL('2025-01-20 15:30:00');

// From Unix timestamp
const dt4 = DateTime.fromSeconds(1737384600);

// From milliseconds
const dt5 = DateTime.fromMillis(1737384600000);

return [{json: {parsed: dt1.toISO()}}];
Date Arithmetic
const now = DateTime.now();

return [{
  json: {
    // Adding time
    tomorrow: now.plus({days: 1}).toISO(),
    nextWeek: now.plus({weeks: 1}).toISO(),
    nextMonth: now.plus({months: 1}).toISO(),
    inTwoHours: now.plus({hours: 2}).toISO(),

    // Subtracting time
    yesterday: now.minus({days: 1}).toISO(),
    lastWeek: now.minus({weeks: 1}).toISO(),
    lastMonth: now.minus({months: 1}).toISO(),
    twoHoursAgo: now.minus({hours: 2}).toISO(),

    // Complex operations
    in90Days: now.plus({days: 90}).toFormat('yyyy-MM-dd'),
    in6Months: now.plus({months: 6}).toFormat('yyyy-MM-dd')
  }
}];
Time Comparisons
const now = DateTime.now();
const targetDate = DateTime.fromISO('2025-12-31');

return [{
  json: {
    // Comparisons
    isFuture: targetDate > now,
    isPast: targetDate < now,
    isEqual: targetDate.equals(now),

    // Differences
    daysUntil: targetDate.diff(now, 'days').days,
    hoursUntil: targetDate.diff(now, 'hours').hours,
    monthsUntil: targetDate.diff(now, 'months').months,

    // Detailed difference
    detailedDiff: targetDate.diff(now, ['months', 'days', 'hours']).toObject()
  }
}];
Timezone Operations
const now = DateTime.now();

return [{
  json: {
    // Current timezone
    local: now.toISO(),

    // Convert to different timezone
    tokyo: now.setZone('Asia/Tokyo').toISO(),
    newYork: now.setZone('America/New_York').toISO(),
    london: now.setZone('Europe/London').toISO(),
    utc: now.toUTC().toISO(),

    // Get timezone info
    timezone: now.zoneName,  // "America/Los_Angeles"
    offset: now.offset,  // Offset in minutes
    offsetFormatted: now.toFormat('ZZ')  // "+08:00"
  }
}];
Start/End of Period
const now = DateTime.now();

return [{
  json: {
    startOfDay: now.startOf('day').toISO(),
    endOfDay: now.endOf('day').toISO(),
    startOfWeek: now.startOf('week').toISO(),
    endOfWeek: now.endOf('week').toISO(),
    startOfMonth: now.startOf('month').toISO(),
    endOfMonth: now.endOf('month').toISO(),
    startOfYear: now.startOf('year').toISO(),
    endOfYear: now.endOf('year').toISO()
  }
}];
Weekday & Month Info
const now = DateTime.now();

return [{
  json: {
    // Day info
    weekday: now.weekday,  // 1 = Monday, 7 = Sunday
    weekdayShort: now.weekdayShort,  // "Mon"
    weekdayLong: now.weekdayLong,  // "Monday"
    isWeekend: now.weekday > 5,  // Saturday or Sunday

    // Month info
    month: now.month,  // 1-12
    monthShort: now.monthShort,  // "Jan"
    monthLong: now.monthLong,  // "January"

    // Year info
    year: now.year,  // 2025
    quarter: now.quarter,  // 1-4
    daysInMonth: now.daysInMonth  // 28-31
  }
}];

3. $jmespath() - JSON Querying

Query and transform JSON structures using JMESPath syntax.

Consider an expression first. $jmespath works the same inside {{ }}, so a query that only feeds one field rarely needs a Code node. See n8n-expression-syntax → $jmespath().

Rules that bite (verified on n8n 2.38)
  • Argument order is $jmespath(object, query), the reverse of JMESPath's own docs (search(query, data)). Reversed, or given a string/undefined as the object, it throws expected two arguments (Object, string) for this function.

  • String literals take single quotes (tier == 'premium'), so wrap the query in a JS double-quoted string. "premium" in double quotes inside the query is a field name and silently returns [].

  • Numbers and booleans take backticks (age >= `18`, inStock == `true`). A bare 18 is a parse error.

  • Use && || ! ==, not and / or / =.

  • Over $input.all() items, include the wrapper ([?json.age >= \18`].json.name) or map first: $jmespath($input.all().map(i => i.json), '[?age >= `18`].name')`.

  • Parse errors throw in a Code node, but the message comes out garbled by the task runner: Cannot assign to read only property 'name' of object 'Error: Invalid token (Number): "18"'. If you see that, check the query's literals first. (Inside {{ }} the same error silently yields null instead.)

  • Missing path → null; filter with no match → [].

Basic Queries
const data = $input.first().json;

// Extract specific field
const names = $jmespath(data, 'users[*].name');

// Filter array
const adults = $jmespath(data, 'users[?age >= `18`]');

// Get specific index
const firstUser = $jmespath(data, 'users[0]');

return [{json: {names, adults, firstUser}}];
Advanced Queries
const data = $input.first().json;

// Sort and slice
const top5 = $jmespath(data, 'users | sort_by(@, &score) | reverse(@) | [0:5]');

// Extract nested fields
const emails = $jmespath(data, 'users[*].contact.email');

// Multi-field extraction
const simplified = $jmespath(data, 'users[*].{name: name, email: contact.email}');

// Conditional filtering
const premium = $jmespath(data, "users[?subscription.tier == 'premium']");

return [{json: {top5, emails, simplified, premium}}];
Common Patterns
// Pattern 1: Filter and project
const query1 = $jmespath(data, 'products[?price > `100`].{name: name, price: price}');

// Pattern 2: Aggregate functions
const query2 = $jmespath(data, 'sum(products[*].price)');
const query3 = $jmespath(data, 'max(products[*].price)');
const query4 = $jmespath(data, 'length(products)');

// Pattern 3: Nested filtering
const query5 = $jmespath(data, 'categories[*].products[?inStock == `true`]');

return [{json: {query1, query2, query3, query4, query5}}];

4. $getWorkflowStaticData() - Persistent Storage

Store data that persists across workflow executions.

Basic Usage
// Get static data storage
const staticData = $getWorkflowStaticData();

// Initialize counter if doesn't exist
if (!staticData.counter) {
  staticData.counter = 0;
}

// Increment counter
staticData.counter++;

return [{
  json: {
    executionCount: staticData.counter
  }
}];
Use Cases
// Use Case 1: Rate limiting
const staticData = $getWorkflowStaticData();
const now = Date.now();

if (!staticData.lastRun) {
  staticData.lastRun = now;
  staticData.runCount = 1;
} else {
  const timeSinceLastRun = now - staticData.lastRun;

  if (timeSinceLastRun < 60000) {  // Less than 1 minute
    return [{json: {error: 'Rate limit: wait 1 minute between runs'}}];
  }

  staticData.lastRun = now;
  staticData.runCount++;
}

return [{json: {allowed: true, totalRuns: staticData.runCount}}];
// Use Case 2: Tracking last processed ID
const staticData = $getWorkflowStaticData();
const currentItems = $input.all();

// Get last processed ID
const lastId = staticData.lastProcessedId || 0;

// Filter only new items
const newItems = currentItems.filter(item => item.json.id > lastId);

// Update last processed ID
if (newItems.length > 0) {
  staticData.lastProcessedId = Math.max(...newItems.map(item => item.json.id));
}

return newItems;
// Use Case 3: Accumulating results
const staticData = $getWorkflowStaticData();

if (!staticData.accumulated) {
  staticData.accumulated = [];
}

// Add current items to accumulated list
const currentData = $input.all().map(item => item.json);
staticData.accumulated.push(...currentData);

return [{
  json: {
    currentBatch: currentData.length,
    totalAccumulated: staticData.accumulated.length,
    allData: staticData.accumulated
  }
}];

5. Standard JavaScript Globals

Math Object
return [{
  json: {
    // Rounding
    rounded: Math.round(3.7),  // 4
    floor: Math.floor(3.7),  // 3
    ceil: Math.ceil(3.2),  // 4

    // Min/Max
    max: Math.max(1, 5, 3, 9, 2),  // 9
    min: Math.min(1, 5, 3, 9, 2),  // 1

    // Random
    random: Math.random(),  // 0-1
    randomInt: Math.floor(Math.random() * 100),  // 0-99

    // Other
    abs: Math.abs(-5),  // 5
    sqrt: Math.sqrt(16),  // 4
    pow: Math.pow(2, 3)  // 8
  }
}];
JSON Object
// Parse JSON string
const jsonString = '{"name": "John", "age": 30}';
const parsed = JSON.parse(jsonString);

// Stringify object
const obj = {name: "John", age: 30};
const stringified = JSON.stringify(obj);

// Pretty print
const pretty = JSON.stringify(obj, null, 2);

return [{json: {parsed, stringified, pretty}}];
console Object
// Debug logging (appears in browser console, press F12)
console.log('Processing items:', $input.all().length);
console.log('First item:', $input.first().json);

// Other console methods
console.error('Error message');
console.warn('Warning message');
console.info('Info message');

// Continues to return data
return [{json: {processed: true}}];
Object Methods
const obj = {name: "John", age: 30, city: "NYC"};

return [{
  json: {
    keys: Object.keys(obj),  // ["name", "age", "city"]
    values: Object.values(obj),  // ["John", 30, "NYC"]
    entries: Object.entries(obj),  // [["name", "John"], ...]

    // Check property
    hasName: 'name' in obj,  // true

    // Merge objects
    merged: Object.assign({}, obj, {country: "USA"})
  }
}];
Array Methods
const arr = [1, 2, 3, 4, 5];

return [{
  json: {
    mapped: arr.map(x => x * 2),  // [2, 4, 6, 8, 10]
    filtered: arr.filter(x => x > 2),  // [3, 4, 5]
    reduced: arr.reduce((sum, x) => sum + x, 0),  // 15
    some: arr.some(x => x > 3),  // true
    every: arr.every(x => x > 0),  // true
    find: arr.find(x => x > 3),  // 4
    includes: arr.includes(3),  // true
    joined: arr.join(', ')  // "1, 2, 3, 4, 5"
  }
}];

6. Available Node.js Modules

crypto Module

Gated: require('crypto') only works if N8N_RUNNERS_ALLOWED_BUILT_IN_MODULES (or legacy NODE_FUNCTION_ALLOW_BUILTIN) includes crypto (or is *). On default installs it throws "Cannot find module 'crypto'". For hashing, HMAC, signing or UUIDs use the Crypto node instead (typeVersion 2; HMAC and signing secrets come from a crypto credential) — no allowlist needed. Use require('crypto') only for what the Crypto node can't do, and only after confirming the instance allows it.

const crypto = require('crypto');

// Hash functions
const hash = crypto.createHash('sha256')
  .update('my secret text')
  .digest('hex');

// MD5 hash
const md5 = crypto.createHash('md5')
  .update('my text')
  .digest('hex');

// Random values
const randomBytes = crypto.randomBytes(16).toString('hex');

return [{json: {hash, md5, randomBytes}}];
Buffer (built-in)
// Base64 encoding
const encoded = Buffer.from('Hello World').toString('base64');

// Base64 decoding
const decoded = Buffer.from(encoded, 'base64').toString();

// Hex encoding
const hex = Buffer.from('Hello').toString('hex');

return [{json: {encoded, decoded, hex}}];
URL / URLSearchParams
// Parse URL
const url = new URL('https://example.com/path?param1=value1&param2=value2');

// Build query string
const params = new URLSearchParams({
  search: 'query',
  page: 1,
  limit: 10
});

return [{
  json: {
    host: url.host,
    pathname: url.pathname,
    search: url.search,
    queryString: params.toString()  // "search=query&page=1&limit=10"
  }
}];

What's NOT Available

External npm packages are NOT available (unless explicitly allowlisted via N8N_RUNNERS_ALLOWED_EXTERNAL_MODULES and installed in the runner image — rare):

  • ❌ axios

  • ❌ lodash

  • ❌ moment (use DateTime/Luxon instead)

  • ❌ request

  • ❌ Any other npm package

Authentication helpers are blocked in the task runner sandbox (see section 0):

  • ❌ this.helpers.httpRequestWithAuthentication

  • ❌ this.helpers.requestWithAuthenticationPaginated

Conditionally blocked (depends on instance config):

  • ⚠️ $env.* — blocked when N8N_BLOCK_ENV_ACCESS_IN_NODE=true

  • ⚠️ require('crypto') / require('fs') / etc. — blocked unless N8N_RUNNERS_ALLOWED_BUILT_IN_MODULES includes them

Workarounds:

  • HTTP with auth → HTTP Request node with credential attached, or sub-workflow pattern

  • Secrets → arrive as data from an upstream HTTP Request / credential-aware node

  • Hashing/crypto → the Crypto node (hash, HMAC, sign, UUID), no allowlist needed


Summary

Most Useful Built-ins:

  1. this.helpers.httpRequest() - API calls inside Code logic; a plain call belongs in the HTTP Request node (the bare $helpers global is undefined)

  2. DateTime - Professional date/time handling

  3. $jmespath() - Complex JSON queries

  4. Math, JSON, Object, Array - Standard JavaScript utilities

Common Patterns:

  • API calls: Use this.helpers.httpRequest() (or, preferably, the HTTP Request node)

  • Date operations: Use DateTime (Luxon)

  • Data filtering: a Filter node before the Code node; inside Code, $jmespath() or .filter()

  • Persistent data: Use $getWorkflowStaticData()

  • Hashing: the Crypto node; require('crypto') only if allowlisted

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 or Romuald Czlonkowski.

Download ZIP

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